VirtualBox

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

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

Main/Machine: implement IMachine::readLog, and fix log file deletion when a VM is deleted. Hardcoding the log file count is bad, we have the system property for a long time.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 363.5 KB
Line 
1/* $Id: MachineImpl.cpp 28194 2010-04-12 09:58:53Z 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 ULONG uLogHistoryCount = 3;
3757 ComPtr<ISystemProperties> systemProperties;
3758 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
3759 if (!systemProperties.isNull())
3760 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
3761
3762 /* delete the settings only when the file actually exists */
3763 if (mData->pMachineConfigFile->fileExists())
3764 {
3765 int vrc = RTFileDelete(mData->m_strConfigFileFull.c_str());
3766 if (RT_FAILURE(vrc))
3767 return setError(VBOX_E_IPRT_ERROR,
3768 tr("Could not delete the settings file '%s' (%Rrc)"),
3769 mData->m_strConfigFileFull.raw(),
3770 vrc);
3771
3772 /* delete the Logs folder, nothing important should be left
3773 * there (we don't check for errors because the user might have
3774 * some private files there that we don't want to delete) */
3775 Utf8Str logFolder;
3776 getLogFolder(logFolder);
3777 Assert(logFolder.length());
3778 if (RTDirExists(logFolder.c_str()))
3779 {
3780 /* Delete all VBox.log[.N] files from the Logs folder
3781 * (this must be in sync with the rotation logic in
3782 * Console::powerUpThread()). Also, delete the VBox.png[.N]
3783 * files that may have been created by the GUI. */
3784 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
3785 logFolder.raw(), RTPATH_DELIMITER);
3786 RTFileDelete(log.c_str());
3787 log = Utf8StrFmt("%s%cVBox.png",
3788 logFolder.raw(), RTPATH_DELIMITER);
3789 RTFileDelete(log.c_str());
3790 for (int i = uLogHistoryCount; i > 0; i--)
3791 {
3792 log = Utf8StrFmt("%s%cVBox.log.%d",
3793 logFolder.raw(), RTPATH_DELIMITER, i);
3794 RTFileDelete(log.c_str());
3795 log = Utf8StrFmt("%s%cVBox.png.%d",
3796 logFolder.raw(), RTPATH_DELIMITER, i);
3797 RTFileDelete(log.c_str());
3798 }
3799
3800 RTDirRemove(logFolder.c_str());
3801 }
3802
3803 /* delete the Snapshots folder, nothing important should be left
3804 * there (we don't check for errors because the user might have
3805 * some private files there that we don't want to delete) */
3806 Utf8Str snapshotFolder(mUserData->mSnapshotFolderFull);
3807 Assert(snapshotFolder.length());
3808 if (RTDirExists(snapshotFolder.c_str()))
3809 RTDirRemove(snapshotFolder.c_str());
3810
3811 /* delete the directory that contains the settings file, but only
3812 * if it matches the VM name (i.e. a structure created by default in
3813 * prepareSaveSettings()) */
3814 {
3815 Utf8Str settingsDir;
3816 if (isInOwnDir(&settingsDir))
3817 RTDirRemove(settingsDir.c_str());
3818 }
3819 }
3820
3821 return S_OK;
3822}
3823
3824STDMETHODIMP Machine::GetSnapshot(IN_BSTR aId, ISnapshot **aSnapshot)
3825{
3826 CheckComArgOutPointerValid(aSnapshot);
3827
3828 AutoCaller autoCaller(this);
3829 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3830
3831 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3832
3833 Guid uuid(aId);
3834 /* Todo: fix this properly by perhaps introducing an isValid method for the Guid class */
3835 if ( (aId)
3836 && (*aId != '\0') // an empty Bstr means "get root snapshot", so don't fail on that
3837 && (uuid.isEmpty()))
3838 {
3839 RTUUID uuidTemp;
3840 /* Either it's a null UUID or the conversion failed. (null uuid has a special meaning in findSnapshot) */
3841 if (RT_FAILURE(RTUuidFromUtf16(&uuidTemp, aId)))
3842 return setError(E_FAIL,
3843 tr("Could not find a snapshot with UUID {%ls}"),
3844 aId);
3845 }
3846
3847 ComObjPtr<Snapshot> snapshot;
3848
3849 HRESULT rc = findSnapshot(uuid, snapshot, true /* aSetError */);
3850 snapshot.queryInterfaceTo(aSnapshot);
3851
3852 return rc;
3853}
3854
3855STDMETHODIMP Machine::FindSnapshot(IN_BSTR aName, ISnapshot **aSnapshot)
3856{
3857 CheckComArgStrNotEmptyOrNull(aName);
3858 CheckComArgOutPointerValid(aSnapshot);
3859
3860 AutoCaller autoCaller(this);
3861 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3862
3863 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3864
3865 ComObjPtr<Snapshot> snapshot;
3866
3867 HRESULT rc = findSnapshot(aName, snapshot, true /* aSetError */);
3868 snapshot.queryInterfaceTo(aSnapshot);
3869
3870 return rc;
3871}
3872
3873STDMETHODIMP Machine::SetCurrentSnapshot(IN_BSTR /* aId */)
3874{
3875 /// @todo (dmik) don't forget to set
3876 // mData->mCurrentStateModified to FALSE
3877
3878 return setError(E_NOTIMPL, "Not implemented");
3879}
3880
3881STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable)
3882{
3883 CheckComArgStrNotEmptyOrNull(aName);
3884 CheckComArgStrNotEmptyOrNull(aHostPath);
3885
3886 AutoCaller autoCaller(this);
3887 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3888
3889 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3890
3891 HRESULT rc = checkStateDependency(MutableStateDep);
3892 if (FAILED(rc)) return rc;
3893
3894 ComObjPtr<SharedFolder> sharedFolder;
3895 rc = findSharedFolder(aName, sharedFolder, false /* aSetError */);
3896 if (SUCCEEDED(rc))
3897 return setError(VBOX_E_OBJECT_IN_USE,
3898 tr("Shared folder named '%ls' already exists"),
3899 aName);
3900
3901 sharedFolder.createObject();
3902 rc = sharedFolder->init(getMachine(), aName, aHostPath, aWritable);
3903 if (FAILED(rc)) return rc;
3904
3905 setModified(IsModified_SharedFolders);
3906 mHWData.backup();
3907 mHWData->mSharedFolders.push_back(sharedFolder);
3908
3909 /* inform the direct session if any */
3910 alock.leave();
3911 onSharedFolderChange();
3912
3913 return S_OK;
3914}
3915
3916STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
3917{
3918 CheckComArgStrNotEmptyOrNull(aName);
3919
3920 AutoCaller autoCaller(this);
3921 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3922
3923 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3924
3925 HRESULT rc = checkStateDependency(MutableStateDep);
3926 if (FAILED(rc)) return rc;
3927
3928 ComObjPtr<SharedFolder> sharedFolder;
3929 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
3930 if (FAILED(rc)) return rc;
3931
3932 setModified(IsModified_SharedFolders);
3933 mHWData.backup();
3934 mHWData->mSharedFolders.remove(sharedFolder);
3935
3936 /* inform the direct session if any */
3937 alock.leave();
3938 onSharedFolderChange();
3939
3940 return S_OK;
3941}
3942
3943STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
3944{
3945 CheckComArgOutPointerValid(aCanShow);
3946
3947 /* start with No */
3948 *aCanShow = FALSE;
3949
3950 AutoCaller autoCaller(this);
3951 AssertComRCReturnRC(autoCaller.rc());
3952
3953 ComPtr<IInternalSessionControl> directControl;
3954 {
3955 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3956
3957 if (mData->mSession.mState != SessionState_Open)
3958 return setError(VBOX_E_INVALID_VM_STATE,
3959 tr("Machine session is not open (session state: %s)"),
3960 Global::stringifySessionState(mData->mSession.mState));
3961
3962 directControl = mData->mSession.mDirectControl;
3963 }
3964
3965 /* ignore calls made after #OnSessionEnd() is called */
3966 if (!directControl)
3967 return S_OK;
3968
3969 ULONG64 dummy;
3970 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
3971}
3972
3973STDMETHODIMP Machine::ShowConsoleWindow(ULONG64 *aWinId)
3974{
3975 CheckComArgOutPointerValid(aWinId);
3976
3977 AutoCaller autoCaller(this);
3978 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3979
3980 ComPtr<IInternalSessionControl> directControl;
3981 {
3982 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3983
3984 if (mData->mSession.mState != SessionState_Open)
3985 return setError(E_FAIL,
3986 tr("Machine session is not open (session state: %s)"),
3987 Global::stringifySessionState(mData->mSession.mState));
3988
3989 directControl = mData->mSession.mDirectControl;
3990 }
3991
3992 /* ignore calls made after #OnSessionEnd() is called */
3993 if (!directControl)
3994 return S_OK;
3995
3996 BOOL dummy;
3997 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
3998}
3999
4000#ifdef VBOX_WITH_GUEST_PROPS
4001/**
4002 * Look up a guest property in VBoxSVC's internal structures.
4003 */
4004HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4005 BSTR *aValue,
4006 ULONG64 *aTimestamp,
4007 BSTR *aFlags)
4008{
4009 using namespace guestProp;
4010
4011 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4012 Utf8Str strName(aName);
4013 HWData::GuestPropertyList::const_iterator it;
4014
4015 for (it = mHWData->mGuestProperties.begin();
4016 it != mHWData->mGuestProperties.end(); ++it)
4017 {
4018 if (it->strName == strName)
4019 {
4020 char szFlags[MAX_FLAGS_LEN + 1];
4021 it->strValue.cloneTo(aValue);
4022 *aTimestamp = it->mTimestamp;
4023 writeFlags(it->mFlags, szFlags);
4024 Bstr(szFlags).cloneTo(aFlags);
4025 break;
4026 }
4027 }
4028 return S_OK;
4029}
4030
4031/**
4032 * Query the VM that a guest property belongs to for the property.
4033 * @returns E_ACCESSDENIED if the VM process is not available or not
4034 * currently handling queries and the lookup should then be done in
4035 * VBoxSVC.
4036 */
4037HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4038 BSTR *aValue,
4039 ULONG64 *aTimestamp,
4040 BSTR *aFlags)
4041{
4042 HRESULT rc;
4043 ComPtr<IInternalSessionControl> directControl;
4044 directControl = mData->mSession.mDirectControl;
4045
4046 /* fail if we were called after #OnSessionEnd() is called. This is a
4047 * silly race condition. */
4048
4049 if (!directControl)
4050 rc = E_ACCESSDENIED;
4051 else
4052 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4053 false /* isSetter */,
4054 aValue, aTimestamp, aFlags);
4055 return rc;
4056}
4057#endif // VBOX_WITH_GUEST_PROPS
4058
4059STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4060 BSTR *aValue,
4061 ULONG64 *aTimestamp,
4062 BSTR *aFlags)
4063{
4064#ifndef VBOX_WITH_GUEST_PROPS
4065 ReturnComNotImplemented();
4066#else // VBOX_WITH_GUEST_PROPS
4067 CheckComArgStrNotEmptyOrNull(aName);
4068 CheckComArgOutPointerValid(aValue);
4069 CheckComArgOutPointerValid(aTimestamp);
4070 CheckComArgOutPointerValid(aFlags);
4071
4072 AutoCaller autoCaller(this);
4073 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4074
4075 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4076 if (rc == E_ACCESSDENIED)
4077 /* The VM is not running or the service is not (yet) accessible */
4078 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4079 return rc;
4080#endif // VBOX_WITH_GUEST_PROPS
4081}
4082
4083STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4084{
4085 ULONG64 dummyTimestamp;
4086 BSTR dummyFlags;
4087 return GetGuestProperty(aName, aValue, &dummyTimestamp, &dummyFlags);
4088}
4089
4090STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, ULONG64 *aTimestamp)
4091{
4092 BSTR dummyValue;
4093 BSTR dummyFlags;
4094 return GetGuestProperty(aName, &dummyValue, aTimestamp, &dummyFlags);
4095}
4096
4097#ifdef VBOX_WITH_GUEST_PROPS
4098/**
4099 * Set a guest property in VBoxSVC's internal structures.
4100 */
4101HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4102 IN_BSTR aFlags)
4103{
4104 using namespace guestProp;
4105
4106 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4107 HRESULT rc = S_OK;
4108 HWData::GuestProperty property;
4109 property.mFlags = NILFLAG;
4110 bool found = false;
4111
4112 rc = checkStateDependency(MutableStateDep);
4113 if (FAILED(rc)) return rc;
4114
4115 try
4116 {
4117 Utf8Str utf8Name(aName);
4118 Utf8Str utf8Flags(aFlags);
4119 uint32_t fFlags = NILFLAG;
4120 if ( (aFlags != NULL)
4121 && RT_FAILURE(validateFlags(utf8Flags.raw(), &fFlags))
4122 )
4123 return setError(E_INVALIDARG,
4124 tr("Invalid flag values: '%ls'"),
4125 aFlags);
4126
4127 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
4128 * know, this is simple and do an OK job atm.) */
4129 HWData::GuestPropertyList::iterator it;
4130 for (it = mHWData->mGuestProperties.begin();
4131 it != mHWData->mGuestProperties.end(); ++it)
4132 if (it->strName == utf8Name)
4133 {
4134 property = *it;
4135 if (it->mFlags & (RDONLYHOST))
4136 rc = setError(E_ACCESSDENIED,
4137 tr("The property '%ls' cannot be changed by the host"),
4138 aName);
4139 else
4140 {
4141 setModified(IsModified_MachineData);
4142 mHWData.backup(); // @todo r=dj backup in a loop?!?
4143
4144 /* The backup() operation invalidates our iterator, so
4145 * get a new one. */
4146 for (it = mHWData->mGuestProperties.begin();
4147 it->strName != utf8Name;
4148 ++it)
4149 ;
4150 mHWData->mGuestProperties.erase(it);
4151 }
4152 found = true;
4153 break;
4154 }
4155 if (found && SUCCEEDED(rc))
4156 {
4157 if (*aValue)
4158 {
4159 RTTIMESPEC time;
4160 property.strValue = aValue;
4161 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4162 if (aFlags != NULL)
4163 property.mFlags = fFlags;
4164 mHWData->mGuestProperties.push_back(property);
4165 }
4166 }
4167 else if (SUCCEEDED(rc) && *aValue)
4168 {
4169 RTTIMESPEC time;
4170 setModified(IsModified_MachineData);
4171 mHWData.backup();
4172 property.strName = aName;
4173 property.strValue = aValue;
4174 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4175 property.mFlags = fFlags;
4176 mHWData->mGuestProperties.push_back(property);
4177 }
4178 if ( SUCCEEDED(rc)
4179 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
4180 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(), RTSTR_MAX,
4181 utf8Name.raw(), RTSTR_MAX, NULL) )
4182 )
4183 {
4184 /** @todo r=bird: Why aren't we leaving the lock here? The
4185 * same code in PushGuestProperty does... */
4186 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
4187 }
4188 }
4189 catch (std::bad_alloc &)
4190 {
4191 rc = E_OUTOFMEMORY;
4192 }
4193
4194 return rc;
4195}
4196
4197/**
4198 * Set a property on the VM that that property belongs to.
4199 * @returns E_ACCESSDENIED if the VM process is not available or not
4200 * currently handling queries and the setting should then be done in
4201 * VBoxSVC.
4202 */
4203HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
4204 IN_BSTR aFlags)
4205{
4206 HRESULT rc;
4207
4208 try {
4209 ComPtr<IInternalSessionControl> directControl =
4210 mData->mSession.mDirectControl;
4211
4212 BSTR dummy = NULL;
4213 ULONG64 dummy64;
4214 if (!directControl)
4215 rc = E_ACCESSDENIED;
4216 else
4217 rc = directControl->AccessGuestProperty
4218 (aName,
4219 /** @todo Fix when adding DeleteGuestProperty(),
4220 see defect. */
4221 *aValue ? aValue : NULL, aFlags, true /* isSetter */,
4222 &dummy, &dummy64, &dummy);
4223 }
4224 catch (std::bad_alloc &)
4225 {
4226 rc = E_OUTOFMEMORY;
4227 }
4228
4229 return rc;
4230}
4231#endif // VBOX_WITH_GUEST_PROPS
4232
4233STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
4234 IN_BSTR aFlags)
4235{
4236#ifndef VBOX_WITH_GUEST_PROPS
4237 ReturnComNotImplemented();
4238#else // VBOX_WITH_GUEST_PROPS
4239 CheckComArgStrNotEmptyOrNull(aName);
4240 if ((aFlags != NULL) && !VALID_PTR(aFlags))
4241 return E_INVALIDARG;
4242 AutoCaller autoCaller(this);
4243 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4244
4245 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
4246 if (rc == E_ACCESSDENIED)
4247 /* The VM is not running or the service is not (yet) accessible */
4248 rc = setGuestPropertyToService(aName, aValue, aFlags);
4249 return rc;
4250#endif // VBOX_WITH_GUEST_PROPS
4251}
4252
4253STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
4254{
4255 return SetGuestProperty(aName, aValue, NULL);
4256}
4257
4258#ifdef VBOX_WITH_GUEST_PROPS
4259/**
4260 * Enumerate the guest properties in VBoxSVC's internal structures.
4261 */
4262HRESULT Machine::enumerateGuestPropertiesInService
4263 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4264 ComSafeArrayOut(BSTR, aValues),
4265 ComSafeArrayOut(ULONG64, aTimestamps),
4266 ComSafeArrayOut(BSTR, aFlags))
4267{
4268 using namespace guestProp;
4269
4270 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4271 Utf8Str strPatterns(aPatterns);
4272
4273 /*
4274 * Look for matching patterns and build up a list.
4275 */
4276 HWData::GuestPropertyList propList;
4277 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
4278 it != mHWData->mGuestProperties.end();
4279 ++it)
4280 if ( strPatterns.isEmpty()
4281 || RTStrSimplePatternMultiMatch(strPatterns.raw(),
4282 RTSTR_MAX,
4283 it->strName.raw(),
4284 RTSTR_MAX, NULL)
4285 )
4286 propList.push_back(*it);
4287
4288 /*
4289 * And build up the arrays for returning the property information.
4290 */
4291 size_t cEntries = propList.size();
4292 SafeArray<BSTR> names(cEntries);
4293 SafeArray<BSTR> values(cEntries);
4294 SafeArray<ULONG64> timestamps(cEntries);
4295 SafeArray<BSTR> flags(cEntries);
4296 size_t iProp = 0;
4297 for (HWData::GuestPropertyList::iterator it = propList.begin();
4298 it != propList.end();
4299 ++it)
4300 {
4301 char szFlags[MAX_FLAGS_LEN + 1];
4302 it->strName.cloneTo(&names[iProp]);
4303 it->strValue.cloneTo(&values[iProp]);
4304 timestamps[iProp] = it->mTimestamp;
4305 writeFlags(it->mFlags, szFlags);
4306 Bstr(szFlags).cloneTo(&flags[iProp]);
4307 ++iProp;
4308 }
4309 names.detachTo(ComSafeArrayOutArg(aNames));
4310 values.detachTo(ComSafeArrayOutArg(aValues));
4311 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
4312 flags.detachTo(ComSafeArrayOutArg(aFlags));
4313 return S_OK;
4314}
4315
4316/**
4317 * Enumerate the properties managed by a VM.
4318 * @returns E_ACCESSDENIED if the VM process is not available or not
4319 * currently handling queries and the setting should then be done in
4320 * VBoxSVC.
4321 */
4322HRESULT Machine::enumerateGuestPropertiesOnVM
4323 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4324 ComSafeArrayOut(BSTR, aValues),
4325 ComSafeArrayOut(ULONG64, aTimestamps),
4326 ComSafeArrayOut(BSTR, aFlags))
4327{
4328 HRESULT rc;
4329 ComPtr<IInternalSessionControl> directControl;
4330 directControl = mData->mSession.mDirectControl;
4331
4332 if (!directControl)
4333 rc = E_ACCESSDENIED;
4334 else
4335 rc = directControl->EnumerateGuestProperties
4336 (aPatterns, ComSafeArrayOutArg(aNames),
4337 ComSafeArrayOutArg(aValues),
4338 ComSafeArrayOutArg(aTimestamps),
4339 ComSafeArrayOutArg(aFlags));
4340 return rc;
4341}
4342#endif // VBOX_WITH_GUEST_PROPS
4343
4344STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
4345 ComSafeArrayOut(BSTR, aNames),
4346 ComSafeArrayOut(BSTR, aValues),
4347 ComSafeArrayOut(ULONG64, aTimestamps),
4348 ComSafeArrayOut(BSTR, aFlags))
4349{
4350#ifndef VBOX_WITH_GUEST_PROPS
4351 ReturnComNotImplemented();
4352#else // VBOX_WITH_GUEST_PROPS
4353 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
4354 return E_POINTER;
4355
4356 CheckComArgOutSafeArrayPointerValid(aNames);
4357 CheckComArgOutSafeArrayPointerValid(aValues);
4358 CheckComArgOutSafeArrayPointerValid(aTimestamps);
4359 CheckComArgOutSafeArrayPointerValid(aFlags);
4360
4361 AutoCaller autoCaller(this);
4362 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4363
4364 HRESULT rc = enumerateGuestPropertiesOnVM
4365 (aPatterns, ComSafeArrayOutArg(aNames),
4366 ComSafeArrayOutArg(aValues),
4367 ComSafeArrayOutArg(aTimestamps),
4368 ComSafeArrayOutArg(aFlags));
4369 if (rc == E_ACCESSDENIED)
4370 /* The VM is not running or the service is not (yet) accessible */
4371 rc = enumerateGuestPropertiesInService
4372 (aPatterns, ComSafeArrayOutArg(aNames),
4373 ComSafeArrayOutArg(aValues),
4374 ComSafeArrayOutArg(aTimestamps),
4375 ComSafeArrayOutArg(aFlags));
4376 return rc;
4377#endif // VBOX_WITH_GUEST_PROPS
4378}
4379
4380STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
4381 ComSafeArrayOut(IMediumAttachment*, aAttachments))
4382{
4383 MediaData::AttachmentList atts;
4384
4385 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
4386 if (FAILED(rc)) return rc;
4387
4388 SafeIfaceArray<IMediumAttachment> attachments(atts);
4389 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
4390
4391 return S_OK;
4392}
4393
4394STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
4395 LONG aControllerPort,
4396 LONG aDevice,
4397 IMediumAttachment **aAttachment)
4398{
4399 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4400 aControllerName, aControllerPort, aDevice));
4401
4402 CheckComArgStrNotEmptyOrNull(aControllerName);
4403 CheckComArgOutPointerValid(aAttachment);
4404
4405 AutoCaller autoCaller(this);
4406 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4407
4408 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4409
4410 *aAttachment = NULL;
4411
4412 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4413 aControllerName,
4414 aControllerPort,
4415 aDevice);
4416 if (pAttach.isNull())
4417 return setError(VBOX_E_OBJECT_NOT_FOUND,
4418 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4419 aDevice, aControllerPort, aControllerName);
4420
4421 pAttach.queryInterfaceTo(aAttachment);
4422
4423 return S_OK;
4424}
4425
4426STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
4427 StorageBus_T aConnectionType,
4428 IStorageController **controller)
4429{
4430 CheckComArgStrNotEmptyOrNull(aName);
4431
4432 if ( (aConnectionType <= StorageBus_Null)
4433 || (aConnectionType > StorageBus_SAS))
4434 return setError(E_INVALIDARG,
4435 tr("Invalid connection type: %d"),
4436 aConnectionType);
4437
4438 AutoCaller autoCaller(this);
4439 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4440
4441 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4442
4443 HRESULT rc = checkStateDependency(MutableStateDep);
4444 if (FAILED(rc)) return rc;
4445
4446 /* try to find one with the name first. */
4447 ComObjPtr<StorageController> ctrl;
4448
4449 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
4450 if (SUCCEEDED(rc))
4451 return setError(VBOX_E_OBJECT_IN_USE,
4452 tr("Storage controller named '%ls' already exists"),
4453 aName);
4454
4455 ctrl.createObject();
4456
4457 /* get a new instance number for the storage controller */
4458 ULONG ulInstance = 0;
4459 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4460 it != mStorageControllers->end();
4461 ++it)
4462 {
4463 if ((*it)->getStorageBus() == aConnectionType)
4464 {
4465 ULONG ulCurInst = (*it)->getInstance();
4466
4467 if (ulCurInst >= ulInstance)
4468 ulInstance = ulCurInst + 1;
4469 }
4470 }
4471
4472 rc = ctrl->init(this, aName, aConnectionType, ulInstance);
4473 if (FAILED(rc)) return rc;
4474
4475 setModified(IsModified_Storage);
4476 mStorageControllers.backup();
4477 mStorageControllers->push_back(ctrl);
4478
4479 ctrl.queryInterfaceTo(controller);
4480
4481 /* inform the direct session if any */
4482 alock.leave();
4483 onStorageControllerChange();
4484
4485 return S_OK;
4486}
4487
4488STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
4489 IStorageController **aStorageController)
4490{
4491 CheckComArgStrNotEmptyOrNull(aName);
4492
4493 AutoCaller autoCaller(this);
4494 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4495
4496 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4497
4498 ComObjPtr<StorageController> ctrl;
4499
4500 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
4501 if (SUCCEEDED(rc))
4502 ctrl.queryInterfaceTo(aStorageController);
4503
4504 return rc;
4505}
4506
4507STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
4508 IStorageController **aStorageController)
4509{
4510 AutoCaller autoCaller(this);
4511 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4512
4513 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4514
4515 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4516 it != mStorageControllers->end();
4517 ++it)
4518 {
4519 if ((*it)->getInstance() == aInstance)
4520 {
4521 (*it).queryInterfaceTo(aStorageController);
4522 return S_OK;
4523 }
4524 }
4525
4526 return setError(VBOX_E_OBJECT_NOT_FOUND,
4527 tr("Could not find a storage controller with instance number '%lu'"),
4528 aInstance);
4529}
4530
4531STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
4532{
4533 CheckComArgStrNotEmptyOrNull(aName);
4534
4535 AutoCaller autoCaller(this);
4536 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4537
4538 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4539
4540 HRESULT rc = checkStateDependency(MutableStateDep);
4541 if (FAILED(rc)) return rc;
4542
4543 ComObjPtr<StorageController> ctrl;
4544 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
4545 if (FAILED(rc)) return rc;
4546
4547 /* We can remove the controller only if there is no device attached. */
4548 /* check if the device slot is already busy */
4549 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
4550 it != mMediaData->mAttachments.end();
4551 ++it)
4552 {
4553 if ((*it)->getControllerName() == aName)
4554 return setError(VBOX_E_OBJECT_IN_USE,
4555 tr("Storage controller named '%ls' has still devices attached"),
4556 aName);
4557 }
4558
4559 /* We can remove it now. */
4560 setModified(IsModified_Storage);
4561 mStorageControllers.backup();
4562
4563 ctrl->unshare();
4564
4565 mStorageControllers->remove(ctrl);
4566
4567 /* inform the direct session if any */
4568 alock.leave();
4569 onStorageControllerChange();
4570
4571 return S_OK;
4572}
4573
4574/* @todo where is the right place for this? */
4575#define sSSMDisplayScreenshotVer 0x00010001
4576
4577static int readSavedDisplayScreenshot(Utf8Str *pStateFilePath, uint32_t u32Type, uint8_t **ppu8Data, uint32_t *pcbData, uint32_t *pu32Width, uint32_t *pu32Height)
4578{
4579 LogFlowFunc(("u32Type = %d [%s]\n", u32Type, pStateFilePath->raw()));
4580
4581 /* @todo cache read data */
4582 if (pStateFilePath->isEmpty())
4583 {
4584 /* No saved state data. */
4585 return VERR_NOT_SUPPORTED;
4586 }
4587
4588 uint8_t *pu8Data = NULL;
4589 uint32_t cbData = 0;
4590 uint32_t u32Width = 0;
4591 uint32_t u32Height = 0;
4592
4593 PSSMHANDLE pSSM;
4594 int rc = SSMR3Open(pStateFilePath->raw(), 0 /*fFlags*/, &pSSM);
4595 if (RT_SUCCESS(rc))
4596 {
4597 uint32_t uVersion;
4598 rc = SSMR3Seek(pSSM, "DisplayScreenshot", 1100 /*iInstance*/, &uVersion);
4599 if (RT_SUCCESS(rc))
4600 {
4601 if (uVersion == sSSMDisplayScreenshotVer)
4602 {
4603 uint32_t cBlocks;
4604 rc = SSMR3GetU32(pSSM, &cBlocks);
4605 AssertRCReturn(rc, rc);
4606
4607 for (uint32_t i = 0; i < cBlocks; i++)
4608 {
4609 uint32_t cbBlock;
4610 rc = SSMR3GetU32(pSSM, &cbBlock);
4611 AssertRCBreak(rc);
4612
4613 uint32_t typeOfBlock;
4614 rc = SSMR3GetU32(pSSM, &typeOfBlock);
4615 AssertRCBreak(rc);
4616
4617 LogFlowFunc(("[%d] type %d, size %d bytes\n", i, typeOfBlock, cbBlock));
4618
4619 if (typeOfBlock == u32Type)
4620 {
4621 if (cbBlock > 2 * sizeof(uint32_t))
4622 {
4623 cbData = cbBlock - 2 * sizeof(uint32_t);
4624 pu8Data = (uint8_t *)RTMemAlloc(cbData);
4625 if (pu8Data == NULL)
4626 {
4627 rc = VERR_NO_MEMORY;
4628 break;
4629 }
4630
4631 rc = SSMR3GetU32(pSSM, &u32Width);
4632 AssertRCBreak(rc);
4633 rc = SSMR3GetU32(pSSM, &u32Height);
4634 AssertRCBreak(rc);
4635 rc = SSMR3GetMem(pSSM, pu8Data, cbData);
4636 AssertRCBreak(rc);
4637 }
4638 else
4639 {
4640 /* No saved state data. */
4641 rc = VERR_NOT_SUPPORTED;
4642 }
4643
4644 break;
4645 }
4646 else
4647 {
4648 /* displaySSMSaveScreenshot did not write any data, if
4649 * cbBlock was == 2 * sizeof (uint32_t).
4650 */
4651 if (cbBlock > 2 * sizeof (uint32_t))
4652 {
4653 rc = SSMR3Skip(pSSM, cbBlock);
4654 AssertRCBreak(rc);
4655 }
4656 }
4657 }
4658 }
4659 else
4660 {
4661 rc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
4662 }
4663 }
4664
4665 SSMR3Close(pSSM);
4666 }
4667
4668 if (RT_SUCCESS(rc))
4669 {
4670 if (u32Type == 0 && cbData % 4 != 0)
4671 {
4672 /* Bitmap is 32bpp, so data is invalid. */
4673 rc = VERR_SSM_UNEXPECTED_DATA;
4674 }
4675 }
4676
4677 if (RT_SUCCESS(rc))
4678 {
4679 *ppu8Data = pu8Data;
4680 *pcbData = cbData;
4681 *pu32Width = u32Width;
4682 *pu32Height = u32Height;
4683 LogFlowFunc(("cbData %d, u32Width %d, u32Height %d\n", cbData, u32Width, u32Height));
4684 }
4685
4686 LogFlowFunc(("rc %Rrc\n", rc));
4687 return rc;
4688}
4689
4690static void freeSavedDisplayScreenshot(uint8_t *pu8Data)
4691{
4692 /* @todo not necessary when caching is implemented. */
4693 RTMemFree(pu8Data);
4694}
4695
4696STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
4697{
4698 LogFlowThisFunc(("\n"));
4699
4700 CheckComArgNotNull(aSize);
4701 CheckComArgNotNull(aWidth);
4702 CheckComArgNotNull(aHeight);
4703
4704 AutoCaller autoCaller(this);
4705 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4706
4707 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4708
4709 uint8_t *pu8Data = NULL;
4710 uint32_t cbData = 0;
4711 uint32_t u32Width = 0;
4712 uint32_t u32Height = 0;
4713
4714 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4715
4716 if (RT_FAILURE(vrc))
4717 return setError(VBOX_E_IPRT_ERROR,
4718 tr("Saved screenshot data is not available (%Rrc)"),
4719 vrc);
4720
4721 *aSize = cbData;
4722 *aWidth = u32Width;
4723 *aHeight = u32Height;
4724
4725 freeSavedDisplayScreenshot(pu8Data);
4726
4727 return S_OK;
4728}
4729
4730STDMETHODIMP Machine::ReadSavedThumbnailToArray(BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
4731{
4732 LogFlowThisFunc(("\n"));
4733
4734 CheckComArgNotNull(aWidth);
4735 CheckComArgNotNull(aHeight);
4736 CheckComArgOutSafeArrayPointerValid(aData);
4737
4738 AutoCaller autoCaller(this);
4739 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4740
4741 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4742
4743 uint8_t *pu8Data = NULL;
4744 uint32_t cbData = 0;
4745 uint32_t u32Width = 0;
4746 uint32_t u32Height = 0;
4747
4748 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4749
4750 if (RT_FAILURE(vrc))
4751 return setError(VBOX_E_IPRT_ERROR,
4752 tr("Saved screenshot data is not available (%Rrc)"),
4753 vrc);
4754
4755 *aWidth = u32Width;
4756 *aHeight = u32Height;
4757
4758 com::SafeArray<BYTE> bitmap(cbData);
4759 /* Convert pixels to format expected by the API caller. */
4760 if (aBGR)
4761 {
4762 /* [0] B, [1] G, [2] R, [3] A. */
4763 for (unsigned i = 0; i < cbData; i += 4)
4764 {
4765 bitmap[i] = pu8Data[i];
4766 bitmap[i + 1] = pu8Data[i + 1];
4767 bitmap[i + 2] = pu8Data[i + 2];
4768 bitmap[i + 3] = 0xff;
4769 }
4770 }
4771 else
4772 {
4773 /* [0] R, [1] G, [2] B, [3] A. */
4774 for (unsigned i = 0; i < cbData; i += 4)
4775 {
4776 bitmap[i] = pu8Data[i + 2];
4777 bitmap[i + 1] = pu8Data[i + 1];
4778 bitmap[i + 2] = pu8Data[i];
4779 bitmap[i + 3] = 0xff;
4780 }
4781 }
4782 bitmap.detachTo(ComSafeArrayOutArg(aData));
4783
4784 freeSavedDisplayScreenshot(pu8Data);
4785
4786 return S_OK;
4787}
4788
4789STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
4790{
4791 LogFlowThisFunc(("\n"));
4792
4793 CheckComArgNotNull(aSize);
4794 CheckComArgNotNull(aWidth);
4795 CheckComArgNotNull(aHeight);
4796
4797 AutoCaller autoCaller(this);
4798 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4799
4800 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4801
4802 uint8_t *pu8Data = NULL;
4803 uint32_t cbData = 0;
4804 uint32_t u32Width = 0;
4805 uint32_t u32Height = 0;
4806
4807 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4808
4809 if (RT_FAILURE(vrc))
4810 return setError(VBOX_E_IPRT_ERROR,
4811 tr("Saved screenshot data is not available (%Rrc)"),
4812 vrc);
4813
4814 *aSize = cbData;
4815 *aWidth = u32Width;
4816 *aHeight = u32Height;
4817
4818 freeSavedDisplayScreenshot(pu8Data);
4819
4820 return S_OK;
4821}
4822
4823STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
4824{
4825 LogFlowThisFunc(("\n"));
4826
4827 CheckComArgNotNull(aWidth);
4828 CheckComArgNotNull(aHeight);
4829 CheckComArgOutSafeArrayPointerValid(aData);
4830
4831 AutoCaller autoCaller(this);
4832 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4833
4834 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4835
4836 uint8_t *pu8Data = NULL;
4837 uint32_t cbData = 0;
4838 uint32_t u32Width = 0;
4839 uint32_t u32Height = 0;
4840
4841 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4842
4843 if (RT_FAILURE(vrc))
4844 return setError(VBOX_E_IPRT_ERROR,
4845 tr("Saved screenshot data is not available (%Rrc)"),
4846 vrc);
4847
4848 *aWidth = u32Width;
4849 *aHeight = u32Height;
4850
4851 com::SafeArray<BYTE> png(cbData);
4852 for (unsigned i = 0; i < cbData; i++)
4853 png[i] = pu8Data[i];
4854 png.detachTo(ComSafeArrayOutArg(aData));
4855
4856 freeSavedDisplayScreenshot(pu8Data);
4857
4858 return S_OK;
4859}
4860
4861STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
4862{
4863 HRESULT rc = S_OK;
4864 LogFlowThisFunc(("\n"));
4865
4866 AutoCaller autoCaller(this);
4867 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4868
4869 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4870
4871 if (!mHWData->mCPUHotPlugEnabled)
4872 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
4873
4874 if (aCpu >= mHWData->mCPUCount)
4875 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
4876
4877 if (mHWData->mCPUAttached[aCpu])
4878 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
4879
4880 alock.leave();
4881 rc = onCPUChange(aCpu, false);
4882 alock.enter();
4883 if (FAILED(rc)) return rc;
4884
4885 setModified(IsModified_MachineData);
4886 mHWData.backup();
4887 mHWData->mCPUAttached[aCpu] = true;
4888
4889 /* Save settings if online */
4890 if (Global::IsOnline(mData->mMachineState))
4891 SaveSettings();
4892
4893 return S_OK;
4894}
4895
4896STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
4897{
4898 HRESULT rc = S_OK;
4899 LogFlowThisFunc(("\n"));
4900
4901 AutoCaller autoCaller(this);
4902 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4903
4904 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4905
4906 if (!mHWData->mCPUHotPlugEnabled)
4907 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
4908
4909 if (aCpu >= SchemaDefs::MaxCPUCount)
4910 return setError(E_INVALIDARG,
4911 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
4912 SchemaDefs::MaxCPUCount);
4913
4914 if (!mHWData->mCPUAttached[aCpu])
4915 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
4916
4917 /* CPU 0 can't be detached */
4918 if (aCpu == 0)
4919 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
4920
4921 alock.leave();
4922 rc = onCPUChange(aCpu, true);
4923 alock.enter();
4924 if (FAILED(rc)) return rc;
4925
4926 setModified(IsModified_MachineData);
4927 mHWData.backup();
4928 mHWData->mCPUAttached[aCpu] = false;
4929
4930 /* Save settings if online */
4931 if (Global::IsOnline(mData->mMachineState))
4932 SaveSettings();
4933
4934 return S_OK;
4935}
4936
4937STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
4938{
4939 LogFlowThisFunc(("\n"));
4940
4941 CheckComArgNotNull(aCpuAttached);
4942
4943 *aCpuAttached = false;
4944
4945 AutoCaller autoCaller(this);
4946 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4947
4948 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4949
4950 /* If hotplug is enabled the CPU is always enabled. */
4951 if (!mHWData->mCPUHotPlugEnabled)
4952 {
4953 if (aCpu < mHWData->mCPUCount)
4954 *aCpuAttached = true;
4955 }
4956 else
4957 {
4958 if (aCpu < SchemaDefs::MaxCPUCount)
4959 *aCpuAttached = mHWData->mCPUAttached[aCpu];
4960 }
4961
4962 return S_OK;
4963}
4964
4965STDMETHODIMP Machine::ReadLog(ULONG aIdx, ULONG64 aOffset, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
4966{
4967 LogFlowThisFunc(("\n"));
4968 CheckComArgOutSafeArrayPointerValid(aData);
4969
4970 AutoCaller autoCaller(this);
4971 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4972
4973 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4974
4975 HRESULT rc = S_OK;
4976 Utf8Str logFolder;
4977 getLogFolder(logFolder);
4978 Assert(logFolder.length());
4979 ULONG uLogHistoryCount = 3;
4980 ComPtr<ISystemProperties> systemProperties;
4981 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4982 if (!systemProperties.isNull())
4983 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4984 Utf8Str log;
4985 if (aIdx == 0)
4986 log = Utf8StrFmt("%s%cVBox.log",
4987 logFolder.raw(), RTPATH_DELIMITER);
4988 else
4989 log = Utf8StrFmt("%s%cVBox.log.%d",
4990 logFolder.raw(), RTPATH_DELIMITER, aIdx);
4991
4992 size_t cbData = (size_t)RT_MIN(aSize, 2048);
4993 com::SafeArray<BYTE> logData(cbData);
4994
4995 RTFILE LogFile;
4996 int vrc = RTFileOpen(&LogFile, log.raw(),
4997 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
4998 if (RT_SUCCESS(vrc))
4999 {
5000 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5001 if (RT_SUCCESS(vrc))
5002 logData.resize(cbData);
5003 else
5004 rc = setError(VBOX_E_IPRT_ERROR,
5005 tr("Could not read log file '%s' (%Rrc)"),
5006 log.raw(), vrc);
5007 }
5008 else
5009 rc = setError(VBOX_E_IPRT_ERROR,
5010 tr("Could not open log file '%s' (%Rrc)"),
5011 log.raw(), vrc);
5012
5013 if (FAILED(rc))
5014 logData.resize(0);
5015 logData.detachTo(ComSafeArrayOutArg(aData));
5016
5017 return rc;
5018}
5019
5020
5021// public methods for internal purposes
5022/////////////////////////////////////////////////////////////////////////////
5023
5024/**
5025 * Adds the given IsModified_* flag to the dirty flags of the machine.
5026 * This must be called either during loadSettings or under the machine write lock.
5027 * @param fl
5028 */
5029void Machine::setModified(uint32_t fl)
5030{
5031 mData->flModifications |= fl;
5032}
5033
5034/**
5035 * Saves the registry entry of this machine to the given configuration node.
5036 *
5037 * @param aEntryNode Node to save the registry entry to.
5038 *
5039 * @note locks this object for reading.
5040 */
5041HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5042{
5043 AutoLimitedCaller autoCaller(this);
5044 AssertComRCReturnRC(autoCaller.rc());
5045
5046 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5047
5048 data.uuid = mData->mUuid;
5049 data.strSettingsFile = mData->m_strConfigFile;
5050
5051 return S_OK;
5052}
5053
5054/**
5055 * Calculates the absolute path of the given path taking the directory of the
5056 * machine settings file as the current directory.
5057 *
5058 * @param aPath Path to calculate the absolute path for.
5059 * @param aResult Where to put the result (used only on success, can be the
5060 * same Utf8Str instance as passed in @a aPath).
5061 * @return IPRT result.
5062 *
5063 * @note Locks this object for reading.
5064 */
5065int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5066{
5067 AutoCaller autoCaller(this);
5068 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5069
5070 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5071
5072 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5073
5074 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5075
5076 strSettingsDir.stripFilename();
5077 char folder[RTPATH_MAX];
5078 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5079 if (RT_SUCCESS(vrc))
5080 aResult = folder;
5081
5082 return vrc;
5083}
5084
5085/**
5086 * Tries to calculate the relative path of the given absolute path using the
5087 * directory of the machine settings file as the base directory.
5088 *
5089 * @param aPath Absolute path to calculate the relative path for.
5090 * @param aResult Where to put the result (used only when it's possible to
5091 * make a relative path from the given absolute path; otherwise
5092 * left untouched).
5093 *
5094 * @note Locks this object for reading.
5095 */
5096void Machine::calculateRelativePath(const Utf8Str &strPath, Utf8Str &aResult)
5097{
5098 AutoCaller autoCaller(this);
5099 AssertComRCReturn(autoCaller.rc(), (void)0);
5100
5101 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5102
5103 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5104
5105 Utf8Str settingsDir = mData->m_strConfigFileFull;
5106
5107 settingsDir.stripFilename();
5108 if (RTPathStartsWith(strPath.c_str(), settingsDir.c_str()))
5109 {
5110 /* when assigning, we create a separate Utf8Str instance because both
5111 * aPath and aResult can point to the same memory location when this
5112 * func is called (if we just do aResult = aPath, aResult will be freed
5113 * first, and since its the same as aPath, an attempt to copy garbage
5114 * will be made. */
5115 aResult = Utf8Str(strPath.c_str() + settingsDir.length() + 1);
5116 }
5117}
5118
5119/**
5120 * Returns the full path to the machine's log folder in the
5121 * \a aLogFolder argument.
5122 */
5123void Machine::getLogFolder(Utf8Str &aLogFolder)
5124{
5125 AutoCaller autoCaller(this);
5126 AssertComRCReturnVoid(autoCaller.rc());
5127
5128 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5129
5130 Utf8Str settingsDir;
5131 if (isInOwnDir(&settingsDir))
5132 {
5133 /* Log folder is <Machines>/<VM_Name>/Logs */
5134 aLogFolder = Utf8StrFmt("%s%cLogs", settingsDir.raw(), RTPATH_DELIMITER);
5135 }
5136 else
5137 {
5138 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5139 Assert(!mUserData->mSnapshotFolderFull.isEmpty());
5140 aLogFolder = Utf8StrFmt ("%ls%cLogs", mUserData->mSnapshotFolderFull.raw(),
5141 RTPATH_DELIMITER);
5142 }
5143}
5144
5145/**
5146 * @note Locks this object for writing, calls the client process (outside the
5147 * lock).
5148 */
5149HRESULT Machine::openSession(IInternalSessionControl *aControl)
5150{
5151 LogFlowThisFuncEnter();
5152
5153 AssertReturn(aControl, E_FAIL);
5154
5155 AutoCaller autoCaller(this);
5156 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5157
5158 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5159
5160 if (!mData->mRegistered)
5161 return setError(E_UNEXPECTED,
5162 tr("The machine '%ls' is not registered"),
5163 mUserData->mName.raw());
5164
5165 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5166
5167 /* Hack: in case the session is closing and there is a progress object
5168 * which allows waiting for the session to be closed, take the opportunity
5169 * and do a limited wait (max. 1 second). This helps a lot when the system
5170 * is busy and thus session closing can take a little while. */
5171 if ( mData->mSession.mState == SessionState_Closing
5172 && mData->mSession.mProgress)
5173 {
5174 alock.leave();
5175 mData->mSession.mProgress->WaitForCompletion(1000);
5176 alock.enter();
5177 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5178 }
5179
5180 if (mData->mSession.mState == SessionState_Open ||
5181 mData->mSession.mState == SessionState_Closing)
5182 return setError(VBOX_E_INVALID_OBJECT_STATE,
5183 tr("A session for the machine '%ls' is currently open (or being closed)"),
5184 mUserData->mName.raw());
5185
5186 /* may not be busy */
5187 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5188
5189 /* get the session PID */
5190 RTPROCESS pid = NIL_RTPROCESS;
5191 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
5192 aControl->GetPID((ULONG *) &pid);
5193 Assert(pid != NIL_RTPROCESS);
5194
5195 if (mData->mSession.mState == SessionState_Spawning)
5196 {
5197 /* This machine is awaiting for a spawning session to be opened, so
5198 * reject any other open attempts from processes other than one
5199 * started by #openRemoteSession(). */
5200
5201 LogFlowThisFunc(("mSession.mPid=%d(0x%x)\n",
5202 mData->mSession.mPid, mData->mSession.mPid));
5203 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
5204
5205 if (mData->mSession.mPid != pid)
5206 return setError(E_ACCESSDENIED,
5207 tr("An unexpected process (PID=0x%08X) has tried to open a direct "
5208 "session with the machine named '%ls', while only a process "
5209 "started by OpenRemoteSession (PID=0x%08X) is allowed"),
5210 pid, mUserData->mName.raw(), mData->mSession.mPid);
5211 }
5212
5213 /* create a SessionMachine object */
5214 ComObjPtr<SessionMachine> sessionMachine;
5215 sessionMachine.createObject();
5216 HRESULT rc = sessionMachine->init(this);
5217 AssertComRC(rc);
5218
5219 /* NOTE: doing return from this function after this point but
5220 * before the end is forbidden since it may call SessionMachine::uninit()
5221 * (through the ComObjPtr's destructor) which requests the VirtualBox write
5222 * lock while still holding the Machine lock in alock so that a deadlock
5223 * is possible due to the wrong lock order. */
5224
5225 if (SUCCEEDED(rc))
5226 {
5227#ifdef VBOX_WITH_RESOURCE_USAGE_API
5228 registerMetrics(mParent->performanceCollector(), this, pid);
5229#endif /* VBOX_WITH_RESOURCE_USAGE_API */
5230
5231 /*
5232 * Set the session state to Spawning to protect against subsequent
5233 * attempts to open a session and to unregister the machine after
5234 * we leave the lock.
5235 */
5236 SessionState_T origState = mData->mSession.mState;
5237 mData->mSession.mState = SessionState_Spawning;
5238
5239 /*
5240 * Leave the lock before calling the client process -- it will call
5241 * Machine/SessionMachine methods. Leaving the lock here is quite safe
5242 * because the state is Spawning, so that openRemotesession() and
5243 * openExistingSession() calls will fail. This method, called before we
5244 * enter the lock again, will fail because of the wrong PID.
5245 *
5246 * Note that mData->mSession.mRemoteControls accessed outside
5247 * the lock may not be modified when state is Spawning, so it's safe.
5248 */
5249 alock.leave();
5250
5251 LogFlowThisFunc(("Calling AssignMachine()...\n"));
5252 rc = aControl->AssignMachine(sessionMachine);
5253 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
5254
5255 /* The failure may occur w/o any error info (from RPC), so provide one */
5256 if (FAILED(rc))
5257 setError(VBOX_E_VM_ERROR,
5258 tr("Failed to assign the machine to the session (%Rrc)"), rc);
5259
5260 if (SUCCEEDED(rc) && origState == SessionState_Spawning)
5261 {
5262 /* complete the remote session initialization */
5263
5264 /* get the console from the direct session */
5265 ComPtr<IConsole> console;
5266 rc = aControl->GetRemoteConsole(console.asOutParam());
5267 ComAssertComRC(rc);
5268
5269 if (SUCCEEDED(rc) && !console)
5270 {
5271 ComAssert(!!console);
5272 rc = E_FAIL;
5273 }
5274
5275 /* assign machine & console to the remote session */
5276 if (SUCCEEDED(rc))
5277 {
5278 /*
5279 * after openRemoteSession(), the first and the only
5280 * entry in remoteControls is that remote session
5281 */
5282 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
5283 rc = mData->mSession.mRemoteControls.front()->
5284 AssignRemoteMachine(sessionMachine, console);
5285 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
5286
5287 /* The failure may occur w/o any error info (from RPC), so provide one */
5288 if (FAILED(rc))
5289 setError(VBOX_E_VM_ERROR,
5290 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
5291 }
5292
5293 if (FAILED(rc))
5294 aControl->Uninitialize();
5295 }
5296
5297 /* enter the lock again */
5298 alock.enter();
5299
5300 /* Restore the session state */
5301 mData->mSession.mState = origState;
5302 }
5303
5304 /* finalize spawning anyway (this is why we don't return on errors above) */
5305 if (mData->mSession.mState == SessionState_Spawning)
5306 {
5307 /* Note that the progress object is finalized later */
5308
5309 /* We don't reset mSession.mPid here because it is necessary for
5310 * SessionMachine::uninit() to reap the child process later. */
5311
5312 if (FAILED(rc))
5313 {
5314 /* Close the remote session, remove the remote control from the list
5315 * and reset session state to Closed (@note keep the code in sync
5316 * with the relevant part in openSession()). */
5317
5318 Assert(mData->mSession.mRemoteControls.size() == 1);
5319 if (mData->mSession.mRemoteControls.size() == 1)
5320 {
5321 ErrorInfoKeeper eik;
5322 mData->mSession.mRemoteControls.front()->Uninitialize();
5323 }
5324
5325 mData->mSession.mRemoteControls.clear();
5326 mData->mSession.mState = SessionState_Closed;
5327 }
5328 }
5329 else
5330 {
5331 /* memorize PID of the directly opened session */
5332 if (SUCCEEDED(rc))
5333 mData->mSession.mPid = pid;
5334 }
5335
5336 if (SUCCEEDED(rc))
5337 {
5338 /* memorize the direct session control and cache IUnknown for it */
5339 mData->mSession.mDirectControl = aControl;
5340 mData->mSession.mState = SessionState_Open;
5341 /* associate the SessionMachine with this Machine */
5342 mData->mSession.mMachine = sessionMachine;
5343
5344 /* request an IUnknown pointer early from the remote party for later
5345 * identity checks (it will be internally cached within mDirectControl
5346 * at least on XPCOM) */
5347 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
5348 NOREF(unk);
5349 }
5350
5351 /* Leave the lock since SessionMachine::uninit() locks VirtualBox which
5352 * would break the lock order */
5353 alock.leave();
5354
5355 /* uninitialize the created session machine on failure */
5356 if (FAILED(rc))
5357 sessionMachine->uninit();
5358
5359 LogFlowThisFunc(("rc=%08X\n", rc));
5360 LogFlowThisFuncLeave();
5361 return rc;
5362}
5363
5364/**
5365 * @note Locks this object for writing, calls the client process
5366 * (inside the lock).
5367 */
5368HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5369 IN_BSTR aType,
5370 IN_BSTR aEnvironment,
5371 Progress *aProgress)
5372{
5373 LogFlowThisFuncEnter();
5374
5375 AssertReturn(aControl, E_FAIL);
5376 AssertReturn(aProgress, E_FAIL);
5377
5378 AutoCaller autoCaller(this);
5379 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5380
5381 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5382
5383 if (!mData->mRegistered)
5384 return setError(E_UNEXPECTED,
5385 tr("The machine '%ls' is not registered"),
5386 mUserData->mName.raw());
5387
5388 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5389
5390 if (mData->mSession.mState == SessionState_Open ||
5391 mData->mSession.mState == SessionState_Spawning ||
5392 mData->mSession.mState == SessionState_Closing)
5393 return setError(VBOX_E_INVALID_OBJECT_STATE,
5394 tr("A session for the machine '%ls' is currently open (or being opened or closed)"),
5395 mUserData->mName.raw());
5396
5397 /* may not be busy */
5398 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5399
5400 /* get the path to the executable */
5401 char szPath[RTPATH_MAX];
5402 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5403 size_t sz = strlen(szPath);
5404 szPath[sz++] = RTPATH_DELIMITER;
5405 szPath[sz] = 0;
5406 char *cmd = szPath + sz;
5407 sz = RTPATH_MAX - sz;
5408
5409 int vrc = VINF_SUCCESS;
5410 RTPROCESS pid = NIL_RTPROCESS;
5411
5412 RTENV env = RTENV_DEFAULT;
5413
5414 if (aEnvironment != NULL && *aEnvironment)
5415 {
5416 char *newEnvStr = NULL;
5417
5418 do
5419 {
5420 /* clone the current environment */
5421 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5422 AssertRCBreakStmt(vrc2, vrc = vrc2);
5423
5424 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5425 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5426
5427 /* put new variables to the environment
5428 * (ignore empty variable names here since RTEnv API
5429 * intentionally doesn't do that) */
5430 char *var = newEnvStr;
5431 for (char *p = newEnvStr; *p; ++p)
5432 {
5433 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5434 {
5435 *p = '\0';
5436 if (*var)
5437 {
5438 char *val = strchr(var, '=');
5439 if (val)
5440 {
5441 *val++ = '\0';
5442 vrc2 = RTEnvSetEx(env, var, val);
5443 }
5444 else
5445 vrc2 = RTEnvUnsetEx(env, var);
5446 if (RT_FAILURE(vrc2))
5447 break;
5448 }
5449 var = p + 1;
5450 }
5451 }
5452 if (RT_SUCCESS(vrc2) && *var)
5453 vrc2 = RTEnvPutEx(env, var);
5454
5455 AssertRCBreakStmt(vrc2, vrc = vrc2);
5456 }
5457 while (0);
5458
5459 if (newEnvStr != NULL)
5460 RTStrFree(newEnvStr);
5461 }
5462
5463 Utf8Str strType(aType);
5464
5465 /* Qt is default */
5466#ifdef VBOX_WITH_QTGUI
5467 if (strType == "gui" || strType == "GUI/Qt")
5468 {
5469# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5470 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5471# else
5472 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5473# endif
5474 Assert(sz >= sizeof(VirtualBox_exe));
5475 strcpy(cmd, VirtualBox_exe);
5476
5477 Utf8Str idStr = mData->mUuid.toString();
5478# ifdef RT_OS_WINDOWS /** @todo drop this once the RTProcCreate bug has been fixed */
5479 const char * args[] = {szPath, "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5480# else
5481 Utf8Str strName = mUserData->mName;
5482 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5483# endif
5484 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5485 }
5486#else /* !VBOX_WITH_QTGUI */
5487 if (0)
5488 ;
5489#endif /* VBOX_WITH_QTGUI */
5490
5491 else
5492
5493#ifdef VBOX_WITH_VBOXSDL
5494 if (strType == "sdl" || strType == "GUI/SDL")
5495 {
5496 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5497 Assert(sz >= sizeof(VBoxSDL_exe));
5498 strcpy(cmd, VBoxSDL_exe);
5499
5500 Utf8Str idStr = mData->mUuid.toString();
5501# ifdef RT_OS_WINDOWS
5502 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0 };
5503# else
5504 Utf8Str strName = mUserData->mName;
5505 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0 };
5506# endif
5507 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5508 }
5509#else /* !VBOX_WITH_VBOXSDL */
5510 if (0)
5511 ;
5512#endif /* !VBOX_WITH_VBOXSDL */
5513
5514 else
5515
5516#ifdef VBOX_WITH_HEADLESS
5517 if ( strType == "headless"
5518 || strType == "capture"
5519#ifdef VBOX_WITH_VRDP
5520 || strType == "vrdp"
5521#endif
5522 )
5523 {
5524 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
5525 Assert(sz >= sizeof(VBoxHeadless_exe));
5526 strcpy(cmd, VBoxHeadless_exe);
5527
5528 Utf8Str idStr = mData->mUuid.toString();
5529 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
5530# ifdef RT_OS_WINDOWS
5531 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0, 0, 0 };
5532# else
5533 Utf8Str strName = mUserData->mName;
5534 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
5535# endif
5536#ifdef VBOX_WITH_VRDP
5537 if (strType == "headless")
5538 {
5539 unsigned pos = RT_ELEMENTS(args) - 3;
5540 args[pos++] = "--vrdp";
5541 args[pos] = "off";
5542 }
5543#endif
5544 if (strType == "capture")
5545 {
5546 unsigned pos = RT_ELEMENTS(args) - 3;
5547 args[pos] = "--capture";
5548 }
5549 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5550 }
5551#else /* !VBOX_WITH_HEADLESS */
5552 if (0)
5553 ;
5554#endif /* !VBOX_WITH_HEADLESS */
5555 else
5556 {
5557 RTEnvDestroy(env);
5558 return setError(E_INVALIDARG,
5559 tr("Invalid session type: '%s'"),
5560 strType.c_str());
5561 }
5562
5563 RTEnvDestroy(env);
5564
5565 if (RT_FAILURE(vrc))
5566 return setError(VBOX_E_IPRT_ERROR,
5567 tr("Could not launch a process for the machine '%ls' (%Rrc)"),
5568 mUserData->mName.raw(), vrc);
5569
5570 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
5571
5572 /*
5573 * Note that we don't leave the lock here before calling the client,
5574 * because it doesn't need to call us back if called with a NULL argument.
5575 * Leaving the lock herer is dangerous because we didn't prepare the
5576 * launch data yet, but the client we've just started may happen to be
5577 * too fast and call openSession() that will fail (because of PID, etc.),
5578 * so that the Machine will never get out of the Spawning session state.
5579 */
5580
5581 /* inform the session that it will be a remote one */
5582 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
5583 HRESULT rc = aControl->AssignMachine(NULL);
5584 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
5585
5586 if (FAILED(rc))
5587 {
5588 /* restore the session state */
5589 mData->mSession.mState = SessionState_Closed;
5590 /* The failure may occur w/o any error info (from RPC), so provide one */
5591 return setError(VBOX_E_VM_ERROR,
5592 tr("Failed to assign the machine to the session (%Rrc)"), rc);
5593 }
5594
5595 /* attach launch data to the machine */
5596 Assert(mData->mSession.mPid == NIL_RTPROCESS);
5597 mData->mSession.mRemoteControls.push_back (aControl);
5598 mData->mSession.mProgress = aProgress;
5599 mData->mSession.mPid = pid;
5600 mData->mSession.mState = SessionState_Spawning;
5601 mData->mSession.mType = strType;
5602
5603 LogFlowThisFuncLeave();
5604 return S_OK;
5605}
5606
5607/**
5608 * @note Locks this object for writing, calls the client process
5609 * (outside the lock).
5610 */
5611HRESULT Machine::openExistingSession(IInternalSessionControl *aControl)
5612{
5613 LogFlowThisFuncEnter();
5614
5615 AssertReturn(aControl, E_FAIL);
5616
5617 AutoCaller autoCaller(this);
5618 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5619
5620 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5621
5622 if (!mData->mRegistered)
5623 return setError(E_UNEXPECTED,
5624 tr("The machine '%ls' is not registered"),
5625 mUserData->mName.raw());
5626
5627 LogFlowThisFunc(("mSession.state=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5628
5629 if (mData->mSession.mState != SessionState_Open)
5630 return setError(VBOX_E_INVALID_SESSION_STATE,
5631 tr("The machine '%ls' does not have an open session"),
5632 mUserData->mName.raw());
5633
5634 ComAssertRet(!mData->mSession.mDirectControl.isNull(), E_FAIL);
5635
5636 // copy member variables before leaving lock
5637 ComPtr<IInternalSessionControl> pDirectControl = mData->mSession.mDirectControl;
5638 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
5639 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
5640
5641 /*
5642 * Leave the lock before calling the client process. It's safe here
5643 * since the only thing to do after we get the lock again is to add
5644 * the remote control to the list (which doesn't directly influence
5645 * anything).
5646 */
5647 alock.leave();
5648
5649 // get the console from the direct session (this is a remote call)
5650 ComPtr<IConsole> pConsole;
5651 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
5652 HRESULT rc = pDirectControl->GetRemoteConsole(pConsole.asOutParam());
5653 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
5654 if (FAILED (rc))
5655 /* The failure may occur w/o any error info (from RPC), so provide one */
5656 return setError (VBOX_E_VM_ERROR,
5657 tr ("Failed to get a console object from the direct session (%Rrc)"), rc);
5658
5659 ComAssertRet(!pConsole.isNull(), E_FAIL);
5660
5661 /* attach the remote session to the machine */
5662 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
5663 rc = aControl->AssignRemoteMachine(pSessionMachine, pConsole);
5664 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
5665
5666 /* The failure may occur w/o any error info (from RPC), so provide one */
5667 if (FAILED(rc))
5668 return setError(VBOX_E_VM_ERROR,
5669 tr("Failed to assign the machine to the session (%Rrc)"),
5670 rc);
5671
5672 alock.enter();
5673
5674 /* need to revalidate the state after entering the lock again */
5675 if (mData->mSession.mState != SessionState_Open)
5676 {
5677 aControl->Uninitialize();
5678
5679 return setError(VBOX_E_INVALID_SESSION_STATE,
5680 tr("The machine '%ls' does not have an open session"),
5681 mUserData->mName.raw());
5682 }
5683
5684 /* store the control in the list */
5685 mData->mSession.mRemoteControls.push_back(aControl);
5686
5687 LogFlowThisFuncLeave();
5688 return S_OK;
5689}
5690
5691/**
5692 * Returns @c true if the given machine has an open direct session and returns
5693 * the session machine instance and additional session data (on some platforms)
5694 * if so.
5695 *
5696 * Note that when the method returns @c false, the arguments remain unchanged.
5697 *
5698 * @param aMachine Session machine object.
5699 * @param aControl Direct session control object (optional).
5700 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
5701 *
5702 * @note locks this object for reading.
5703 */
5704#if defined(RT_OS_WINDOWS)
5705bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5706 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5707 HANDLE *aIPCSem /*= NULL*/,
5708 bool aAllowClosing /*= false*/)
5709#elif defined(RT_OS_OS2)
5710bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5711 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5712 HMTX *aIPCSem /*= NULL*/,
5713 bool aAllowClosing /*= false*/)
5714#else
5715bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5716 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5717 bool aAllowClosing /*= false*/)
5718#endif
5719{
5720 AutoLimitedCaller autoCaller(this);
5721 AssertComRCReturn(autoCaller.rc(), false);
5722
5723 /* just return false for inaccessible machines */
5724 if (autoCaller.state() != Ready)
5725 return false;
5726
5727 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5728
5729 if (mData->mSession.mState == SessionState_Open ||
5730 (aAllowClosing && mData->mSession.mState == SessionState_Closing))
5731 {
5732 AssertReturn(!mData->mSession.mMachine.isNull(), false);
5733
5734 aMachine = mData->mSession.mMachine;
5735
5736 if (aControl != NULL)
5737 *aControl = mData->mSession.mDirectControl;
5738
5739#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5740 /* Additional session data */
5741 if (aIPCSem != NULL)
5742 *aIPCSem = aMachine->mIPCSem;
5743#endif
5744 return true;
5745 }
5746
5747 return false;
5748}
5749
5750/**
5751 * Returns @c true if the given machine has an spawning direct session and
5752 * returns and additional session data (on some platforms) if so.
5753 *
5754 * Note that when the method returns @c false, the arguments remain unchanged.
5755 *
5756 * @param aPID PID of the spawned direct session process.
5757 *
5758 * @note locks this object for reading.
5759 */
5760#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5761bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
5762#else
5763bool Machine::isSessionSpawning()
5764#endif
5765{
5766 AutoLimitedCaller autoCaller(this);
5767 AssertComRCReturn(autoCaller.rc(), false);
5768
5769 /* just return false for inaccessible machines */
5770 if (autoCaller.state() != Ready)
5771 return false;
5772
5773 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5774
5775 if (mData->mSession.mState == SessionState_Spawning)
5776 {
5777#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5778 /* Additional session data */
5779 if (aPID != NULL)
5780 {
5781 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
5782 *aPID = mData->mSession.mPid;
5783 }
5784#endif
5785 return true;
5786 }
5787
5788 return false;
5789}
5790
5791/**
5792 * Called from the client watcher thread to check for unexpected client process
5793 * death during Session_Spawning state (e.g. before it successfully opened a
5794 * direct session).
5795 *
5796 * On Win32 and on OS/2, this method is called only when we've got the
5797 * direct client's process termination notification, so it always returns @c
5798 * true.
5799 *
5800 * On other platforms, this method returns @c true if the client process is
5801 * terminated and @c false if it's still alive.
5802 *
5803 * @note Locks this object for writing.
5804 */
5805bool Machine::checkForSpawnFailure()
5806{
5807 AutoCaller autoCaller(this);
5808 if (!autoCaller.isOk())
5809 {
5810 /* nothing to do */
5811 LogFlowThisFunc(("Already uninitialized!\n"));
5812 return true;
5813 }
5814
5815 /* VirtualBox::addProcessToReap() needs a write lock */
5816 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
5817
5818 if (mData->mSession.mState != SessionState_Spawning)
5819 {
5820 /* nothing to do */
5821 LogFlowThisFunc(("Not spawning any more!\n"));
5822 return true;
5823 }
5824
5825 HRESULT rc = S_OK;
5826
5827#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5828
5829 /* the process was already unexpectedly terminated, we just need to set an
5830 * error and finalize session spawning */
5831 rc = setError(E_FAIL,
5832 tr("Virtual machine '%ls' has terminated unexpectedly during startup"),
5833 getName().raw());
5834#else
5835
5836 /* PID not yet initialized, skip check. */
5837 if (mData->mSession.mPid == NIL_RTPROCESS)
5838 return false;
5839
5840 RTPROCSTATUS status;
5841 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
5842 &status);
5843
5844 if (vrc != VERR_PROCESS_RUNNING)
5845 rc = setError(E_FAIL,
5846 tr("Virtual machine '%ls' has terminated unexpectedly during startup"),
5847 getName().raw());
5848#endif
5849
5850 if (FAILED(rc))
5851 {
5852 /* Close the remote session, remove the remote control from the list
5853 * and reset session state to Closed (@note keep the code in sync with
5854 * the relevant part in checkForSpawnFailure()). */
5855
5856 Assert(mData->mSession.mRemoteControls.size() == 1);
5857 if (mData->mSession.mRemoteControls.size() == 1)
5858 {
5859 ErrorInfoKeeper eik;
5860 mData->mSession.mRemoteControls.front()->Uninitialize();
5861 }
5862
5863 mData->mSession.mRemoteControls.clear();
5864 mData->mSession.mState = SessionState_Closed;
5865
5866 /* finalize the progress after setting the state */
5867 if (!mData->mSession.mProgress.isNull())
5868 {
5869 mData->mSession.mProgress->notifyComplete(rc);
5870 mData->mSession.mProgress.setNull();
5871 }
5872
5873 mParent->addProcessToReap(mData->mSession.mPid);
5874 mData->mSession.mPid = NIL_RTPROCESS;
5875
5876 mParent->onSessionStateChange(mData->mUuid, SessionState_Closed);
5877 return true;
5878 }
5879
5880 return false;
5881}
5882
5883/**
5884 * Checks that the registered flag of the machine can be set according to
5885 * the argument and sets it. On success, commits and saves all settings.
5886 *
5887 * @note When this machine is inaccessible, the only valid value for \a
5888 * aRegistered is FALSE (i.e. unregister the machine) because unregistered
5889 * inaccessible machines are not currently supported. Note that unregistering
5890 * an inaccessible machine will \b uninitialize this machine object. Therefore,
5891 * the caller must make sure there are no active Machine::addCaller() calls
5892 * on the current thread because this will block Machine::uninit().
5893 *
5894 * @note Must be called from mParent's write lock. Locks this object and
5895 * children for writing.
5896 */
5897HRESULT Machine::trySetRegistered(BOOL argNewRegistered)
5898{
5899 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
5900
5901 AutoLimitedCaller autoCaller(this);
5902 AssertComRCReturnRC(autoCaller.rc());
5903
5904 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5905
5906 /* wait for state dependants to drop to zero */
5907 ensureNoStateDependencies();
5908
5909 ComAssertRet(mData->mRegistered != argNewRegistered, E_FAIL);
5910
5911 if (!mData->mAccessible)
5912 {
5913 /* A special case: the machine is not accessible. */
5914
5915 /* inaccessible machines can only be unregistered */
5916 AssertReturn(!argNewRegistered, E_FAIL);
5917
5918 /* Uninitialize ourselves here because currently there may be no
5919 * unregistered that are inaccessible (this state combination is not
5920 * supported). Note releasing the caller and leaving the lock before
5921 * calling uninit() */
5922
5923 alock.leave();
5924 autoCaller.release();
5925
5926 uninit();
5927
5928 return S_OK;
5929 }
5930
5931 AssertReturn(autoCaller.state() == Ready, E_FAIL);
5932
5933 if (argNewRegistered)
5934 {
5935 if (mData->mRegistered)
5936 return setError(VBOX_E_INVALID_OBJECT_STATE,
5937 tr("The machine '%ls' with UUID {%s} is already registered"),
5938 mUserData->mName.raw(),
5939 mData->mUuid.toString().raw());
5940 }
5941 else
5942 {
5943 if (mData->mMachineState == MachineState_Saved)
5944 return setError(VBOX_E_INVALID_VM_STATE,
5945 tr("Cannot unregister the machine '%ls' because it is in the Saved state"),
5946 mUserData->mName.raw());
5947
5948 size_t snapshotCount = 0;
5949 if (mData->mFirstSnapshot)
5950 snapshotCount = mData->mFirstSnapshot->getAllChildrenCount() + 1;
5951 if (snapshotCount)
5952 return setError(VBOX_E_INVALID_OBJECT_STATE,
5953 tr("Cannot unregister the machine '%ls' because it has %d snapshots"),
5954 mUserData->mName.raw(), snapshotCount);
5955
5956 if (mData->mSession.mState != SessionState_Closed)
5957 return setError(VBOX_E_INVALID_OBJECT_STATE,
5958 tr("Cannot unregister the machine '%ls' because it has an open session"),
5959 mUserData->mName.raw());
5960
5961 if (mMediaData->mAttachments.size() != 0)
5962 return setError(VBOX_E_INVALID_OBJECT_STATE,
5963 tr("Cannot unregister the machine '%ls' because it has %d medium attachments"),
5964 mUserData->mName.raw(),
5965 mMediaData->mAttachments.size());
5966
5967 /* Note that we do not prevent unregistration of a DVD or Floppy image
5968 * is attached: as opposed to hard disks detaching such an image
5969 * implicitly in this method (which we will do below) won't have any
5970 * side effects (like detached orphan base and diff hard disks etc).*/
5971 }
5972
5973 HRESULT rc = S_OK;
5974
5975 // Ensure the settings are saved. If we are going to be registered and
5976 // no config file exists yet, create it by calling saveSettings() too.
5977 if ( (mData->flModifications)
5978 || (argNewRegistered && !mData->pMachineConfigFile->fileExists())
5979 )
5980 {
5981 rc = saveSettings(NULL);
5982 // no need to check whether VirtualBox.xml needs saving too since
5983 // we can't have a machine XML file rename pending
5984 if (FAILED(rc)) return rc;
5985 }
5986
5987 /* more config checking goes here */
5988
5989 if (SUCCEEDED(rc))
5990 {
5991 /* we may have had implicit modifications we want to fix on success */
5992 commit();
5993
5994 mData->mRegistered = argNewRegistered;
5995 }
5996 else
5997 {
5998 /* we may have had implicit modifications we want to cancel on failure*/
5999 rollback(false /* aNotify */);
6000 }
6001
6002 return rc;
6003}
6004
6005/**
6006 * Increases the number of objects dependent on the machine state or on the
6007 * registered state. Guarantees that these two states will not change at least
6008 * until #releaseStateDependency() is called.
6009 *
6010 * Depending on the @a aDepType value, additional state checks may be made.
6011 * These checks will set extended error info on failure. See
6012 * #checkStateDependency() for more info.
6013 *
6014 * If this method returns a failure, the dependency is not added and the caller
6015 * is not allowed to rely on any particular machine state or registration state
6016 * value and may return the failed result code to the upper level.
6017 *
6018 * @param aDepType Dependency type to add.
6019 * @param aState Current machine state (NULL if not interested).
6020 * @param aRegistered Current registered state (NULL if not interested).
6021 *
6022 * @note Locks this object for writing.
6023 */
6024HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6025 MachineState_T *aState /* = NULL */,
6026 BOOL *aRegistered /* = NULL */)
6027{
6028 AutoCaller autoCaller(this);
6029 AssertComRCReturnRC(autoCaller.rc());
6030
6031 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6032
6033 HRESULT rc = checkStateDependency(aDepType);
6034 if (FAILED(rc)) return rc;
6035
6036 {
6037 if (mData->mMachineStateChangePending != 0)
6038 {
6039 /* ensureNoStateDependencies() is waiting for state dependencies to
6040 * drop to zero so don't add more. It may make sense to wait a bit
6041 * and retry before reporting an error (since the pending state
6042 * transition should be really quick) but let's just assert for
6043 * now to see if it ever happens on practice. */
6044
6045 AssertFailed();
6046
6047 return setError(E_ACCESSDENIED,
6048 tr("Machine state change is in progress. Please retry the operation later."));
6049 }
6050
6051 ++mData->mMachineStateDeps;
6052 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6053 }
6054
6055 if (aState)
6056 *aState = mData->mMachineState;
6057 if (aRegistered)
6058 *aRegistered = mData->mRegistered;
6059
6060 return S_OK;
6061}
6062
6063/**
6064 * Decreases the number of objects dependent on the machine state.
6065 * Must always complete the #addStateDependency() call after the state
6066 * dependency is no more necessary.
6067 */
6068void Machine::releaseStateDependency()
6069{
6070 AutoCaller autoCaller(this);
6071 AssertComRCReturnVoid(autoCaller.rc());
6072
6073 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6074
6075 /* releaseStateDependency() w/o addStateDependency()? */
6076 AssertReturnVoid(mData->mMachineStateDeps != 0);
6077 -- mData->mMachineStateDeps;
6078
6079 if (mData->mMachineStateDeps == 0)
6080 {
6081 /* inform ensureNoStateDependencies() that there are no more deps */
6082 if (mData->mMachineStateChangePending != 0)
6083 {
6084 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6085 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6086 }
6087 }
6088}
6089
6090// protected methods
6091/////////////////////////////////////////////////////////////////////////////
6092
6093/**
6094 * Performs machine state checks based on the @a aDepType value. If a check
6095 * fails, this method will set extended error info, otherwise it will return
6096 * S_OK. It is supposed, that on failure, the caller will immedieately return
6097 * the return value of this method to the upper level.
6098 *
6099 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6100 *
6101 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6102 * current state of this machine object allows to change settings of the
6103 * machine (i.e. the machine is not registered, or registered but not running
6104 * and not saved). It is useful to call this method from Machine setters
6105 * before performing any change.
6106 *
6107 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6108 * as for MutableStateDep except that if the machine is saved, S_OK is also
6109 * returned. This is useful in setters which allow changing machine
6110 * properties when it is in the saved state.
6111 *
6112 * @param aDepType Dependency type to check.
6113 *
6114 * @note Non Machine based classes should use #addStateDependency() and
6115 * #releaseStateDependency() methods or the smart AutoStateDependency
6116 * template.
6117 *
6118 * @note This method must be called from under this object's read or write
6119 * lock.
6120 */
6121HRESULT Machine::checkStateDependency(StateDependency aDepType)
6122{
6123 switch (aDepType)
6124 {
6125 case AnyStateDep:
6126 {
6127 break;
6128 }
6129 case MutableStateDep:
6130 {
6131 if ( mData->mRegistered
6132 && ( getClassID() != clsidSessionMachine /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6133 || ( mData->mMachineState != MachineState_Paused
6134 && mData->mMachineState != MachineState_Running
6135 && mData->mMachineState != MachineState_Aborted
6136 && mData->mMachineState != MachineState_Teleported
6137 && mData->mMachineState != MachineState_PoweredOff
6138 )
6139 )
6140 )
6141 return setError(VBOX_E_INVALID_VM_STATE,
6142 tr("The machine is not mutable (state is %s)"),
6143 Global::stringifyMachineState(mData->mMachineState));
6144 break;
6145 }
6146 case MutableOrSavedStateDep:
6147 {
6148 if ( mData->mRegistered
6149 && ( getClassID() != clsidSessionMachine /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6150 || ( mData->mMachineState != MachineState_Paused
6151 && mData->mMachineState != MachineState_Running
6152 && mData->mMachineState != MachineState_Aborted
6153 && mData->mMachineState != MachineState_Teleported
6154 && mData->mMachineState != MachineState_Saved
6155 && mData->mMachineState != MachineState_PoweredOff
6156 )
6157 )
6158 )
6159 return setError(VBOX_E_INVALID_VM_STATE,
6160 tr("The machine is not mutable (state is %s)"),
6161 Global::stringifyMachineState(mData->mMachineState));
6162 break;
6163 }
6164 }
6165
6166 return S_OK;
6167}
6168
6169/**
6170 * Helper to initialize all associated child objects and allocate data
6171 * structures.
6172 *
6173 * This method must be called as a part of the object's initialization procedure
6174 * (usually done in the #init() method).
6175 *
6176 * @note Must be called only from #init() or from #registeredInit().
6177 */
6178HRESULT Machine::initDataAndChildObjects()
6179{
6180 AutoCaller autoCaller(this);
6181 AssertComRCReturnRC(autoCaller.rc());
6182 AssertComRCReturn(autoCaller.state() == InInit ||
6183 autoCaller.state() == Limited, E_FAIL);
6184
6185 AssertReturn(!mData->mAccessible, E_FAIL);
6186
6187 /* allocate data structures */
6188 mSSData.allocate();
6189 mUserData.allocate();
6190 mHWData.allocate();
6191 mMediaData.allocate();
6192 mStorageControllers.allocate();
6193
6194 /* initialize mOSTypeId */
6195 mUserData->mOSTypeId = mParent->getUnknownOSType()->id();
6196
6197 /* create associated BIOS settings object */
6198 unconst(mBIOSSettings).createObject();
6199 mBIOSSettings->init(this);
6200
6201#ifdef VBOX_WITH_VRDP
6202 /* create an associated VRDPServer object (default is disabled) */
6203 unconst(mVRDPServer).createObject();
6204 mVRDPServer->init(this);
6205#endif
6206
6207 /* create associated serial port objects */
6208 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6209 {
6210 unconst(mSerialPorts[slot]).createObject();
6211 mSerialPorts[slot]->init(this, slot);
6212 }
6213
6214 /* create associated parallel port objects */
6215 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6216 {
6217 unconst(mParallelPorts[slot]).createObject();
6218 mParallelPorts[slot]->init(this, slot);
6219 }
6220
6221 /* create the audio adapter object (always present, default is disabled) */
6222 unconst(mAudioAdapter).createObject();
6223 mAudioAdapter->init(this);
6224
6225 /* create the USB controller object (always present, default is disabled) */
6226 unconst(mUSBController).createObject();
6227 mUSBController->init(this);
6228
6229 /* create associated network adapter objects */
6230 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6231 {
6232 unconst(mNetworkAdapters[slot]).createObject();
6233 mNetworkAdapters[slot]->init(this, slot);
6234 }
6235
6236 return S_OK;
6237}
6238
6239/**
6240 * Helper to uninitialize all associated child objects and to free all data
6241 * structures.
6242 *
6243 * This method must be called as a part of the object's uninitialization
6244 * procedure (usually done in the #uninit() method).
6245 *
6246 * @note Must be called only from #uninit() or from #registeredInit().
6247 */
6248void Machine::uninitDataAndChildObjects()
6249{
6250 AutoCaller autoCaller(this);
6251 AssertComRCReturnVoid(autoCaller.rc());
6252 AssertComRCReturnVoid( autoCaller.state() == InUninit
6253 || autoCaller.state() == Limited);
6254
6255 /* uninit all children using addDependentChild()/removeDependentChild()
6256 * in their init()/uninit() methods */
6257 uninitDependentChildren();
6258
6259 /* tell all our other child objects we've been uninitialized */
6260
6261 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6262 {
6263 if (mNetworkAdapters[slot])
6264 {
6265 mNetworkAdapters[slot]->uninit();
6266 unconst(mNetworkAdapters[slot]).setNull();
6267 }
6268 }
6269
6270 if (mUSBController)
6271 {
6272 mUSBController->uninit();
6273 unconst(mUSBController).setNull();
6274 }
6275
6276 if (mAudioAdapter)
6277 {
6278 mAudioAdapter->uninit();
6279 unconst(mAudioAdapter).setNull();
6280 }
6281
6282 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6283 {
6284 if (mParallelPorts[slot])
6285 {
6286 mParallelPorts[slot]->uninit();
6287 unconst(mParallelPorts[slot]).setNull();
6288 }
6289 }
6290
6291 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6292 {
6293 if (mSerialPorts[slot])
6294 {
6295 mSerialPorts[slot]->uninit();
6296 unconst(mSerialPorts[slot]).setNull();
6297 }
6298 }
6299
6300#ifdef VBOX_WITH_VRDP
6301 if (mVRDPServer)
6302 {
6303 mVRDPServer->uninit();
6304 unconst(mVRDPServer).setNull();
6305 }
6306#endif
6307
6308 if (mBIOSSettings)
6309 {
6310 mBIOSSettings->uninit();
6311 unconst(mBIOSSettings).setNull();
6312 }
6313
6314 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6315 * instance is uninitialized; SessionMachine instances refer to real
6316 * Machine hard disks). This is necessary for a clean re-initialization of
6317 * the VM after successfully re-checking the accessibility state. Note
6318 * that in case of normal Machine or SnapshotMachine uninitialization (as
6319 * a result of unregistering or discarding the snapshot), outdated hard
6320 * disk attachments will already be uninitialized and deleted, so this
6321 * code will not affect them. */
6322 VBoxClsID clsid = getClassID();
6323 if ( !!mMediaData
6324 && (clsid == clsidMachine || clsid == clsidSnapshotMachine)
6325 )
6326 {
6327 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6328 it != mMediaData->mAttachments.end();
6329 ++it)
6330 {
6331 ComObjPtr<Medium> hd = (*it)->getMedium();
6332 if (hd.isNull())
6333 continue;
6334 HRESULT rc = hd->detachFrom(mData->mUuid, getSnapshotId());
6335 AssertComRC(rc);
6336 }
6337 }
6338
6339 if (getClassID() == clsidMachine)
6340 {
6341 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6342 if (mData->mFirstSnapshot)
6343 {
6344 // snapshots tree is protected by media write lock; strictly
6345 // this isn't necessary here since we're deleting the entire
6346 // machine, but otherwise we assert in Snapshot::uninit()
6347 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6348 mData->mFirstSnapshot->uninit();
6349 mData->mFirstSnapshot.setNull();
6350 }
6351
6352 mData->mCurrentSnapshot.setNull();
6353 }
6354
6355 /* free data structures (the essential mData structure is not freed here
6356 * since it may be still in use) */
6357 mMediaData.free();
6358 mStorageControllers.free();
6359 mHWData.free();
6360 mUserData.free();
6361 mSSData.free();
6362}
6363
6364/**
6365 * Returns a pointer to the Machine object for this machine that acts like a
6366 * parent for complex machine data objects such as shared folders, etc.
6367 *
6368 * For primary Machine objects and for SnapshotMachine objects, returns this
6369 * object's pointer itself. For SessoinMachine objects, returns the peer
6370 * (primary) machine pointer.
6371 */
6372Machine* Machine::getMachine()
6373{
6374 if (getClassID() == clsidSessionMachine)
6375 return (Machine*)mPeer;
6376 return this;
6377}
6378
6379/**
6380 * Makes sure that there are no machine state dependants. If necessary, waits
6381 * for the number of dependants to drop to zero.
6382 *
6383 * Make sure this method is called from under this object's write lock to
6384 * guarantee that no new dependants may be added when this method returns
6385 * control to the caller.
6386 *
6387 * @note Locks this object for writing. The lock will be released while waiting
6388 * (if necessary).
6389 *
6390 * @warning To be used only in methods that change the machine state!
6391 */
6392void Machine::ensureNoStateDependencies()
6393{
6394 AssertReturnVoid(isWriteLockOnCurrentThread());
6395
6396 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6397
6398 /* Wait for all state dependants if necessary */
6399 if (mData->mMachineStateDeps != 0)
6400 {
6401 /* lazy semaphore creation */
6402 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6403 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6404
6405 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6406 mData->mMachineStateDeps));
6407
6408 ++mData->mMachineStateChangePending;
6409
6410 /* reset the semaphore before waiting, the last dependant will signal
6411 * it */
6412 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6413
6414 alock.leave();
6415
6416 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6417
6418 alock.enter();
6419
6420 -- mData->mMachineStateChangePending;
6421 }
6422}
6423
6424/**
6425 * Changes the machine state and informs callbacks.
6426 *
6427 * This method is not intended to fail so it either returns S_OK or asserts (and
6428 * returns a failure).
6429 *
6430 * @note Locks this object for writing.
6431 */
6432HRESULT Machine::setMachineState(MachineState_T aMachineState)
6433{
6434 LogFlowThisFuncEnter();
6435 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6436
6437 AutoCaller autoCaller(this);
6438 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6439
6440 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6441
6442 /* wait for state dependants to drop to zero */
6443 ensureNoStateDependencies();
6444
6445 if (mData->mMachineState != aMachineState)
6446 {
6447 mData->mMachineState = aMachineState;
6448
6449 RTTimeNow(&mData->mLastStateChange);
6450
6451 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6452 }
6453
6454 LogFlowThisFuncLeave();
6455 return S_OK;
6456}
6457
6458/**
6459 * Searches for a shared folder with the given logical name
6460 * in the collection of shared folders.
6461 *
6462 * @param aName logical name of the shared folder
6463 * @param aSharedFolder where to return the found object
6464 * @param aSetError whether to set the error info if the folder is
6465 * not found
6466 * @return
6467 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6468 *
6469 * @note
6470 * must be called from under the object's lock!
6471 */
6472HRESULT Machine::findSharedFolder(CBSTR aName,
6473 ComObjPtr<SharedFolder> &aSharedFolder,
6474 bool aSetError /* = false */)
6475{
6476 bool found = false;
6477 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6478 !found && it != mHWData->mSharedFolders.end();
6479 ++it)
6480 {
6481 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6482 found = (*it)->getName() == aName;
6483 if (found)
6484 aSharedFolder = *it;
6485 }
6486
6487 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6488
6489 if (aSetError && !found)
6490 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6491
6492 return rc;
6493}
6494
6495/**
6496 * Initializes all machine instance data from the given settings structures
6497 * from XML. The exception is the machine UUID which needs special handling
6498 * depending on the caller's use case, so the caller needs to set that herself.
6499 *
6500 * @param config
6501 * @param fAllowStorage
6502 */
6503HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config)
6504{
6505 /* name (required) */
6506 mUserData->mName = config.strName;
6507
6508 /* nameSync (optional, default is true) */
6509 mUserData->mNameSync = config.fNameSync;
6510
6511 mUserData->mDescription = config.strDescription;
6512
6513 // guest OS type
6514 mUserData->mOSTypeId = config.strOsType;
6515 /* look up the object by Id to check it is valid */
6516 ComPtr<IGuestOSType> guestOSType;
6517 HRESULT rc = mParent->GetGuestOSType(mUserData->mOSTypeId,
6518 guestOSType.asOutParam());
6519 if (FAILED(rc)) return rc;
6520
6521 // stateFile (optional)
6522 if (config.strStateFile.isEmpty())
6523 mSSData->mStateFilePath.setNull();
6524 else
6525 {
6526 Utf8Str stateFilePathFull(config.strStateFile);
6527 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6528 if (RT_FAILURE(vrc))
6529 return setError(E_FAIL,
6530 tr("Invalid saved state file path '%s' (%Rrc)"),
6531 config.strStateFile.raw(),
6532 vrc);
6533 mSSData->mStateFilePath = stateFilePathFull;
6534 }
6535
6536 /* snapshotFolder (optional) */
6537 rc = COMSETTER(SnapshotFolder)(Bstr(config.strSnapshotFolder));
6538 if (FAILED(rc)) return rc;
6539
6540 /* currentStateModified (optional, default is true) */
6541 mData->mCurrentStateModified = config.fCurrentStateModified;
6542
6543 mData->mLastStateChange = config.timeLastStateChange;
6544
6545 /* teleportation */
6546 mUserData->mTeleporterEnabled = config.fTeleporterEnabled;
6547 mUserData->mTeleporterPort = config.uTeleporterPort;
6548 mUserData->mTeleporterAddress = config.strTeleporterAddress;
6549 mUserData->mTeleporterPassword = config.strTeleporterPassword;
6550
6551 /* RTC */
6552 mUserData->mRTCUseUTC = config.fRTCUseUTC;
6553
6554 /*
6555 * note: all mUserData members must be assigned prior this point because
6556 * we need to commit changes in order to let mUserData be shared by all
6557 * snapshot machine instances.
6558 */
6559 mUserData.commitCopy();
6560
6561 /* Snapshot node (optional) */
6562 size_t cRootSnapshots;
6563 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6564 {
6565 // there must be only one root snapshot
6566 Assert(cRootSnapshots == 1);
6567
6568 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6569
6570 rc = loadSnapshot(snap,
6571 config.uuidCurrentSnapshot,
6572 NULL); // no parent == first snapshot
6573 if (FAILED(rc)) return rc;
6574 }
6575
6576 /* Hardware node (required) */
6577 rc = loadHardware(config.hardwareMachine);
6578 if (FAILED(rc)) return rc;
6579
6580 /* Load storage controllers */
6581 rc = loadStorageControllers(config.storageMachine);
6582 if (FAILED(rc)) return rc;
6583
6584 /*
6585 * NOTE: the assignment below must be the last thing to do,
6586 * otherwise it will be not possible to change the settings
6587 * somewehere in the code above because all setters will be
6588 * blocked by checkStateDependency(MutableStateDep).
6589 */
6590
6591 /* set the machine state to Aborted or Saved when appropriate */
6592 if (config.fAborted)
6593 {
6594 Assert(!mSSData->mStateFilePath.isEmpty());
6595 mSSData->mStateFilePath.setNull();
6596
6597 /* no need to use setMachineState() during init() */
6598 mData->mMachineState = MachineState_Aborted;
6599 }
6600 else if (!mSSData->mStateFilePath.isEmpty())
6601 {
6602 /* no need to use setMachineState() during init() */
6603 mData->mMachineState = MachineState_Saved;
6604 }
6605
6606 // after loading settings, we are no longer different from the XML on disk
6607 mData->flModifications = 0;
6608
6609 return S_OK;
6610}
6611
6612/**
6613 * Recursively loads all snapshots starting from the given.
6614 *
6615 * @param aNode <Snapshot> node.
6616 * @param aCurSnapshotId Current snapshot ID from the settings file.
6617 * @param aParentSnapshot Parent snapshot.
6618 */
6619HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6620 const Guid &aCurSnapshotId,
6621 Snapshot *aParentSnapshot)
6622{
6623 AssertReturn(getClassID() == clsidMachine, E_FAIL);
6624
6625 HRESULT rc = S_OK;
6626
6627 Utf8Str strStateFile;
6628 if (!data.strStateFile.isEmpty())
6629 {
6630 /* optional */
6631 strStateFile = data.strStateFile;
6632 int vrc = calculateFullPath(strStateFile, strStateFile);
6633 if (RT_FAILURE(vrc))
6634 return setError(E_FAIL,
6635 tr("Invalid saved state file path '%s' (%Rrc)"),
6636 strStateFile.raw(),
6637 vrc);
6638 }
6639
6640 /* create a snapshot machine object */
6641 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6642 pSnapshotMachine.createObject();
6643 rc = pSnapshotMachine->init(this,
6644 data.hardware,
6645 data.storage,
6646 data.uuid,
6647 strStateFile);
6648 if (FAILED(rc)) return rc;
6649
6650 /* create a snapshot object */
6651 ComObjPtr<Snapshot> pSnapshot;
6652 pSnapshot.createObject();
6653 /* initialize the snapshot */
6654 rc = pSnapshot->init(mParent, // VirtualBox object
6655 data.uuid,
6656 data.strName,
6657 data.strDescription,
6658 data.timestamp,
6659 pSnapshotMachine,
6660 aParentSnapshot);
6661 if (FAILED(rc)) return rc;
6662
6663 /* memorize the first snapshot if necessary */
6664 if (!mData->mFirstSnapshot)
6665 mData->mFirstSnapshot = pSnapshot;
6666
6667 /* memorize the current snapshot when appropriate */
6668 if ( !mData->mCurrentSnapshot
6669 && pSnapshot->getId() == aCurSnapshotId
6670 )
6671 mData->mCurrentSnapshot = pSnapshot;
6672
6673 // now create the children
6674 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
6675 it != data.llChildSnapshots.end();
6676 ++it)
6677 {
6678 const settings::Snapshot &childData = *it;
6679 // recurse
6680 rc = loadSnapshot(childData,
6681 aCurSnapshotId,
6682 pSnapshot); // parent = the one we created above
6683 if (FAILED(rc)) return rc;
6684 }
6685
6686 return rc;
6687}
6688
6689/**
6690 * @param aNode <Hardware> node.
6691 */
6692HRESULT Machine::loadHardware(const settings::Hardware &data)
6693{
6694 AssertReturn(getClassID() == clsidMachine || getClassID() == clsidSnapshotMachine, E_FAIL);
6695
6696 HRESULT rc = S_OK;
6697
6698 try
6699 {
6700 /* The hardware version attribute (optional). */
6701 mHWData->mHWVersion = data.strVersion;
6702 mHWData->mHardwareUUID = data.uuid;
6703
6704 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
6705 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
6706 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
6707 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
6708 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
6709 mHWData->mPAEEnabled = data.fPAE;
6710 mHWData->mSyntheticCpu = data.fSyntheticCpu;
6711
6712 mHWData->mCPUCount = data.cCPUs;
6713 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
6714
6715 // cpu
6716 if (mHWData->mCPUHotPlugEnabled)
6717 {
6718 for (settings::CpuList::const_iterator it = data.llCpus.begin();
6719 it != data.llCpus.end();
6720 ++it)
6721 {
6722 const settings::Cpu &cpu = *it;
6723
6724 mHWData->mCPUAttached[cpu.ulId] = true;
6725 }
6726 }
6727
6728 // cpuid leafs
6729 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
6730 it != data.llCpuIdLeafs.end();
6731 ++it)
6732 {
6733 const settings::CpuIdLeaf &leaf = *it;
6734
6735 switch (leaf.ulId)
6736 {
6737 case 0x0:
6738 case 0x1:
6739 case 0x2:
6740 case 0x3:
6741 case 0x4:
6742 case 0x5:
6743 case 0x6:
6744 case 0x7:
6745 case 0x8:
6746 case 0x9:
6747 case 0xA:
6748 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
6749 break;
6750
6751 case 0x80000000:
6752 case 0x80000001:
6753 case 0x80000002:
6754 case 0x80000003:
6755 case 0x80000004:
6756 case 0x80000005:
6757 case 0x80000006:
6758 case 0x80000007:
6759 case 0x80000008:
6760 case 0x80000009:
6761 case 0x8000000A:
6762 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
6763 break;
6764
6765 default:
6766 /* just ignore */
6767 break;
6768 }
6769 }
6770
6771 mHWData->mMemorySize = data.ulMemorySizeMB;
6772
6773 // boot order
6774 for (size_t i = 0;
6775 i < RT_ELEMENTS(mHWData->mBootOrder);
6776 i++)
6777 {
6778 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
6779 if (it == data.mapBootOrder.end())
6780 mHWData->mBootOrder[i] = DeviceType_Null;
6781 else
6782 mHWData->mBootOrder[i] = it->second;
6783 }
6784
6785 mHWData->mVRAMSize = data.ulVRAMSizeMB;
6786 mHWData->mMonitorCount = data.cMonitors;
6787 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
6788 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
6789 mHWData->mFirmwareType = data.firmwareType;
6790 mHWData->mPointingHidType = data.pointingHidType;
6791 mHWData->mKeyboardHidType = data.keyboardHidType;
6792 mHWData->mHpetEnabled = data.fHpetEnabled;
6793
6794#ifdef VBOX_WITH_VRDP
6795 /* RemoteDisplay */
6796 rc = mVRDPServer->loadSettings(data.vrdpSettings);
6797 if (FAILED(rc)) return rc;
6798#endif
6799
6800 /* BIOS */
6801 rc = mBIOSSettings->loadSettings(data.biosSettings);
6802 if (FAILED(rc)) return rc;
6803
6804 /* USB Controller */
6805 rc = mUSBController->loadSettings(data.usbController);
6806 if (FAILED(rc)) return rc;
6807
6808 // network adapters
6809 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
6810 it != data.llNetworkAdapters.end();
6811 ++it)
6812 {
6813 const settings::NetworkAdapter &nic = *it;
6814
6815 /* slot unicity is guaranteed by XML Schema */
6816 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
6817 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
6818 if (FAILED(rc)) return rc;
6819 }
6820
6821 // serial ports
6822 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
6823 it != data.llSerialPorts.end();
6824 ++it)
6825 {
6826 const settings::SerialPort &s = *it;
6827
6828 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
6829 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
6830 if (FAILED(rc)) return rc;
6831 }
6832
6833 // parallel ports (optional)
6834 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
6835 it != data.llParallelPorts.end();
6836 ++it)
6837 {
6838 const settings::ParallelPort &p = *it;
6839
6840 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
6841 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
6842 if (FAILED(rc)) return rc;
6843 }
6844
6845 /* AudioAdapter */
6846 rc = mAudioAdapter->loadSettings(data.audioAdapter);
6847 if (FAILED(rc)) return rc;
6848
6849 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
6850 it != data.llSharedFolders.end();
6851 ++it)
6852 {
6853 const settings::SharedFolder &sf = *it;
6854 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable);
6855 if (FAILED(rc)) return rc;
6856 }
6857
6858 // Clipboard
6859 mHWData->mClipboardMode = data.clipboardMode;
6860
6861 // guest settings
6862 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
6863
6864 // IO settings
6865 mHWData->mIoMgrType = data.ioSettings.ioMgrType;
6866 mHWData->mIoBackendType = data.ioSettings.ioBackendType;
6867 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
6868 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
6869 mHWData->mIoBandwidthMax = data.ioSettings.ulIoBandwidthMax;
6870
6871#ifdef VBOX_WITH_GUEST_PROPS
6872 /* Guest properties (optional) */
6873 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
6874 it != data.llGuestProperties.end();
6875 ++it)
6876 {
6877 const settings::GuestProperty &prop = *it;
6878 uint32_t fFlags = guestProp::NILFLAG;
6879 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
6880 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
6881 mHWData->mGuestProperties.push_back(property);
6882 }
6883
6884 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
6885#endif /* VBOX_WITH_GUEST_PROPS defined */
6886 }
6887 catch(std::bad_alloc &)
6888 {
6889 return E_OUTOFMEMORY;
6890 }
6891
6892 AssertComRC(rc);
6893 return rc;
6894}
6895
6896 /**
6897 * @param aNode <StorageControllers> node.
6898 */
6899HRESULT Machine::loadStorageControllers(const settings::Storage &data,
6900 const Guid *aSnapshotId /* = NULL */)
6901{
6902 AssertReturn(getClassID() == clsidMachine || getClassID() == clsidSnapshotMachine, E_FAIL);
6903
6904 HRESULT rc = S_OK;
6905
6906 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
6907 it != data.llStorageControllers.end();
6908 ++it)
6909 {
6910 const settings::StorageController &ctlData = *it;
6911
6912 ComObjPtr<StorageController> pCtl;
6913 /* Try to find one with the name first. */
6914 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
6915 if (SUCCEEDED(rc))
6916 return setError(VBOX_E_OBJECT_IN_USE,
6917 tr("Storage controller named '%s' already exists"),
6918 ctlData.strName.raw());
6919
6920 pCtl.createObject();
6921 rc = pCtl->init(this,
6922 ctlData.strName,
6923 ctlData.storageBus,
6924 ctlData.ulInstance);
6925 if (FAILED(rc)) return rc;
6926
6927 mStorageControllers->push_back(pCtl);
6928
6929 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
6930 if (FAILED(rc)) return rc;
6931
6932 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
6933 if (FAILED(rc)) return rc;
6934
6935 /* Set IDE emulation settings (only for AHCI controller). */
6936 if (ctlData.controllerType == StorageControllerType_IntelAhci)
6937 {
6938 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
6939 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
6940 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
6941 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
6942 )
6943 return rc;
6944 }
6945
6946 /* Load the attached devices now. */
6947 rc = loadStorageDevices(pCtl,
6948 ctlData,
6949 aSnapshotId);
6950 if (FAILED(rc)) return rc;
6951 }
6952
6953 return S_OK;
6954}
6955
6956/**
6957 * @param aNode <HardDiskAttachments> node.
6958 * @param fAllowStorage if false, we produce an error if the config requests media attachments
6959 * (used with importing unregistered machines which cannot have media attachments)
6960 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
6961 *
6962 * @note Lock mParent for reading and hard disks for writing before calling.
6963 */
6964HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
6965 const settings::StorageController &data,
6966 const Guid *aSnapshotId /*= NULL*/)
6967{
6968 AssertReturn( (getClassID() == clsidMachine && aSnapshotId == NULL)
6969 || (getClassID() == clsidSnapshotMachine && aSnapshotId != NULL),
6970 E_FAIL);
6971
6972 HRESULT rc = S_OK;
6973
6974 /* paranoia: detect duplicate attachments */
6975 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
6976 it != data.llAttachedDevices.end();
6977 ++it)
6978 {
6979 for (settings::AttachedDevicesList::const_iterator it2 = it;
6980 it2 != data.llAttachedDevices.end();
6981 ++it2)
6982 {
6983 if (it == it2)
6984 continue;
6985
6986 if ( (*it).lPort == (*it2).lPort
6987 && (*it).lDevice == (*it2).lDevice)
6988 {
6989 return setError(E_FAIL,
6990 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%ls'"),
6991 aStorageController->getName().raw(), (*it).lPort, (*it).lDevice, mUserData->mName.raw());
6992 }
6993 }
6994 }
6995
6996 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
6997 it != data.llAttachedDevices.end();
6998 ++it)
6999 {
7000 const settings::AttachedDevice &dev = *it;
7001 ComObjPtr<Medium> medium;
7002
7003 switch (dev.deviceType)
7004 {
7005 case DeviceType_Floppy:
7006 /* find a floppy by UUID */
7007 if (!dev.uuid.isEmpty())
7008 rc = mParent->findFloppyImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7009 /* find a floppy by host device name */
7010 else if (!dev.strHostDriveSrc.isEmpty())
7011 {
7012 SafeIfaceArray<IMedium> drivevec;
7013 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
7014 if (SUCCEEDED(rc))
7015 {
7016 for (size_t i = 0; i < drivevec.size(); ++i)
7017 {
7018 /// @todo eliminate this conversion
7019 ComObjPtr<Medium> med = (Medium *)drivevec[i];
7020 if ( dev.strHostDriveSrc == med->getName()
7021 || dev.strHostDriveSrc == med->getLocation())
7022 {
7023 medium = med;
7024 break;
7025 }
7026 }
7027 }
7028 }
7029 break;
7030
7031 case DeviceType_DVD:
7032 /* find a DVD by UUID */
7033 if (!dev.uuid.isEmpty())
7034 rc = mParent->findDVDImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7035 /* find a DVD by host device name */
7036 else if (!dev.strHostDriveSrc.isEmpty())
7037 {
7038 SafeIfaceArray<IMedium> drivevec;
7039 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
7040 if (SUCCEEDED(rc))
7041 {
7042 for (size_t i = 0; i < drivevec.size(); ++i)
7043 {
7044 Bstr hostDriveSrc(dev.strHostDriveSrc);
7045 /// @todo eliminate this conversion
7046 ComObjPtr<Medium> med = (Medium *)drivevec[i];
7047 if ( hostDriveSrc == med->getName()
7048 || hostDriveSrc == med->getLocation())
7049 {
7050 medium = med;
7051 break;
7052 }
7053 }
7054 }
7055 }
7056 break;
7057
7058 case DeviceType_HardDisk:
7059 {
7060 /* find a hard disk by UUID */
7061 rc = mParent->findHardDisk(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7062 if (FAILED(rc))
7063 {
7064 VBoxClsID clsid = getClassID();
7065 if (clsid == clsidSnapshotMachine)
7066 {
7067 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7068 // so the user knows that the bad disk is in a snapshot somewhere
7069 com::ErrorInfo info;
7070 return setError(E_FAIL,
7071 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7072 aSnapshotId->raw(),
7073 info.getText().raw());
7074 }
7075 else
7076 return rc;
7077 }
7078
7079 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7080
7081 if (medium->getType() == MediumType_Immutable)
7082 {
7083 if (getClassID() == clsidSnapshotMachine)
7084 return setError(E_FAIL,
7085 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7086 "of the virtual machine '%ls' ('%s')"),
7087 medium->getLocationFull().raw(),
7088 dev.uuid.raw(),
7089 aSnapshotId->raw(),
7090 mUserData->mName.raw(),
7091 mData->m_strConfigFileFull.raw());
7092
7093 return setError(E_FAIL,
7094 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s')"),
7095 medium->getLocationFull().raw(),
7096 dev.uuid.raw(),
7097 mUserData->mName.raw(),
7098 mData->m_strConfigFileFull.raw());
7099 }
7100
7101 if ( getClassID() != clsidSnapshotMachine
7102 && medium->getChildren().size() != 0
7103 )
7104 return setError(E_FAIL,
7105 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s') "
7106 "because it has %d differencing child hard disks"),
7107 medium->getLocationFull().raw(),
7108 dev.uuid.raw(),
7109 mUserData->mName.raw(),
7110 mData->m_strConfigFileFull.raw(),
7111 medium->getChildren().size());
7112
7113 if (findAttachment(mMediaData->mAttachments,
7114 medium))
7115 return setError(E_FAIL,
7116 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%ls' ('%s')"),
7117 medium->getLocationFull().raw(),
7118 dev.uuid.raw(),
7119 mUserData->mName.raw(),
7120 mData->m_strConfigFileFull.raw());
7121
7122 break;
7123 }
7124
7125 default:
7126 return setError(E_FAIL,
7127 tr("Device with unknown type is attached to the virtual machine '%s' ('%s')"),
7128 medium->getLocationFull().raw(),
7129 mUserData->mName.raw(),
7130 mData->m_strConfigFileFull.raw());
7131 }
7132
7133 if (FAILED(rc))
7134 break;
7135
7136 const Bstr controllerName = aStorageController->getName();
7137 ComObjPtr<MediumAttachment> pAttachment;
7138 pAttachment.createObject();
7139 rc = pAttachment->init(this,
7140 medium,
7141 controllerName,
7142 dev.lPort,
7143 dev.lDevice,
7144 dev.deviceType,
7145 dev.fPassThrough);
7146 if (FAILED(rc)) break;
7147
7148 /* associate the medium with this machine and snapshot */
7149 if (!medium.isNull())
7150 {
7151 if (getClassID() == clsidSnapshotMachine)
7152 rc = medium->attachTo(mData->mUuid, *aSnapshotId);
7153 else
7154 rc = medium->attachTo(mData->mUuid);
7155 }
7156
7157 if (FAILED(rc))
7158 break;
7159
7160 /* back up mMediaData to let registeredInit() properly rollback on failure
7161 * (= limited accessibility) */
7162 setModified(IsModified_Storage);
7163 mMediaData.backup();
7164 mMediaData->mAttachments.push_back(pAttachment);
7165 }
7166
7167 return rc;
7168}
7169
7170/**
7171 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7172 *
7173 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7174 * @param aSnapshot where to return the found snapshot
7175 * @param aSetError true to set extended error info on failure
7176 */
7177HRESULT Machine::findSnapshot(const Guid &aId,
7178 ComObjPtr<Snapshot> &aSnapshot,
7179 bool aSetError /* = false */)
7180{
7181 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7182
7183 if (!mData->mFirstSnapshot)
7184 {
7185 if (aSetError)
7186 return setError(E_FAIL,
7187 tr("This machine does not have any snapshots"));
7188 return E_FAIL;
7189 }
7190
7191 if (aId.isEmpty())
7192 aSnapshot = mData->mFirstSnapshot;
7193 else
7194 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
7195
7196 if (!aSnapshot)
7197 {
7198 if (aSetError)
7199 return setError(E_FAIL,
7200 tr("Could not find a snapshot with UUID {%s}"),
7201 aId.toString().raw());
7202 return E_FAIL;
7203 }
7204
7205 return S_OK;
7206}
7207
7208/**
7209 * Returns the snapshot with the given name or fails of no such snapshot.
7210 *
7211 * @param aName snapshot name to find
7212 * @param aSnapshot where to return the found snapshot
7213 * @param aSetError true to set extended error info on failure
7214 */
7215HRESULT Machine::findSnapshot(IN_BSTR aName,
7216 ComObjPtr<Snapshot> &aSnapshot,
7217 bool aSetError /* = false */)
7218{
7219 AssertReturn(aName, E_INVALIDARG);
7220
7221 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7222
7223 if (!mData->mFirstSnapshot)
7224 {
7225 if (aSetError)
7226 return setError(VBOX_E_OBJECT_NOT_FOUND,
7227 tr("This machine does not have any snapshots"));
7228 return VBOX_E_OBJECT_NOT_FOUND;
7229 }
7230
7231 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aName);
7232
7233 if (!aSnapshot)
7234 {
7235 if (aSetError)
7236 return setError(VBOX_E_OBJECT_NOT_FOUND,
7237 tr("Could not find a snapshot named '%ls'"), aName);
7238 return VBOX_E_OBJECT_NOT_FOUND;
7239 }
7240
7241 return S_OK;
7242}
7243
7244/**
7245 * Returns a storage controller object with the given name.
7246 *
7247 * @param aName storage controller name to find
7248 * @param aStorageController where to return the found storage controller
7249 * @param aSetError true to set extended error info on failure
7250 */
7251HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7252 ComObjPtr<StorageController> &aStorageController,
7253 bool aSetError /* = false */)
7254{
7255 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7256
7257 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7258 it != mStorageControllers->end();
7259 ++it)
7260 {
7261 if ((*it)->getName() == aName)
7262 {
7263 aStorageController = (*it);
7264 return S_OK;
7265 }
7266 }
7267
7268 if (aSetError)
7269 return setError(VBOX_E_OBJECT_NOT_FOUND,
7270 tr("Could not find a storage controller named '%s'"),
7271 aName.raw());
7272 return VBOX_E_OBJECT_NOT_FOUND;
7273}
7274
7275HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7276 MediaData::AttachmentList &atts)
7277{
7278 AutoCaller autoCaller(this);
7279 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7280
7281 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7282
7283 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7284 it != mMediaData->mAttachments.end();
7285 ++it)
7286 {
7287 if ((*it)->getControllerName() == aName)
7288 atts.push_back(*it);
7289 }
7290
7291 return S_OK;
7292}
7293
7294/**
7295 * Helper for #saveSettings. Cares about renaming the settings directory and
7296 * file if the machine name was changed and about creating a new settings file
7297 * if this is a new machine.
7298 *
7299 * @note Must be never called directly but only from #saveSettings().
7300 */
7301HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7302{
7303 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7304
7305 HRESULT rc = S_OK;
7306
7307 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7308
7309 /* attempt to rename the settings file if machine name is changed */
7310 if ( mUserData->mNameSync
7311 && mUserData.isBackedUp()
7312 && mUserData.backedUpData()->mName != mUserData->mName
7313 )
7314 {
7315 bool dirRenamed = false;
7316 bool fileRenamed = false;
7317
7318 Utf8Str configFile, newConfigFile;
7319 Utf8Str configDir, newConfigDir;
7320
7321 do
7322 {
7323 int vrc = VINF_SUCCESS;
7324
7325 Utf8Str name = mUserData.backedUpData()->mName;
7326 Utf8Str newName = mUserData->mName;
7327
7328 configFile = mData->m_strConfigFileFull;
7329
7330 /* first, rename the directory if it matches the machine name */
7331 configDir = configFile;
7332 configDir.stripFilename();
7333 newConfigDir = configDir;
7334 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7335 {
7336 newConfigDir.stripFilename();
7337 newConfigDir = Utf8StrFmt("%s%c%s",
7338 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
7339 /* new dir and old dir cannot be equal here because of 'if'
7340 * above and because name != newName */
7341 Assert(configDir != newConfigDir);
7342 if (!fSettingsFileIsNew)
7343 {
7344 /* perform real rename only if the machine is not new */
7345 vrc = RTPathRename(configDir.raw(), newConfigDir.raw(), 0);
7346 if (RT_FAILURE(vrc))
7347 {
7348 rc = setError(E_FAIL,
7349 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7350 configDir.raw(),
7351 newConfigDir.raw(),
7352 vrc);
7353 break;
7354 }
7355 dirRenamed = true;
7356 }
7357 }
7358
7359 newConfigFile = Utf8StrFmt("%s%c%s.xml",
7360 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
7361
7362 /* then try to rename the settings file itself */
7363 if (newConfigFile != configFile)
7364 {
7365 /* get the path to old settings file in renamed directory */
7366 configFile = Utf8StrFmt("%s%c%s",
7367 newConfigDir.raw(),
7368 RTPATH_DELIMITER,
7369 RTPathFilename(configFile.c_str()));
7370 if (!fSettingsFileIsNew)
7371 {
7372 /* perform real rename only if the machine is not new */
7373 vrc = RTFileRename(configFile.raw(), newConfigFile.raw(), 0);
7374 if (RT_FAILURE(vrc))
7375 {
7376 rc = setError(E_FAIL,
7377 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7378 configFile.raw(),
7379 newConfigFile.raw(),
7380 vrc);
7381 break;
7382 }
7383 fileRenamed = true;
7384 }
7385 }
7386
7387 /* update m_strConfigFileFull amd mConfigFile */
7388 mData->m_strConfigFileFull = newConfigFile;
7389
7390 // compute the relative path too
7391 Utf8Str path = newConfigFile;
7392 mParent->calculateRelativePath(path, path);
7393 mData->m_strConfigFile = path;
7394
7395 // store the old and new so that VirtualBox::saveSettings() can update
7396 // the media registry
7397 if ( mData->mRegistered
7398 && configDir != newConfigDir)
7399 {
7400 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7401
7402 if (pfNeedsGlobalSaveSettings)
7403 *pfNeedsGlobalSaveSettings = true;
7404 }
7405
7406 /* update the snapshot folder */
7407 path = mUserData->mSnapshotFolderFull;
7408 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7409 {
7410 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
7411 path.raw() + configDir.length());
7412 mUserData->mSnapshotFolderFull = path;
7413 calculateRelativePath(path, path);
7414 mUserData->mSnapshotFolder = path;
7415 }
7416
7417 /* update the saved state file path */
7418 path = mSSData->mStateFilePath;
7419 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7420 {
7421 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
7422 path.raw() + configDir.length());
7423 mSSData->mStateFilePath = path;
7424 }
7425
7426 /* Update saved state file paths of all online snapshots.
7427 * Note that saveSettings() will recognize name change
7428 * and will save all snapshots in this case. */
7429 if (mData->mFirstSnapshot)
7430 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7431 newConfigDir.c_str());
7432 }
7433 while (0);
7434
7435 if (FAILED(rc))
7436 {
7437 /* silently try to rename everything back */
7438 if (fileRenamed)
7439 RTFileRename(newConfigFile.raw(), configFile.raw(), 0);
7440 if (dirRenamed)
7441 RTPathRename(newConfigDir.raw(), configDir.raw(), 0);
7442 }
7443
7444 if (FAILED(rc)) return rc;
7445 }
7446
7447 if (fSettingsFileIsNew)
7448 {
7449 /* create a virgin config file */
7450 int vrc = VINF_SUCCESS;
7451
7452 /* ensure the settings directory exists */
7453 Utf8Str path(mData->m_strConfigFileFull);
7454 path.stripFilename();
7455 if (!RTDirExists(path.c_str()))
7456 {
7457 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7458 if (RT_FAILURE(vrc))
7459 {
7460 return setError(E_FAIL,
7461 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7462 path.raw(),
7463 vrc);
7464 }
7465 }
7466
7467 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7468 path = Utf8Str(mData->m_strConfigFileFull);
7469 RTFILE f = NIL_RTFILE;
7470 vrc = RTFileOpen(&f, path.c_str(),
7471 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7472 if (RT_FAILURE(vrc))
7473 return setError(E_FAIL,
7474 tr("Could not create the settings file '%s' (%Rrc)"),
7475 path.raw(),
7476 vrc);
7477 RTFileClose(f);
7478 }
7479
7480 return rc;
7481}
7482
7483/**
7484 * Saves and commits machine data, user data and hardware data.
7485 *
7486 * Note that on failure, the data remains uncommitted.
7487 *
7488 * @a aFlags may combine the following flags:
7489 *
7490 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7491 * Used when saving settings after an operation that makes them 100%
7492 * correspond to the settings from the current snapshot.
7493 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7494 * #isReallyModified() returns false. This is necessary for cases when we
7495 * change machine data directly, not through the backup()/commit() mechanism.
7496 * - SaveS_Force: settings will be saved without doing a deep compare of the
7497 * settings structures. This is used when this is called because snapshots
7498 * have changed to avoid the overhead of the deep compare.
7499 *
7500 * @note Must be called from under this object's write lock. Locks children for
7501 * writing.
7502 *
7503 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7504 * initialized to false and that will be set to true by this function if
7505 * the caller must invoke VirtualBox::saveSettings() because the global
7506 * settings have changed. This will happen if a machine rename has been
7507 * saved and the global machine and media registries will therefore need
7508 * updating.
7509 */
7510HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7511 int aFlags /*= 0*/)
7512{
7513 LogFlowThisFuncEnter();
7514
7515 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7516
7517 /* make sure child objects are unable to modify the settings while we are
7518 * saving them */
7519 ensureNoStateDependencies();
7520
7521 AssertReturn( getClassID() == clsidMachine
7522 || getClassID() == clsidSessionMachine,
7523 E_FAIL);
7524
7525 HRESULT rc = S_OK;
7526 bool fNeedsWrite = false;
7527
7528 /* First, prepare to save settings. It will care about renaming the
7529 * settings directory and file if the machine name was changed and about
7530 * creating a new settings file if this is a new machine. */
7531 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7532 if (FAILED(rc)) return rc;
7533
7534 // keep a pointer to the current settings structures
7535 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7536 settings::MachineConfigFile *pNewConfig = NULL;
7537
7538 try
7539 {
7540 // make a fresh one to have everyone write stuff into
7541 pNewConfig = new settings::MachineConfigFile(NULL);
7542 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7543
7544 // now go and copy all the settings data from COM to the settings structures
7545 // (this calles saveSettings() on all the COM objects in the machine)
7546 copyMachineDataToSettings(*pNewConfig);
7547
7548 if (aFlags & SaveS_ResetCurStateModified)
7549 {
7550 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7551 mData->mCurrentStateModified = FALSE;
7552 fNeedsWrite = true; // always, no need to compare
7553 }
7554 else if (aFlags & SaveS_Force)
7555 {
7556 fNeedsWrite = true; // always, no need to compare
7557 }
7558 else
7559 {
7560 if (!mData->mCurrentStateModified)
7561 {
7562 // do a deep compare of the settings that we just saved with the settings
7563 // previously stored in the config file; this invokes MachineConfigFile::operator==
7564 // which does a deep compare of all the settings, which is expensive but less expensive
7565 // than writing out XML in vain
7566 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7567
7568 // could still be modified if any settings changed
7569 mData->mCurrentStateModified = fAnySettingsChanged;
7570
7571 fNeedsWrite = fAnySettingsChanged;
7572 }
7573 else
7574 fNeedsWrite = true;
7575 }
7576
7577 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7578
7579 if (fNeedsWrite)
7580 // now spit it all out!
7581 pNewConfig->write(mData->m_strConfigFileFull);
7582
7583 mData->pMachineConfigFile = pNewConfig;
7584 delete pOldConfig;
7585 commit();
7586
7587 // after saving settings, we are no longer different from the XML on disk
7588 mData->flModifications = 0;
7589 }
7590 catch (HRESULT err)
7591 {
7592 // we assume that error info is set by the thrower
7593 rc = err;
7594
7595 // restore old config
7596 delete pNewConfig;
7597 mData->pMachineConfigFile = pOldConfig;
7598 }
7599 catch (...)
7600 {
7601 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7602 }
7603
7604 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7605 {
7606 /* Fire the data change event, even on failure (since we've already
7607 * committed all data). This is done only for SessionMachines because
7608 * mutable Machine instances are always not registered (i.e. private
7609 * to the client process that creates them) and thus don't need to
7610 * inform callbacks. */
7611 if (getClassID() == clsidSessionMachine)
7612 mParent->onMachineDataChange(mData->mUuid);
7613 }
7614
7615 LogFlowThisFunc(("rc=%08X\n", rc));
7616 LogFlowThisFuncLeave();
7617 return rc;
7618}
7619
7620/**
7621 * Implementation for saving the machine settings into the given
7622 * settings::MachineConfigFile instance. This copies machine extradata
7623 * from the previous machine config file in the instance data, if any.
7624 *
7625 * This gets called from two locations:
7626 *
7627 * -- Machine::saveSettings(), during the regular XML writing;
7628 *
7629 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7630 * exported to OVF and we write the VirtualBox proprietary XML
7631 * into a <vbox:Machine> tag.
7632 *
7633 * This routine fills all the fields in there, including snapshots, *except*
7634 * for the following:
7635 *
7636 * -- fCurrentStateModified. There is some special logic associated with that.
7637 *
7638 * The caller can then call MachineConfigFile::write() or do something else
7639 * with it.
7640 *
7641 * Caller must hold the machine lock!
7642 *
7643 * This throws XML errors and HRESULT, so the caller must have a catch block!
7644 */
7645void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7646{
7647 // deep copy extradata
7648 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7649
7650 config.uuid = mData->mUuid;
7651 config.strName = mUserData->mName;
7652 config.fNameSync = !!mUserData->mNameSync;
7653 config.strDescription = mUserData->mDescription;
7654 config.strOsType = mUserData->mOSTypeId;
7655
7656 if ( mData->mMachineState == MachineState_Saved
7657 || mData->mMachineState == MachineState_Restoring
7658 // when deleting a snapshot we may or may not have a saved state in the current state,
7659 // so let's not assert here please
7660 || ( (mData->mMachineState == MachineState_DeletingSnapshot)
7661 && (!mSSData->mStateFilePath.isEmpty())
7662 )
7663 )
7664 {
7665 Assert(!mSSData->mStateFilePath.isEmpty());
7666 /* try to make the file name relative to the settings file dir */
7667 calculateRelativePath(mSSData->mStateFilePath, config.strStateFile);
7668 }
7669 else
7670 {
7671 Assert(mSSData->mStateFilePath.isEmpty());
7672 config.strStateFile.setNull();
7673 }
7674
7675 if (mData->mCurrentSnapshot)
7676 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7677 else
7678 config.uuidCurrentSnapshot.clear();
7679
7680 config.strSnapshotFolder = mUserData->mSnapshotFolder;
7681 // config.fCurrentStateModified is special, see below
7682 config.timeLastStateChange = mData->mLastStateChange;
7683 config.fAborted = (mData->mMachineState == MachineState_Aborted);
7684 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
7685
7686 config.fTeleporterEnabled = !!mUserData->mTeleporterEnabled;
7687 config.uTeleporterPort = mUserData->mTeleporterPort;
7688 config.strTeleporterAddress = mUserData->mTeleporterAddress;
7689 config.strTeleporterPassword = mUserData->mTeleporterPassword;
7690
7691 config.fRTCUseUTC = !!mUserData->mRTCUseUTC;
7692
7693 HRESULT rc = saveHardware(config.hardwareMachine);
7694 if (FAILED(rc)) throw rc;
7695
7696 rc = saveStorageControllers(config.storageMachine);
7697 if (FAILED(rc)) throw rc;
7698
7699 // save snapshots
7700 rc = saveAllSnapshots(config);
7701 if (FAILED(rc)) throw rc;
7702}
7703
7704/**
7705 * Saves all snapshots of the machine into the given machine config file. Called
7706 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
7707 * @param config
7708 * @return
7709 */
7710HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
7711{
7712 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7713
7714 HRESULT rc = S_OK;
7715
7716 try
7717 {
7718 config.llFirstSnapshot.clear();
7719
7720 if (mData->mFirstSnapshot)
7721 {
7722 settings::Snapshot snapNew;
7723 config.llFirstSnapshot.push_back(snapNew);
7724
7725 // get reference to the fresh copy of the snapshot on the list and
7726 // work on that copy directly to avoid excessive copying later
7727 settings::Snapshot &snap = config.llFirstSnapshot.front();
7728
7729 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
7730 if (FAILED(rc)) throw rc;
7731 }
7732
7733// if (mType == IsSessionMachine)
7734// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
7735
7736 }
7737 catch (HRESULT err)
7738 {
7739 /* we assume that error info is set by the thrower */
7740 rc = err;
7741 }
7742 catch (...)
7743 {
7744 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7745 }
7746
7747 return rc;
7748}
7749
7750/**
7751 * Saves the VM hardware configuration. It is assumed that the
7752 * given node is empty.
7753 *
7754 * @param aNode <Hardware> node to save the VM hardware confguration to.
7755 */
7756HRESULT Machine::saveHardware(settings::Hardware &data)
7757{
7758 HRESULT rc = S_OK;
7759
7760 try
7761 {
7762 /* The hardware version attribute (optional).
7763 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
7764 if ( mHWData->mHWVersion == "1"
7765 && mSSData->mStateFilePath.isEmpty()
7766 )
7767 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. */
7768
7769 data.strVersion = mHWData->mHWVersion;
7770 data.uuid = mHWData->mHardwareUUID;
7771
7772 // CPU
7773 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
7774 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
7775 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
7776 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
7777 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
7778 data.fPAE = !!mHWData->mPAEEnabled;
7779 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
7780
7781 /* Standard and Extended CPUID leafs. */
7782 data.llCpuIdLeafs.clear();
7783 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
7784 {
7785 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
7786 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
7787 }
7788 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
7789 {
7790 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
7791 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
7792 }
7793
7794 data.cCPUs = mHWData->mCPUCount;
7795 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
7796
7797 data.llCpus.clear();
7798 if (data.fCpuHotPlug)
7799 {
7800 for (unsigned idx = 0; idx < data.cCPUs; idx++)
7801 {
7802 if (mHWData->mCPUAttached[idx])
7803 {
7804 settings::Cpu cpu;
7805 cpu.ulId = idx;
7806 data.llCpus.push_back(cpu);
7807 }
7808 }
7809 }
7810
7811 // memory
7812 data.ulMemorySizeMB = mHWData->mMemorySize;
7813
7814 // firmware
7815 data.firmwareType = mHWData->mFirmwareType;
7816
7817 // HID
7818 data.pointingHidType = mHWData->mPointingHidType;
7819 data.keyboardHidType = mHWData->mKeyboardHidType;
7820
7821 // HPET
7822 data.fHpetEnabled = !!mHWData->mHpetEnabled;
7823
7824 // boot order
7825 data.mapBootOrder.clear();
7826 for (size_t i = 0;
7827 i < RT_ELEMENTS(mHWData->mBootOrder);
7828 ++i)
7829 data.mapBootOrder[i] = mHWData->mBootOrder[i];
7830
7831 // display
7832 data.ulVRAMSizeMB = mHWData->mVRAMSize;
7833 data.cMonitors = mHWData->mMonitorCount;
7834 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
7835 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
7836
7837#ifdef VBOX_WITH_VRDP
7838 /* VRDP settings (optional) */
7839 rc = mVRDPServer->saveSettings(data.vrdpSettings);
7840 if (FAILED(rc)) throw rc;
7841#endif
7842
7843 /* BIOS (required) */
7844 rc = mBIOSSettings->saveSettings(data.biosSettings);
7845 if (FAILED(rc)) throw rc;
7846
7847 /* USB Controller (required) */
7848 rc = mUSBController->saveSettings(data.usbController);
7849 if (FAILED(rc)) throw rc;
7850
7851 /* Network adapters (required) */
7852 data.llNetworkAdapters.clear();
7853 for (ULONG slot = 0;
7854 slot < RT_ELEMENTS(mNetworkAdapters);
7855 ++slot)
7856 {
7857 settings::NetworkAdapter nic;
7858 nic.ulSlot = slot;
7859 rc = mNetworkAdapters[slot]->saveSettings(nic);
7860 if (FAILED(rc)) throw rc;
7861
7862 data.llNetworkAdapters.push_back(nic);
7863 }
7864
7865 /* Serial ports */
7866 data.llSerialPorts.clear();
7867 for (ULONG slot = 0;
7868 slot < RT_ELEMENTS(mSerialPorts);
7869 ++slot)
7870 {
7871 settings::SerialPort s;
7872 s.ulSlot = slot;
7873 rc = mSerialPorts[slot]->saveSettings(s);
7874 if (FAILED(rc)) return rc;
7875
7876 data.llSerialPorts.push_back(s);
7877 }
7878
7879 /* Parallel ports */
7880 data.llParallelPorts.clear();
7881 for (ULONG slot = 0;
7882 slot < RT_ELEMENTS(mParallelPorts);
7883 ++slot)
7884 {
7885 settings::ParallelPort p;
7886 p.ulSlot = slot;
7887 rc = mParallelPorts[slot]->saveSettings(p);
7888 if (FAILED(rc)) return rc;
7889
7890 data.llParallelPorts.push_back(p);
7891 }
7892
7893 /* Audio adapter */
7894 rc = mAudioAdapter->saveSettings(data.audioAdapter);
7895 if (FAILED(rc)) return rc;
7896
7897 /* Shared folders */
7898 data.llSharedFolders.clear();
7899 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7900 it != mHWData->mSharedFolders.end();
7901 ++it)
7902 {
7903 ComObjPtr<SharedFolder> pFolder = *it;
7904 settings::SharedFolder sf;
7905 sf.strName = pFolder->getName();
7906 sf.strHostPath = pFolder->getHostPath();
7907 sf.fWritable = !!pFolder->isWritable();
7908
7909 data.llSharedFolders.push_back(sf);
7910 }
7911
7912 // clipboard
7913 data.clipboardMode = mHWData->mClipboardMode;
7914
7915 /* Guest */
7916 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
7917
7918 // IO settings
7919 data.ioSettings.ioMgrType = mHWData->mIoMgrType;
7920 data.ioSettings.ioBackendType = mHWData->mIoBackendType;
7921 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
7922 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
7923 data.ioSettings.ulIoBandwidthMax = mHWData->mIoBandwidthMax;
7924
7925 // guest properties
7926 data.llGuestProperties.clear();
7927#ifdef VBOX_WITH_GUEST_PROPS
7928 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
7929 it != mHWData->mGuestProperties.end();
7930 ++it)
7931 {
7932 HWData::GuestProperty property = *it;
7933
7934 /* Remove transient guest properties at shutdown unless we
7935 * are saving state */
7936 if ( ( mData->mMachineState == MachineState_PoweredOff
7937 || mData->mMachineState == MachineState_Aborted
7938 || mData->mMachineState == MachineState_Teleported)
7939 && property.mFlags & guestProp::TRANSIENT)
7940 continue;
7941 settings::GuestProperty prop;
7942 prop.strName = property.strName;
7943 prop.strValue = property.strValue;
7944 prop.timestamp = property.mTimestamp;
7945 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
7946 guestProp::writeFlags(property.mFlags, szFlags);
7947 prop.strFlags = szFlags;
7948
7949 data.llGuestProperties.push_back(prop);
7950 }
7951
7952 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
7953 /* I presume this doesn't require a backup(). */
7954 mData->mGuestPropertiesModified = FALSE;
7955#endif /* VBOX_WITH_GUEST_PROPS defined */
7956 }
7957 catch(std::bad_alloc &)
7958 {
7959 return E_OUTOFMEMORY;
7960 }
7961
7962 AssertComRC(rc);
7963 return rc;
7964}
7965
7966/**
7967 * Saves the storage controller configuration.
7968 *
7969 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
7970 */
7971HRESULT Machine::saveStorageControllers(settings::Storage &data)
7972{
7973 data.llStorageControllers.clear();
7974
7975 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7976 it != mStorageControllers->end();
7977 ++it)
7978 {
7979 HRESULT rc;
7980 ComObjPtr<StorageController> pCtl = *it;
7981
7982 settings::StorageController ctl;
7983 ctl.strName = pCtl->getName();
7984 ctl.controllerType = pCtl->getControllerType();
7985 ctl.storageBus = pCtl->getStorageBus();
7986 ctl.ulInstance = pCtl->getInstance();
7987
7988 /* Save the port count. */
7989 ULONG portCount;
7990 rc = pCtl->COMGETTER(PortCount)(&portCount);
7991 ComAssertComRCRet(rc, rc);
7992 ctl.ulPortCount = portCount;
7993
7994 /* Save IDE emulation settings. */
7995 if (ctl.controllerType == StorageControllerType_IntelAhci)
7996 {
7997 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
7998 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
7999 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8000 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8001 )
8002 ComAssertComRCRet(rc, rc);
8003 }
8004
8005 /* save the devices now. */
8006 rc = saveStorageDevices(pCtl, ctl);
8007 ComAssertComRCRet(rc, rc);
8008
8009 data.llStorageControllers.push_back(ctl);
8010 }
8011
8012 return S_OK;
8013}
8014
8015/**
8016 * Saves the hard disk confguration.
8017 */
8018HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8019 settings::StorageController &data)
8020{
8021 MediaData::AttachmentList atts;
8022
8023 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()), atts);
8024 if (FAILED(rc)) return rc;
8025
8026 data.llAttachedDevices.clear();
8027 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8028 it != atts.end();
8029 ++it)
8030 {
8031 settings::AttachedDevice dev;
8032
8033 MediumAttachment *pAttach = *it;
8034 Medium *pMedium = pAttach->getMedium();
8035
8036 dev.deviceType = pAttach->getType();
8037 dev.lPort = pAttach->getPort();
8038 dev.lDevice = pAttach->getDevice();
8039 if (pMedium)
8040 {
8041 BOOL fHostDrive = FALSE;
8042 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
8043 if (FAILED(rc))
8044 return rc;
8045 if (fHostDrive)
8046 dev.strHostDriveSrc = pMedium->getLocation();
8047 else
8048 dev.uuid = pMedium->getId();
8049 dev.fPassThrough = pAttach->getPassthrough();
8050 }
8051
8052 data.llAttachedDevices.push_back(dev);
8053 }
8054
8055 return S_OK;
8056}
8057
8058/**
8059 * Saves machine state settings as defined by aFlags
8060 * (SaveSTS_* values).
8061 *
8062 * @param aFlags Combination of SaveSTS_* flags.
8063 *
8064 * @note Locks objects for writing.
8065 */
8066HRESULT Machine::saveStateSettings(int aFlags)
8067{
8068 if (aFlags == 0)
8069 return S_OK;
8070
8071 AutoCaller autoCaller(this);
8072 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8073
8074 /* This object's write lock is also necessary to serialize file access
8075 * (prevent concurrent reads and writes) */
8076 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8077
8078 HRESULT rc = S_OK;
8079
8080 Assert(mData->pMachineConfigFile);
8081
8082 try
8083 {
8084 if (aFlags & SaveSTS_CurStateModified)
8085 mData->pMachineConfigFile->fCurrentStateModified = true;
8086
8087 if (aFlags & SaveSTS_StateFilePath)
8088 {
8089 if (!mSSData->mStateFilePath.isEmpty())
8090 /* try to make the file name relative to the settings file dir */
8091 calculateRelativePath(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8092 else
8093 mData->pMachineConfigFile->strStateFile.setNull();
8094 }
8095
8096 if (aFlags & SaveSTS_StateTimeStamp)
8097 {
8098 Assert( mData->mMachineState != MachineState_Aborted
8099 || mSSData->mStateFilePath.isEmpty());
8100
8101 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8102
8103 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8104//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8105 }
8106
8107 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8108 }
8109 catch (...)
8110 {
8111 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8112 }
8113
8114 return rc;
8115}
8116
8117/**
8118 * Creates differencing hard disks for all normal hard disks attached to this
8119 * machine and a new set of attachments to refer to created disks.
8120 *
8121 * Used when taking a snapshot or when discarding the current state.
8122 *
8123 * This method assumes that mMediaData contains the original hard disk attachments
8124 * it needs to create diffs for. On success, these attachments will be replaced
8125 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8126 * called to delete created diffs which will also rollback mMediaData and restore
8127 * whatever was backed up before calling this method.
8128 *
8129 * Attachments with non-normal hard disks are left as is.
8130 *
8131 * If @a aOnline is @c false then the original hard disks that require implicit
8132 * diffs will be locked for reading. Otherwise it is assumed that they are
8133 * already locked for writing (when the VM was started). Note that in the latter
8134 * case it is responsibility of the caller to lock the newly created diffs for
8135 * writing if this method succeeds.
8136 *
8137 * @param aFolder Folder where to create diff hard disks.
8138 * @param aProgress Progress object to run (must contain at least as
8139 * many operations left as the number of hard disks
8140 * attached).
8141 * @param aOnline Whether the VM was online prior to this operation.
8142 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8143 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8144 *
8145 * @note The progress object is not marked as completed, neither on success nor
8146 * on failure. This is a responsibility of the caller.
8147 *
8148 * @note Locks this object for writing.
8149 */
8150HRESULT Machine::createImplicitDiffs(const Bstr &aFolder,
8151 IProgress *aProgress,
8152 ULONG aWeight,
8153 bool aOnline,
8154 bool *pfNeedsSaveSettings)
8155{
8156 AssertReturn(!aFolder.isEmpty(), E_FAIL);
8157
8158 LogFlowThisFunc(("aFolder='%ls', aOnline=%d\n", aFolder.raw(), aOnline));
8159
8160 AutoCaller autoCaller(this);
8161 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8162
8163 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8164
8165 /* must be in a protective state because we leave the lock below */
8166 AssertReturn( mData->mMachineState == MachineState_Saving
8167 || mData->mMachineState == MachineState_LiveSnapshotting
8168 || mData->mMachineState == MachineState_RestoringSnapshot
8169 || mData->mMachineState == MachineState_DeletingSnapshot
8170 , E_FAIL);
8171
8172 HRESULT rc = S_OK;
8173
8174 MediaList lockedMedia;
8175
8176 try
8177 {
8178 if (!aOnline)
8179 {
8180 /* lock all attached hard disks early to detect "in use"
8181 * situations before creating actual diffs */
8182 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8183 it != mMediaData->mAttachments.end();
8184 ++it)
8185 {
8186 MediumAttachment* pAtt = *it;
8187 if (pAtt->getType() == DeviceType_HardDisk)
8188 {
8189 Medium* pHD = pAtt->getMedium();
8190 Assert(pHD);
8191 rc = pHD->LockRead(NULL);
8192 if (FAILED(rc)) throw rc;
8193 lockedMedia.push_back(pHD);
8194 }
8195 }
8196 }
8197
8198 /* remember the current list (note that we don't use backup() since
8199 * mMediaData may be already backed up) */
8200 MediaData::AttachmentList atts = mMediaData->mAttachments;
8201
8202 /* start from scratch */
8203 mMediaData->mAttachments.clear();
8204
8205 /* go through remembered attachments and create diffs for normal hard
8206 * disks and attach them */
8207 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8208 it != atts.end();
8209 ++it)
8210 {
8211 MediumAttachment* pAtt = *it;
8212
8213 DeviceType_T devType = pAtt->getType();
8214 Medium* medium = pAtt->getMedium();
8215
8216 if ( devType != DeviceType_HardDisk
8217 || medium == NULL
8218 || medium->getType() != MediumType_Normal)
8219 {
8220 /* copy the attachment as is */
8221
8222 /** @todo the progress object created in Console::TakeSnaphot
8223 * only expects operations for hard disks. Later other
8224 * device types need to show up in the progress as well. */
8225 if (devType == DeviceType_HardDisk)
8226 {
8227 if (medium == NULL)
8228 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
8229 aWeight); // weight
8230 else
8231 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8232 medium->getBase()->getName().raw()),
8233 aWeight); // weight
8234 }
8235
8236 mMediaData->mAttachments.push_back(pAtt);
8237 continue;
8238 }
8239
8240 /* need a diff */
8241 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8242 medium->getBase()->getName().raw()),
8243 aWeight); // weight
8244
8245 ComObjPtr<Medium> diff;
8246 diff.createObject();
8247 rc = diff->init(mParent,
8248 medium->preferredDiffFormat().raw(),
8249 BstrFmt("%ls"RTPATH_SLASH_STR,
8250 mUserData->mSnapshotFolderFull.raw()).raw(),
8251 pfNeedsSaveSettings);
8252 if (FAILED(rc)) throw rc;
8253
8254 /* leave the lock before the potentially lengthy operation */
8255 alock.leave();
8256
8257 rc = medium->createDiffStorageAndWait(diff,
8258 MediumVariant_Standard,
8259 pfNeedsSaveSettings);
8260
8261 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8262 * the push_back? Looks like we're going to leave medium with the
8263 * wrong kind of lock (general issue with if we fail anywhere at all)
8264 * and an orphaned VDI in the snapshots folder. */
8265 // at this point, the old image is still locked for writing, but instead
8266 // we need the new diff image locked for writing and lock the previously
8267 // current one for reading only
8268 if (aOnline)
8269 {
8270 diff->LockWrite(NULL);
8271 mData->mSession.mLockedMedia.push_back(Data::Session::LockedMedia::value_type(ComPtr<IMedium>(diff), true));
8272 medium->UnlockWrite(NULL);
8273 medium->LockRead(NULL);
8274 mData->mSession.mLockedMedia.push_back(Data::Session::LockedMedia::value_type(ComPtr<IMedium>(medium), false));
8275 }
8276
8277 if (FAILED(rc)) throw rc;
8278
8279 alock.enter();
8280
8281 rc = diff->attachTo(mData->mUuid);
8282 AssertComRCThrowRC(rc);
8283
8284 /* add a new attachment */
8285 ComObjPtr<MediumAttachment> attachment;
8286 attachment.createObject();
8287 rc = attachment->init(this,
8288 diff,
8289 pAtt->getControllerName(),
8290 pAtt->getPort(),
8291 pAtt->getDevice(),
8292 DeviceType_HardDisk,
8293 true /* aImplicit */);
8294 if (FAILED(rc)) throw rc;
8295
8296 mMediaData->mAttachments.push_back(attachment);
8297 }
8298 }
8299 catch (HRESULT aRC) { rc = aRC; }
8300
8301 /* unlock all hard disks we locked */
8302 if (!aOnline)
8303 {
8304 ErrorInfoKeeper eik;
8305
8306 for (MediaList::const_iterator it = lockedMedia.begin();
8307 it != lockedMedia.end();
8308 ++it)
8309 {
8310 HRESULT rc2 = (*it)->UnlockRead(NULL);
8311 AssertComRC(rc2);
8312 }
8313 }
8314
8315 if (FAILED(rc))
8316 {
8317 MultiResultRef mrc(rc);
8318
8319 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8320 }
8321
8322 return rc;
8323}
8324
8325/**
8326 * Deletes implicit differencing hard disks created either by
8327 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8328 *
8329 * Note that to delete hard disks created by #AttachMedium() this method is
8330 * called from #fixupMedia() when the changes are rolled back.
8331 *
8332 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8333 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8334 *
8335 * @note Locks this object for writing.
8336 */
8337HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8338{
8339 AutoCaller autoCaller(this);
8340 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8341
8342 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8343 LogFlowThisFuncEnter();
8344
8345 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8346
8347 HRESULT rc = S_OK;
8348
8349 MediaData::AttachmentList implicitAtts;
8350
8351 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8352
8353 /* enumerate new attachments */
8354 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8355 it != mMediaData->mAttachments.end();
8356 ++it)
8357 {
8358 ComObjPtr<Medium> hd = (*it)->getMedium();
8359 if (hd.isNull())
8360 continue;
8361
8362 if ((*it)->isImplicit())
8363 {
8364 /* deassociate and mark for deletion */
8365 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8366 rc = hd->detachFrom(mData->mUuid);
8367 AssertComRC(rc);
8368 implicitAtts.push_back(*it);
8369 continue;
8370 }
8371
8372 /* was this hard disk attached before? */
8373 if (!findAttachment(oldAtts, hd))
8374 {
8375 /* no: de-associate */
8376 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8377 rc = hd->detachFrom(mData->mUuid);
8378 AssertComRC(rc);
8379 continue;
8380 }
8381 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8382 }
8383
8384 /* rollback hard disk changes */
8385 mMediaData.rollback();
8386
8387 MultiResult mrc(S_OK);
8388
8389 /* delete unused implicit diffs */
8390 if (implicitAtts.size() != 0)
8391 {
8392 /* will leave the lock before the potentially lengthy
8393 * operation, so protect with the special state (unless already
8394 * protected) */
8395 MachineState_T oldState = mData->mMachineState;
8396 if ( oldState != MachineState_Saving
8397 && oldState != MachineState_LiveSnapshotting
8398 && oldState != MachineState_RestoringSnapshot
8399 && oldState != MachineState_DeletingSnapshot
8400 )
8401 setMachineState(MachineState_SettingUp);
8402
8403 alock.leave();
8404
8405 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8406 it != implicitAtts.end();
8407 ++it)
8408 {
8409 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8410 ComObjPtr<Medium> hd = (*it)->getMedium();
8411
8412 rc = hd->deleteStorageAndWait(NULL /*aProgress*/, pfNeedsSaveSettings);
8413#if 1 /* HACK ALERT: Just make it kind of work */ /** @todo Fix this hack properly. The LockWrite / UnlockWrite / LockRead changes aren't undone! */
8414 if (rc == VBOX_E_INVALID_OBJECT_STATE)
8415 {
8416 LogFlowFunc(("Applying unlock hack on '%s'! FIXME!\n", (*it)->getLogName()));
8417 hd->UnlockWrite(NULL);
8418 rc = hd->deleteStorageAndWait(NULL /*aProgress*/, pfNeedsSaveSettings);
8419 }
8420#endif
8421 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8422 mrc = rc;
8423 }
8424
8425 alock.enter();
8426
8427 if (mData->mMachineState == MachineState_SettingUp)
8428 {
8429 setMachineState(oldState);
8430 }
8431 }
8432
8433 return mrc;
8434}
8435
8436/**
8437 * Looks through the given list of media attachments for one with the given parameters
8438 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8439 * can be searched as well if needed.
8440 *
8441 * @param list
8442 * @param aControllerName
8443 * @param aControllerPort
8444 * @param aDevice
8445 * @return
8446 */
8447MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8448 IN_BSTR aControllerName,
8449 LONG aControllerPort,
8450 LONG aDevice)
8451{
8452 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8453 it != ll.end();
8454 ++it)
8455 {
8456 MediumAttachment *pAttach = *it;
8457 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8458 return pAttach;
8459 }
8460
8461 return NULL;
8462}
8463
8464/**
8465 * Looks through the given list of media attachments for one with the given parameters
8466 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8467 * can be searched as well if needed.
8468 *
8469 * @param list
8470 * @param aControllerName
8471 * @param aControllerPort
8472 * @param aDevice
8473 * @return
8474 */
8475MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8476 ComObjPtr<Medium> pMedium)
8477{
8478 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8479 it != ll.end();
8480 ++it)
8481 {
8482 MediumAttachment *pAttach = *it;
8483 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8484 if (pMediumThis.equalsTo(pMedium))
8485 return pAttach;
8486 }
8487
8488 return NULL;
8489}
8490
8491/**
8492 * Looks through the given list of media attachments for one with the given parameters
8493 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8494 * can be searched as well if needed.
8495 *
8496 * @param list
8497 * @param aControllerName
8498 * @param aControllerPort
8499 * @param aDevice
8500 * @return
8501 */
8502MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8503 Guid &id)
8504{
8505 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8506 it != ll.end();
8507 ++it)
8508 {
8509 MediumAttachment *pAttach = *it;
8510 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8511 if (pMediumThis->getId() == id)
8512 return pAttach;
8513 }
8514
8515 return NULL;
8516}
8517
8518/**
8519 * Perform deferred hard disk detachments.
8520 *
8521 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8522 * backed up).
8523 *
8524 * If @a aOnline is @c true then this method will also unlock the old hard disks
8525 * for which the new implicit diffs were created and will lock these new diffs for
8526 * writing.
8527 *
8528 * @param aOnline Whether the VM was online prior to this operation.
8529 *
8530 * @note Locks this object for writing!
8531 */
8532void Machine::commitMedia(bool aOnline /*= false*/)
8533{
8534 AutoCaller autoCaller(this);
8535 AssertComRCReturnVoid(autoCaller.rc());
8536
8537 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8538
8539 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
8540
8541 HRESULT rc = S_OK;
8542
8543 /* no attach/detach operations -- nothing to do */
8544 if (!mMediaData.isBackedUp())
8545 return;
8546
8547 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8548
8549 /* enumerate new attachments */
8550 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8551 it != mMediaData->mAttachments.end();
8552 ++it)
8553 {
8554 MediumAttachment *pAttach = *it;
8555
8556 pAttach->commit();
8557
8558 Medium* pMedium = pAttach->getMedium();
8559 bool fImplicit = pAttach->isImplicit();
8560
8561 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
8562 (pMedium) ? pMedium->getName().raw() : "NULL",
8563 fImplicit));
8564
8565 /** @todo convert all this Machine-based voodoo to MediumAttachment
8566 * based commit logic. */
8567 if (fImplicit)
8568 {
8569 /* convert implicit attachment to normal */
8570 pAttach->setImplicit(false);
8571
8572 if ( aOnline
8573 && pMedium
8574 && pAttach->getType() == DeviceType_HardDisk
8575 )
8576 {
8577 rc = pMedium->LockWrite(NULL);
8578 AssertComRC(rc);
8579
8580 mData->mSession.mLockedMedia.push_back(
8581 Data::Session::LockedMedia::value_type(
8582 ComPtr<IMedium>(pMedium), true));
8583
8584 /* also, relock the old hard disk which is a base for the
8585 * new diff for reading if the VM is online */
8586
8587 ComObjPtr<Medium> parent = pMedium->getParent();
8588 /* make the relock atomic */
8589 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8590 rc = parent->UnlockWrite(NULL);
8591 AssertComRC(rc);
8592 rc = parent->LockRead(NULL);
8593 AssertComRC(rc);
8594
8595 /* XXX actually we should replace the old entry in that
8596 * vector (write lock => read lock) but this would take
8597 * some effort. So lets just ignore the error code in
8598 * SessionMachine::unlockMedia(). */
8599 mData->mSession.mLockedMedia.push_back(
8600 Data::Session::LockedMedia::value_type (
8601 ComPtr<IMedium>(parent), false));
8602 }
8603
8604 continue;
8605 }
8606
8607 if (pMedium)
8608 {
8609 /* was this medium attached before? */
8610 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
8611 oldIt != oldAtts.end();
8612 ++oldIt)
8613 {
8614 MediumAttachment *pOldAttach = *oldIt;
8615 if (pOldAttach->getMedium().equalsTo(pMedium))
8616 {
8617 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().raw()));
8618
8619 /* yes: remove from old to avoid de-association */
8620 oldAtts.erase(oldIt);
8621 break;
8622 }
8623 }
8624 }
8625 }
8626
8627 /* enumerate remaining old attachments and de-associate from the
8628 * current machine state */
8629 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
8630 it != oldAtts.end();
8631 ++it)
8632 {
8633 MediumAttachment *pAttach = *it;
8634 Medium* pMedium = pAttach->getMedium();
8635
8636 /* Detach only hard disks, since DVD/floppy media is detached
8637 * instantly in MountMedium. */
8638 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
8639 {
8640 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().raw()));
8641
8642 /* now de-associate from the current machine state */
8643 rc = pMedium->detachFrom(mData->mUuid);
8644 AssertComRC(rc);
8645
8646 if ( aOnline
8647 && pAttach->getType() == DeviceType_HardDisk)
8648 {
8649 /* unlock since not used anymore */
8650 MediumState_T state;
8651 rc = pMedium->UnlockWrite(&state);
8652 /* the disk may be alredy relocked for reading above */
8653 Assert(SUCCEEDED(rc) || state == MediumState_LockedRead);
8654 }
8655 }
8656 }
8657
8658 /* commit the hard disk changes */
8659 mMediaData.commit();
8660
8661 if (getClassID() == clsidSessionMachine)
8662 {
8663 /* attach new data to the primary machine and reshare it */
8664 mPeer->mMediaData.attach(mMediaData);
8665 }
8666
8667 return;
8668}
8669
8670/**
8671 * Perform deferred deletion of implicitly created diffs.
8672 *
8673 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8674 * backed up).
8675 *
8676 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8677 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8678 *
8679 * @note Locks this object for writing!
8680 */
8681void Machine::rollbackMedia()
8682{
8683 AutoCaller autoCaller(this);
8684 AssertComRCReturnVoid (autoCaller.rc());
8685
8686 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8687
8688 LogFlowThisFunc(("Entering\n"));
8689
8690 HRESULT rc = S_OK;
8691
8692 /* no attach/detach operations -- nothing to do */
8693 if (!mMediaData.isBackedUp())
8694 return;
8695
8696 /* enumerate new attachments */
8697 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8698 it != mMediaData->mAttachments.end();
8699 ++it)
8700 {
8701 MediumAttachment *pAttach = *it;
8702 /* Fix up the backrefs for DVD/floppy media. */
8703 if (pAttach->getType() != DeviceType_HardDisk)
8704 {
8705 Medium* pMedium = pAttach->getMedium();
8706 if (pMedium)
8707 {
8708 rc = pMedium->detachFrom(mData->mUuid);
8709 AssertComRC(rc);
8710 }
8711 }
8712
8713 (*it)->rollback();
8714
8715 pAttach = *it;
8716 /* Fix up the backrefs for DVD/floppy media. */
8717 if (pAttach->getType() != DeviceType_HardDisk)
8718 {
8719 Medium* pMedium = pAttach->getMedium();
8720 if (pMedium)
8721 {
8722 rc = pMedium->attachTo(mData->mUuid);
8723 AssertComRC(rc);
8724 }
8725 }
8726 }
8727
8728 /** @todo convert all this Machine-based voodoo to MediumAttachment
8729 * based rollback logic. */
8730 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
8731 // which gets called if Machine::registeredInit() fails...
8732 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
8733
8734 return;
8735}
8736
8737/**
8738 * Returns true if the settings file is located in the directory named exactly
8739 * as the machine. This will be true if the machine settings structure was
8740 * created by default in #openConfigLoader().
8741 *
8742 * @param aSettingsDir if not NULL, the full machine settings file directory
8743 * name will be assigned there.
8744 *
8745 * @note Doesn't lock anything.
8746 * @note Not thread safe (must be called from this object's lock).
8747 */
8748bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */)
8749{
8750 Utf8Str settingsDir = mData->m_strConfigFileFull;
8751 settingsDir.stripFilename();
8752 char *dirName = RTPathFilename(settingsDir.c_str());
8753
8754 AssertReturn(dirName, false);
8755
8756 /* if we don't rename anything on name change, return false shorlty */
8757 if (!mUserData->mNameSync)
8758 return false;
8759
8760 if (aSettingsDir)
8761 *aSettingsDir = settingsDir;
8762
8763 return Bstr(dirName) == mUserData->mName;
8764}
8765
8766/**
8767 * Discards all changes to machine settings.
8768 *
8769 * @param aNotify Whether to notify the direct session about changes or not.
8770 *
8771 * @note Locks objects for writing!
8772 */
8773void Machine::rollback(bool aNotify)
8774{
8775 AutoCaller autoCaller(this);
8776 AssertComRCReturn(autoCaller.rc(), (void)0);
8777
8778 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8779
8780 if (!mStorageControllers.isNull())
8781 {
8782 if (mStorageControllers.isBackedUp())
8783 {
8784 /* unitialize all new devices (absent in the backed up list). */
8785 StorageControllerList::const_iterator it = mStorageControllers->begin();
8786 StorageControllerList *backedList = mStorageControllers.backedUpData();
8787 while (it != mStorageControllers->end())
8788 {
8789 if ( std::find(backedList->begin(), backedList->end(), *it)
8790 == backedList->end()
8791 )
8792 {
8793 (*it)->uninit();
8794 }
8795 ++it;
8796 }
8797
8798 /* restore the list */
8799 mStorageControllers.rollback();
8800 }
8801
8802 /* rollback any changes to devices after restoring the list */
8803 if (mData->flModifications & IsModified_Storage)
8804 {
8805 StorageControllerList::const_iterator it = mStorageControllers->begin();
8806 while (it != mStorageControllers->end())
8807 {
8808 (*it)->rollback();
8809 ++it;
8810 }
8811 }
8812 }
8813
8814 mUserData.rollback();
8815
8816 mHWData.rollback();
8817
8818 if (mData->flModifications & IsModified_Storage)
8819 rollbackMedia();
8820
8821 if (mBIOSSettings)
8822 mBIOSSettings->rollback();
8823
8824#ifdef VBOX_WITH_VRDP
8825 if (mVRDPServer && (mData->flModifications & IsModified_VRDPServer))
8826 mVRDPServer->rollback();
8827#endif
8828
8829 if (mAudioAdapter)
8830 mAudioAdapter->rollback();
8831
8832 if (mUSBController && (mData->flModifications & IsModified_USB))
8833 mUSBController->rollback();
8834
8835 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
8836 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
8837 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
8838
8839 if (mData->flModifications & IsModified_NetworkAdapters)
8840 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
8841 if ( mNetworkAdapters[slot]
8842 && mNetworkAdapters[slot]->isModified())
8843 {
8844 mNetworkAdapters[slot]->rollback();
8845 networkAdapters[slot] = mNetworkAdapters[slot];
8846 }
8847
8848 if (mData->flModifications & IsModified_SerialPorts)
8849 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
8850 if ( mSerialPorts[slot]
8851 && mSerialPorts[slot]->isModified())
8852 {
8853 mSerialPorts[slot]->rollback();
8854 serialPorts[slot] = mSerialPorts[slot];
8855 }
8856
8857 if (mData->flModifications & IsModified_ParallelPorts)
8858 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
8859 if ( mParallelPorts[slot]
8860 && mParallelPorts[slot]->isModified())
8861 {
8862 mParallelPorts[slot]->rollback();
8863 parallelPorts[slot] = mParallelPorts[slot];
8864 }
8865
8866 if (aNotify)
8867 {
8868 /* inform the direct session about changes */
8869
8870 ComObjPtr<Machine> that = this;
8871 uint32_t flModifications = mData->flModifications;
8872 alock.leave();
8873
8874 if (flModifications & IsModified_SharedFolders)
8875 that->onSharedFolderChange();
8876
8877 if (flModifications & IsModified_VRDPServer)
8878 that->onVRDPServerChange();
8879 if (flModifications & IsModified_USB)
8880 that->onUSBControllerChange();
8881
8882 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
8883 if (networkAdapters[slot])
8884 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
8885 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
8886 if (serialPorts[slot])
8887 that->onSerialPortChange(serialPorts[slot]);
8888 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
8889 if (parallelPorts[slot])
8890 that->onParallelPortChange(parallelPorts[slot]);
8891
8892 if (flModifications & IsModified_Storage)
8893 that->onStorageControllerChange();
8894 }
8895}
8896
8897/**
8898 * Commits all the changes to machine settings.
8899 *
8900 * Note that this operation is supposed to never fail.
8901 *
8902 * @note Locks this object and children for writing.
8903 */
8904void Machine::commit()
8905{
8906 AutoCaller autoCaller(this);
8907 AssertComRCReturnVoid(autoCaller.rc());
8908
8909 AutoCaller peerCaller(mPeer);
8910 AssertComRCReturnVoid(peerCaller.rc());
8911
8912 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
8913
8914 /*
8915 * use safe commit to ensure Snapshot machines (that share mUserData)
8916 * will still refer to a valid memory location
8917 */
8918 mUserData.commitCopy();
8919
8920 mHWData.commit();
8921
8922 if (mMediaData.isBackedUp())
8923 commitMedia();
8924
8925 mBIOSSettings->commit();
8926#ifdef VBOX_WITH_VRDP
8927 mVRDPServer->commit();
8928#endif
8929 mAudioAdapter->commit();
8930 mUSBController->commit();
8931
8932 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
8933 mNetworkAdapters[slot]->commit();
8934 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
8935 mSerialPorts[slot]->commit();
8936 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
8937 mParallelPorts[slot]->commit();
8938
8939 bool commitStorageControllers = false;
8940
8941 if (mStorageControllers.isBackedUp())
8942 {
8943 mStorageControllers.commit();
8944
8945 if (mPeer)
8946 {
8947 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
8948
8949 /* Commit all changes to new controllers (this will reshare data with
8950 * peers for thos who have peers) */
8951 StorageControllerList *newList = new StorageControllerList();
8952 StorageControllerList::const_iterator it = mStorageControllers->begin();
8953 while (it != mStorageControllers->end())
8954 {
8955 (*it)->commit();
8956
8957 /* look if this controller has a peer device */
8958 ComObjPtr<StorageController> peer = (*it)->getPeer();
8959 if (!peer)
8960 {
8961 /* no peer means the device is a newly created one;
8962 * create a peer owning data this device share it with */
8963 peer.createObject();
8964 peer->init(mPeer, *it, true /* aReshare */);
8965 }
8966 else
8967 {
8968 /* remove peer from the old list */
8969 mPeer->mStorageControllers->remove(peer);
8970 }
8971 /* and add it to the new list */
8972 newList->push_back(peer);
8973
8974 ++it;
8975 }
8976
8977 /* uninit old peer's controllers that are left */
8978 it = mPeer->mStorageControllers->begin();
8979 while (it != mPeer->mStorageControllers->end())
8980 {
8981 (*it)->uninit();
8982 ++it;
8983 }
8984
8985 /* attach new list of controllers to our peer */
8986 mPeer->mStorageControllers.attach(newList);
8987 }
8988 else
8989 {
8990 /* we have no peer (our parent is the newly created machine);
8991 * just commit changes to devices */
8992 commitStorageControllers = true;
8993 }
8994 }
8995 else
8996 {
8997 /* the list of controllers itself is not changed,
8998 * just commit changes to controllers themselves */
8999 commitStorageControllers = true;
9000 }
9001
9002 if (commitStorageControllers)
9003 {
9004 StorageControllerList::const_iterator it = mStorageControllers->begin();
9005 while (it != mStorageControllers->end())
9006 {
9007 (*it)->commit();
9008 ++it;
9009 }
9010 }
9011
9012 if (getClassID() == clsidSessionMachine)
9013 {
9014 /* attach new data to the primary machine and reshare it */
9015 mPeer->mUserData.attach(mUserData);
9016 mPeer->mHWData.attach(mHWData);
9017 /* mMediaData is reshared by fixupMedia */
9018 // mPeer->mMediaData.attach(mMediaData);
9019 Assert(mPeer->mMediaData.data() == mMediaData.data());
9020 }
9021}
9022
9023/**
9024 * Copies all the hardware data from the given machine.
9025 *
9026 * Currently, only called when the VM is being restored from a snapshot. In
9027 * particular, this implies that the VM is not running during this method's
9028 * call.
9029 *
9030 * @note This method must be called from under this object's lock.
9031 *
9032 * @note This method doesn't call #commit(), so all data remains backed up and
9033 * unsaved.
9034 */
9035void Machine::copyFrom(Machine *aThat)
9036{
9037 AssertReturnVoid(getClassID() == clsidMachine || getClassID() == clsidSessionMachine);
9038 AssertReturnVoid(aThat->getClassID() == clsidSnapshotMachine);
9039
9040 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9041
9042 mHWData.assignCopy(aThat->mHWData);
9043
9044 // create copies of all shared folders (mHWData after attiching a copy
9045 // contains just references to original objects)
9046 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9047 it != mHWData->mSharedFolders.end();
9048 ++it)
9049 {
9050 ComObjPtr<SharedFolder> folder;
9051 folder.createObject();
9052 HRESULT rc = folder->initCopy(getMachine(), *it);
9053 AssertComRC(rc);
9054 *it = folder;
9055 }
9056
9057 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9058#ifdef VBOX_WITH_VRDP
9059 mVRDPServer->copyFrom(aThat->mVRDPServer);
9060#endif
9061 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9062 mUSBController->copyFrom(aThat->mUSBController);
9063
9064 /* create private copies of all controllers */
9065 mStorageControllers.backup();
9066 mStorageControllers->clear();
9067 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9068 it != aThat->mStorageControllers->end();
9069 ++it)
9070 {
9071 ComObjPtr<StorageController> ctrl;
9072 ctrl.createObject();
9073 ctrl->initCopy(this, *it);
9074 mStorageControllers->push_back(ctrl);
9075 }
9076
9077 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9078 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9079 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9080 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9081 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9082 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9083}
9084
9085#ifdef VBOX_WITH_RESOURCE_USAGE_API
9086void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9087{
9088 pm::CollectorHAL *hal = aCollector->getHAL();
9089 /* Create sub metrics */
9090 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9091 "Percentage of processor time spent in user mode by the VM process.");
9092 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9093 "Percentage of processor time spent in kernel mode by the VM process.");
9094 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9095 "Size of resident portion of VM process in memory.");
9096 /* Create and register base metrics */
9097 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9098 cpuLoadUser, cpuLoadKernel);
9099 aCollector->registerBaseMetric(cpuLoad);
9100 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9101 ramUsageUsed);
9102 aCollector->registerBaseMetric(ramUsage);
9103
9104 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9105 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9106 new pm::AggregateAvg()));
9107 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9108 new pm::AggregateMin()));
9109 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9110 new pm::AggregateMax()));
9111 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9112 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9113 new pm::AggregateAvg()));
9114 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9115 new pm::AggregateMin()));
9116 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9117 new pm::AggregateMax()));
9118
9119 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9120 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9121 new pm::AggregateAvg()));
9122 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9123 new pm::AggregateMin()));
9124 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9125 new pm::AggregateMax()));
9126
9127
9128 /* Guest metrics */
9129 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9130
9131 /* Create sub metrics */
9132 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/Cpu/Load/User",
9133 "Percentage of processor time spent in user mode as seen by the guest.");
9134 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/Cpu/Load/Kernel",
9135 "Percentage of processor time spent in kernel mode as seen by the guest.");
9136 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/Cpu/Load/Idle",
9137 "Percentage of processor time spent idling as seen by the guest.");
9138
9139 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9140 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9141 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9142 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9143 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9144
9145 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9146
9147 /* Create and register base metrics */
9148 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9149 aCollector->registerBaseMetric(guestCpuLoad);
9150
9151 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon,
9152 guestMemCache, guestPagedTotal);
9153 aCollector->registerBaseMetric(guestCpuMem);
9154
9155 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9156 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9157 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9158 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9159
9160 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9161 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9162 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9163 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9164
9165 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9166 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9167 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9168 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9169
9170 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9171 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9172 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9173 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9174
9175 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9176 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9177 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9178 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9179
9180 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9181 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9182 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9183 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9184
9185 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9186 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9187 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9188 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9189
9190 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9191 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9192 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9193 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9194};
9195
9196void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9197{
9198 aCollector->unregisterMetricsFor(aMachine);
9199 aCollector->unregisterBaseMetricsFor(aMachine);
9200
9201 if (mGuestHAL)
9202 delete mGuestHAL;
9203};
9204#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9205
9206
9207////////////////////////////////////////////////////////////////////////////////
9208
9209DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9210
9211HRESULT SessionMachine::FinalConstruct()
9212{
9213 LogFlowThisFunc(("\n"));
9214
9215#if defined(RT_OS_WINDOWS)
9216 mIPCSem = NULL;
9217#elif defined(RT_OS_OS2)
9218 mIPCSem = NULLHANDLE;
9219#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9220 mIPCSem = -1;
9221#else
9222# error "Port me!"
9223#endif
9224
9225 return S_OK;
9226}
9227
9228void SessionMachine::FinalRelease()
9229{
9230 LogFlowThisFunc(("\n"));
9231
9232 uninit(Uninit::Unexpected);
9233}
9234
9235/**
9236 * @note Must be called only by Machine::openSession() from its own write lock.
9237 */
9238HRESULT SessionMachine::init(Machine *aMachine)
9239{
9240 LogFlowThisFuncEnter();
9241 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
9242
9243 AssertReturn(aMachine, E_INVALIDARG);
9244
9245 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9246
9247 /* Enclose the state transition NotReady->InInit->Ready */
9248 AutoInitSpan autoInitSpan(this);
9249 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9250
9251 /* create the interprocess semaphore */
9252#if defined(RT_OS_WINDOWS)
9253 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9254 for (size_t i = 0; i < mIPCSemName.length(); i++)
9255 if (mIPCSemName[i] == '\\')
9256 mIPCSemName[i] = '/';
9257 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName);
9258 ComAssertMsgRet(mIPCSem,
9259 ("Cannot create IPC mutex '%ls', err=%d",
9260 mIPCSemName.raw(), ::GetLastError()),
9261 E_FAIL);
9262#elif defined(RT_OS_OS2)
9263 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9264 aMachine->mData->mUuid.raw());
9265 mIPCSemName = ipcSem;
9266 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.raw(), &mIPCSem, 0, FALSE);
9267 ComAssertMsgRet(arc == NO_ERROR,
9268 ("Cannot create IPC mutex '%s', arc=%ld",
9269 ipcSem.raw(), arc),
9270 E_FAIL);
9271#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9272# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9273# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9274 /** @todo Check that this still works correctly. */
9275 AssertCompileSize(key_t, 8);
9276# else
9277 AssertCompileSize(key_t, 4);
9278# endif
9279 key_t key;
9280 mIPCSem = -1;
9281 mIPCKey = "0";
9282 for (uint32_t i = 0; i < 1 << 24; i++)
9283 {
9284 key = ((uint32_t)'V' << 24) | i;
9285 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9286 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9287 {
9288 mIPCSem = sem;
9289 if (sem >= 0)
9290 mIPCKey = BstrFmt("%u", key);
9291 break;
9292 }
9293 }
9294# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9295 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9296 char *pszSemName = NULL;
9297 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9298 key_t key = ::ftok(pszSemName, 'V');
9299 RTStrFree(pszSemName);
9300
9301 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9302# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9303
9304 int errnoSave = errno;
9305 if (mIPCSem < 0 && errnoSave == ENOSYS)
9306 {
9307 setError(E_FAIL,
9308 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9309 "support for SysV IPC. Check the host kernel configuration for "
9310 "CONFIG_SYSVIPC=y"));
9311 return E_FAIL;
9312 }
9313 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9314 * the IPC semaphores */
9315 if (mIPCSem < 0 && errnoSave == ENOSPC)
9316 {
9317#ifdef RT_OS_LINUX
9318 setError(E_FAIL,
9319 tr("Cannot create IPC semaphore because the system limit for the "
9320 "maximum number of semaphore sets (SEMMNI), or the system wide "
9321 "maximum number of sempahores (SEMMNS) would be exceeded. The "
9322 "current set of SysV IPC semaphores can be determined from "
9323 "the file /proc/sysvipc/sem"));
9324#else
9325 setError(E_FAIL,
9326 tr("Cannot create IPC semaphore because the system-imposed limit "
9327 "on the maximum number of allowed semaphores or semaphore "
9328 "identifiers system-wide would be exceeded"));
9329#endif
9330 return E_FAIL;
9331 }
9332 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9333 E_FAIL);
9334 /* set the initial value to 1 */
9335 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9336 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9337 E_FAIL);
9338#else
9339# error "Port me!"
9340#endif
9341
9342 /* memorize the peer Machine */
9343 unconst(mPeer) = aMachine;
9344 /* share the parent pointer */
9345 unconst(mParent) = aMachine->mParent;
9346
9347 /* take the pointers to data to share */
9348 mData.share(aMachine->mData);
9349 mSSData.share(aMachine->mSSData);
9350
9351 mUserData.share(aMachine->mUserData);
9352 mHWData.share(aMachine->mHWData);
9353 mMediaData.share(aMachine->mMediaData);
9354
9355 mStorageControllers.allocate();
9356 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9357 it != aMachine->mStorageControllers->end();
9358 ++it)
9359 {
9360 ComObjPtr<StorageController> ctl;
9361 ctl.createObject();
9362 ctl->init(this, *it);
9363 mStorageControllers->push_back(ctl);
9364 }
9365
9366 unconst(mBIOSSettings).createObject();
9367 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9368#ifdef VBOX_WITH_VRDP
9369 /* create another VRDPServer object that will be mutable */
9370 unconst(mVRDPServer).createObject();
9371 mVRDPServer->init(this, aMachine->mVRDPServer);
9372#endif
9373 /* create another audio adapter object that will be mutable */
9374 unconst(mAudioAdapter).createObject();
9375 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9376 /* create a list of serial ports that will be mutable */
9377 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9378 {
9379 unconst(mSerialPorts[slot]).createObject();
9380 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9381 }
9382 /* create a list of parallel ports that will be mutable */
9383 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9384 {
9385 unconst(mParallelPorts[slot]).createObject();
9386 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9387 }
9388 /* create another USB controller object that will be mutable */
9389 unconst(mUSBController).createObject();
9390 mUSBController->init(this, aMachine->mUSBController);
9391
9392 /* create a list of network adapters that will be mutable */
9393 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9394 {
9395 unconst(mNetworkAdapters[slot]).createObject();
9396 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9397 }
9398
9399 /* default is to delete saved state on Saved -> PoweredOff transition */
9400 mRemoveSavedState = true;
9401
9402 /* Confirm a successful initialization when it's the case */
9403 autoInitSpan.setSucceeded();
9404
9405 LogFlowThisFuncLeave();
9406 return S_OK;
9407}
9408
9409/**
9410 * Uninitializes this session object. If the reason is other than
9411 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9412 *
9413 * @param aReason uninitialization reason
9414 *
9415 * @note Locks mParent + this object for writing.
9416 */
9417void SessionMachine::uninit(Uninit::Reason aReason)
9418{
9419 LogFlowThisFuncEnter();
9420 LogFlowThisFunc(("reason=%d\n", aReason));
9421
9422 /*
9423 * Strongly reference ourselves to prevent this object deletion after
9424 * mData->mSession.mMachine.setNull() below (which can release the last
9425 * reference and call the destructor). Important: this must be done before
9426 * accessing any members (and before AutoUninitSpan that does it as well).
9427 * This self reference will be released as the very last step on return.
9428 */
9429 ComObjPtr<SessionMachine> selfRef = this;
9430
9431 /* Enclose the state transition Ready->InUninit->NotReady */
9432 AutoUninitSpan autoUninitSpan(this);
9433 if (autoUninitSpan.uninitDone())
9434 {
9435 LogFlowThisFunc(("Already uninitialized\n"));
9436 LogFlowThisFuncLeave();
9437 return;
9438 }
9439
9440 if (autoUninitSpan.initFailed())
9441 {
9442 /* We've been called by init() because it's failed. It's not really
9443 * necessary (nor it's safe) to perform the regular uninit sequense
9444 * below, the following is enough.
9445 */
9446 LogFlowThisFunc(("Initialization failed.\n"));
9447#if defined(RT_OS_WINDOWS)
9448 if (mIPCSem)
9449 ::CloseHandle(mIPCSem);
9450 mIPCSem = NULL;
9451#elif defined(RT_OS_OS2)
9452 if (mIPCSem != NULLHANDLE)
9453 ::DosCloseMutexSem(mIPCSem);
9454 mIPCSem = NULLHANDLE;
9455#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9456 if (mIPCSem >= 0)
9457 ::semctl(mIPCSem, 0, IPC_RMID);
9458 mIPCSem = -1;
9459# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9460 mIPCKey = "0";
9461# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9462#else
9463# error "Port me!"
9464#endif
9465 uninitDataAndChildObjects();
9466 mData.free();
9467 unconst(mParent) = NULL;
9468 unconst(mPeer) = NULL;
9469 LogFlowThisFuncLeave();
9470 return;
9471 }
9472
9473 MachineState_T lastState;
9474 {
9475 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9476 lastState = mData->mMachineState;
9477 }
9478 NOREF(lastState);
9479
9480#ifdef VBOX_WITH_USB
9481 // release all captured USB devices, but do this before requesting the locks below
9482 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9483 {
9484 /* Console::captureUSBDevices() is called in the VM process only after
9485 * setting the machine state to Starting or Restoring.
9486 * Console::detachAllUSBDevices() will be called upon successful
9487 * termination. So, we need to release USB devices only if there was
9488 * an abnormal termination of a running VM.
9489 *
9490 * This is identical to SessionMachine::DetachAllUSBDevices except
9491 * for the aAbnormal argument. */
9492 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9493 AssertComRC(rc);
9494 NOREF(rc);
9495
9496 USBProxyService *service = mParent->host()->usbProxyService();
9497 if (service)
9498 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9499 }
9500#endif /* VBOX_WITH_USB */
9501
9502 // we need to lock this object in uninit() because the lock is shared
9503 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
9504 // and others need mParent lock, and USB needs host lock.
9505 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
9506
9507#ifdef VBOX_WITH_RESOURCE_USAGE_API
9508 unregisterMetrics(mParent->performanceCollector(), mPeer);
9509#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9510
9511 if (aReason == Uninit::Abnormal)
9512 {
9513 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
9514 Global::IsOnlineOrTransient(lastState)));
9515
9516 /* reset the state to Aborted */
9517 if (mData->mMachineState != MachineState_Aborted)
9518 setMachineState(MachineState_Aborted);
9519 }
9520
9521 // any machine settings modified?
9522 if (mData->flModifications)
9523 {
9524 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
9525 rollback(false /* aNotify */);
9526 }
9527
9528 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
9529 if (!mSnapshotData.mStateFilePath.isEmpty())
9530 {
9531 LogWarningThisFunc(("canceling failed save state request!\n"));
9532 endSavingState(FALSE /* aSuccess */);
9533 }
9534 else if (!mSnapshotData.mSnapshot.isNull())
9535 {
9536 LogWarningThisFunc(("canceling untaken snapshot!\n"));
9537
9538 /* delete all differencing hard disks created (this will also attach
9539 * their parents back by rolling back mMediaData) */
9540 rollbackMedia();
9541 /* delete the saved state file (it might have been already created) */
9542 if (mSnapshotData.mSnapshot->stateFilePath().length())
9543 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
9544
9545 mSnapshotData.mSnapshot->uninit();
9546 }
9547
9548 if (!mData->mSession.mType.isEmpty())
9549 {
9550 /* mType is not null when this machine's process has been started by
9551 * VirtualBox::OpenRemoteSession(), therefore it is our child. We
9552 * need to queue the PID to reap the process (and avoid zombies on
9553 * Linux). */
9554 Assert(mData->mSession.mPid != NIL_RTPROCESS);
9555 mParent->addProcessToReap(mData->mSession.mPid);
9556 }
9557
9558 mData->mSession.mPid = NIL_RTPROCESS;
9559
9560 if (aReason == Uninit::Unexpected)
9561 {
9562 /* Uninitialization didn't come from #checkForDeath(), so tell the
9563 * client watcher thread to update the set of machines that have open
9564 * sessions. */
9565 mParent->updateClientWatcher();
9566 }
9567
9568 /* uninitialize all remote controls */
9569 if (mData->mSession.mRemoteControls.size())
9570 {
9571 LogFlowThisFunc(("Closing remote sessions (%d):\n",
9572 mData->mSession.mRemoteControls.size()));
9573
9574 Data::Session::RemoteControlList::iterator it =
9575 mData->mSession.mRemoteControls.begin();
9576 while (it != mData->mSession.mRemoteControls.end())
9577 {
9578 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
9579 HRESULT rc = (*it)->Uninitialize();
9580 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
9581 if (FAILED(rc))
9582 LogWarningThisFunc(("Forgot to close the remote session?\n"));
9583 ++it;
9584 }
9585 mData->mSession.mRemoteControls.clear();
9586 }
9587
9588 /*
9589 * An expected uninitialization can come only from #checkForDeath().
9590 * Otherwise it means that something's got really wrong (for examlple,
9591 * the Session implementation has released the VirtualBox reference
9592 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
9593 * etc). However, it's also possible, that the client releases the IPC
9594 * semaphore correctly (i.e. before it releases the VirtualBox reference),
9595 * but the VirtualBox release event comes first to the server process.
9596 * This case is practically possible, so we should not assert on an
9597 * unexpected uninit, just log a warning.
9598 */
9599
9600 if ((aReason == Uninit::Unexpected))
9601 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
9602
9603 if (aReason != Uninit::Normal)
9604 {
9605 mData->mSession.mDirectControl.setNull();
9606 }
9607 else
9608 {
9609 /* this must be null here (see #OnSessionEnd()) */
9610 Assert(mData->mSession.mDirectControl.isNull());
9611 Assert(mData->mSession.mState == SessionState_Closing);
9612 Assert(!mData->mSession.mProgress.isNull());
9613 }
9614 if (mData->mSession.mProgress)
9615 {
9616 if (aReason == Uninit::Normal)
9617 mData->mSession.mProgress->notifyComplete(S_OK);
9618 else
9619 mData->mSession.mProgress->notifyComplete(E_FAIL,
9620 COM_IIDOF(ISession),
9621 getComponentName(),
9622 tr("The VM session was aborted"));
9623 mData->mSession.mProgress.setNull();
9624 }
9625
9626 /* remove the association between the peer machine and this session machine */
9627 Assert(mData->mSession.mMachine == this ||
9628 aReason == Uninit::Unexpected);
9629
9630 /* reset the rest of session data */
9631 mData->mSession.mMachine.setNull();
9632 mData->mSession.mState = SessionState_Closed;
9633 mData->mSession.mType.setNull();
9634
9635 /* close the interprocess semaphore before leaving the exclusive lock */
9636#if defined(RT_OS_WINDOWS)
9637 if (mIPCSem)
9638 ::CloseHandle(mIPCSem);
9639 mIPCSem = NULL;
9640#elif defined(RT_OS_OS2)
9641 if (mIPCSem != NULLHANDLE)
9642 ::DosCloseMutexSem(mIPCSem);
9643 mIPCSem = NULLHANDLE;
9644#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9645 if (mIPCSem >= 0)
9646 ::semctl(mIPCSem, 0, IPC_RMID);
9647 mIPCSem = -1;
9648# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9649 mIPCKey = "0";
9650# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9651#else
9652# error "Port me!"
9653#endif
9654
9655 /* fire an event */
9656 mParent->onSessionStateChange(mData->mUuid, SessionState_Closed);
9657
9658 uninitDataAndChildObjects();
9659
9660 /* free the essential data structure last */
9661 mData.free();
9662
9663 /* leave the exclusive lock before setting the below two to NULL */
9664 multilock.leave();
9665
9666 unconst(mParent) = NULL;
9667 unconst(mPeer) = NULL;
9668
9669 LogFlowThisFuncLeave();
9670}
9671
9672// util::Lockable interface
9673////////////////////////////////////////////////////////////////////////////////
9674
9675/**
9676 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
9677 * with the primary Machine instance (mPeer).
9678 */
9679RWLockHandle *SessionMachine::lockHandle() const
9680{
9681 AssertReturn(mPeer != NULL, NULL);
9682 return mPeer->lockHandle();
9683}
9684
9685// IInternalMachineControl methods
9686////////////////////////////////////////////////////////////////////////////////
9687
9688/**
9689 * @note Locks this object for writing.
9690 */
9691STDMETHODIMP SessionMachine::SetRemoveSavedState(BOOL aRemove)
9692{
9693 AutoCaller autoCaller(this);
9694 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9695
9696 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9697
9698 mRemoveSavedState = aRemove;
9699
9700 return S_OK;
9701}
9702
9703/**
9704 * @note Locks the same as #setMachineState() does.
9705 */
9706STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
9707{
9708 return setMachineState(aMachineState);
9709}
9710
9711/**
9712 * @note Locks this object for reading.
9713 */
9714STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
9715{
9716 AutoCaller autoCaller(this);
9717 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9718
9719 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9720
9721#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
9722 mIPCSemName.cloneTo(aId);
9723 return S_OK;
9724#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9725# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9726 mIPCKey.cloneTo(aId);
9727# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9728 mData->m_strConfigFileFull.cloneTo(aId);
9729# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9730 return S_OK;
9731#else
9732# error "Port me!"
9733#endif
9734}
9735
9736/**
9737 * @note Locks this object for writing.
9738 */
9739STDMETHODIMP SessionMachine::SetPowerUpInfo(IVirtualBoxErrorInfo *aError)
9740{
9741 AutoCaller autoCaller(this);
9742 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9743
9744 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9745
9746 if ( mData->mSession.mState == SessionState_Open
9747 && mData->mSession.mProgress)
9748 {
9749 /* Finalize the progress, since the remote session has completed
9750 * power on (successful or not). */
9751 if (aError)
9752 {
9753 /* Transfer error information immediately, as the
9754 * IVirtualBoxErrorInfo object is most likely transient. */
9755 HRESULT rc;
9756 LONG rRc = S_OK;
9757 rc = aError->COMGETTER(ResultCode)(&rRc);
9758 AssertComRCReturnRC(rc);
9759 Bstr rIID;
9760 rc = aError->COMGETTER(InterfaceID)(rIID.asOutParam());
9761 AssertComRCReturnRC(rc);
9762 Bstr rComponent;
9763 rc = aError->COMGETTER(Component)(rComponent.asOutParam());
9764 AssertComRCReturnRC(rc);
9765 Bstr rText;
9766 rc = aError->COMGETTER(Text)(rText.asOutParam());
9767 AssertComRCReturnRC(rc);
9768 mData->mSession.mProgress->notifyComplete(rRc, Guid(rIID), rComponent, Utf8Str(rText).raw());
9769 }
9770 else
9771 mData->mSession.mProgress->notifyComplete(S_OK);
9772 mData->mSession.mProgress.setNull();
9773
9774 return S_OK;
9775 }
9776 else
9777 return VBOX_E_INVALID_OBJECT_STATE;
9778}
9779
9780/**
9781 * Goes through the USB filters of the given machine to see if the given
9782 * device matches any filter or not.
9783 *
9784 * @note Locks the same as USBController::hasMatchingFilter() does.
9785 */
9786STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
9787 BOOL *aMatched,
9788 ULONG *aMaskedIfs)
9789{
9790 LogFlowThisFunc(("\n"));
9791
9792 CheckComArgNotNull(aUSBDevice);
9793 CheckComArgOutPointerValid(aMatched);
9794
9795 AutoCaller autoCaller(this);
9796 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9797
9798#ifdef VBOX_WITH_USB
9799 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
9800#else
9801 NOREF(aUSBDevice);
9802 NOREF(aMaskedIfs);
9803 *aMatched = FALSE;
9804#endif
9805
9806 return S_OK;
9807}
9808
9809/**
9810 * @note Locks the same as Host::captureUSBDevice() does.
9811 */
9812STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
9813{
9814 LogFlowThisFunc(("\n"));
9815
9816 AutoCaller autoCaller(this);
9817 AssertComRCReturnRC(autoCaller.rc());
9818
9819#ifdef VBOX_WITH_USB
9820 /* if captureDeviceForVM() fails, it must have set extended error info */
9821 MultiResult rc = mParent->host()->checkUSBProxyService();
9822 if (FAILED(rc)) return rc;
9823
9824 USBProxyService *service = mParent->host()->usbProxyService();
9825 AssertReturn(service, E_FAIL);
9826 return service->captureDeviceForVM(this, Guid(aId));
9827#else
9828 NOREF(aId);
9829 return E_NOTIMPL;
9830#endif
9831}
9832
9833/**
9834 * @note Locks the same as Host::detachUSBDevice() does.
9835 */
9836STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
9837{
9838 LogFlowThisFunc(("\n"));
9839
9840 AutoCaller autoCaller(this);
9841 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9842
9843#ifdef VBOX_WITH_USB
9844 USBProxyService *service = mParent->host()->usbProxyService();
9845 AssertReturn(service, E_FAIL);
9846 return service->detachDeviceFromVM(this, Guid(aId), !!aDone);
9847#else
9848 NOREF(aId);
9849 NOREF(aDone);
9850 return E_NOTIMPL;
9851#endif
9852}
9853
9854/**
9855 * Inserts all machine filters to the USB proxy service and then calls
9856 * Host::autoCaptureUSBDevices().
9857 *
9858 * Called by Console from the VM process upon VM startup.
9859 *
9860 * @note Locks what called methods lock.
9861 */
9862STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
9863{
9864 LogFlowThisFunc(("\n"));
9865
9866 AutoCaller autoCaller(this);
9867 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9868
9869#ifdef VBOX_WITH_USB
9870 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
9871 AssertComRC(rc);
9872 NOREF(rc);
9873
9874 USBProxyService *service = mParent->host()->usbProxyService();
9875 AssertReturn(service, E_FAIL);
9876 return service->autoCaptureDevicesForVM(this);
9877#else
9878 return S_OK;
9879#endif
9880}
9881
9882/**
9883 * Removes all machine filters from the USB proxy service and then calls
9884 * Host::detachAllUSBDevices().
9885 *
9886 * Called by Console from the VM process upon normal VM termination or by
9887 * SessionMachine::uninit() upon abnormal VM termination (from under the
9888 * Machine/SessionMachine lock).
9889 *
9890 * @note Locks what called methods lock.
9891 */
9892STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
9893{
9894 LogFlowThisFunc(("\n"));
9895
9896 AutoCaller autoCaller(this);
9897 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9898
9899#ifdef VBOX_WITH_USB
9900 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9901 AssertComRC(rc);
9902 NOREF(rc);
9903
9904 USBProxyService *service = mParent->host()->usbProxyService();
9905 AssertReturn(service, E_FAIL);
9906 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
9907#else
9908 NOREF(aDone);
9909 return S_OK;
9910#endif
9911}
9912
9913/**
9914 * @note Locks this object for writing.
9915 */
9916STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
9917 IProgress **aProgress)
9918{
9919 LogFlowThisFuncEnter();
9920
9921 AssertReturn(aSession, E_INVALIDARG);
9922 AssertReturn(aProgress, E_INVALIDARG);
9923
9924 AutoCaller autoCaller(this);
9925
9926 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
9927 /*
9928 * We don't assert below because it might happen that a non-direct session
9929 * informs us it is closed right after we've been uninitialized -- it's ok.
9930 */
9931 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9932
9933 /* get IInternalSessionControl interface */
9934 ComPtr<IInternalSessionControl> control(aSession);
9935
9936 ComAssertRet(!control.isNull(), E_INVALIDARG);
9937
9938 /* Creating a Progress object requires the VirtualBox lock, and
9939 * thus locking it here is required by the lock order rules. */
9940 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
9941
9942 if (control.equalsTo(mData->mSession.mDirectControl))
9943 {
9944 ComAssertRet(aProgress, E_POINTER);
9945
9946 /* The direct session is being normally closed by the client process
9947 * ----------------------------------------------------------------- */
9948
9949 /* go to the closing state (essential for all open*Session() calls and
9950 * for #checkForDeath()) */
9951 Assert(mData->mSession.mState == SessionState_Open);
9952 mData->mSession.mState = SessionState_Closing;
9953
9954 /* set direct control to NULL to release the remote instance */
9955 mData->mSession.mDirectControl.setNull();
9956 LogFlowThisFunc(("Direct control is set to NULL\n"));
9957
9958 if (mData->mSession.mProgress)
9959 {
9960 /* finalize the progress, someone might wait if a frontend
9961 * closes the session before powering on the VM. */
9962 mData->mSession.mProgress->notifyComplete(E_FAIL,
9963 COM_IIDOF(ISession),
9964 getComponentName(),
9965 tr("The VM session was closed before any attempt to power it on"));
9966 mData->mSession.mProgress.setNull();
9967 }
9968
9969 /* Create the progress object the client will use to wait until
9970 * #checkForDeath() is called to uninitialize this session object after
9971 * it releases the IPC semaphore. */
9972 Assert(mData->mSession.mProgress.isNull());
9973 ComObjPtr<Progress> progress;
9974 progress.createObject();
9975 ComPtr<IUnknown> pPeer(mPeer);
9976 progress->init(mParent, pPeer,
9977 Bstr(tr("Closing session")), FALSE /* aCancelable */);
9978 progress.queryInterfaceTo(aProgress);
9979 mData->mSession.mProgress = progress;
9980 }
9981 else
9982 {
9983 /* the remote session is being normally closed */
9984 Data::Session::RemoteControlList::iterator it =
9985 mData->mSession.mRemoteControls.begin();
9986 while (it != mData->mSession.mRemoteControls.end())
9987 {
9988 if (control.equalsTo(*it))
9989 break;
9990 ++it;
9991 }
9992 BOOL found = it != mData->mSession.mRemoteControls.end();
9993 ComAssertMsgRet(found, ("The session is not found in the session list!"),
9994 E_INVALIDARG);
9995 mData->mSession.mRemoteControls.remove(*it);
9996 }
9997
9998 LogFlowThisFuncLeave();
9999 return S_OK;
10000}
10001
10002/**
10003 * @note Locks this object for writing.
10004 */
10005STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10006{
10007 LogFlowThisFuncEnter();
10008
10009 AssertReturn(aProgress, E_INVALIDARG);
10010 AssertReturn(aStateFilePath, E_POINTER);
10011
10012 AutoCaller autoCaller(this);
10013 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10014
10015 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10016
10017 AssertReturn( mData->mMachineState == MachineState_Paused
10018 && mSnapshotData.mLastState == MachineState_Null
10019 && mSnapshotData.mProgressId.isEmpty()
10020 && mSnapshotData.mStateFilePath.isEmpty(),
10021 E_FAIL);
10022
10023 /* memorize the progress ID and add it to the global collection */
10024 Bstr progressId;
10025 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10026 AssertComRCReturn(rc, rc);
10027 rc = mParent->addProgress(aProgress);
10028 AssertComRCReturn(rc, rc);
10029
10030 Bstr stateFilePath;
10031 /* stateFilePath is null when the machine is not running */
10032 if (mData->mMachineState == MachineState_Paused)
10033 {
10034 stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
10035 mUserData->mSnapshotFolderFull.raw(),
10036 RTPATH_DELIMITER, mData->mUuid.raw());
10037 }
10038
10039 /* fill in the snapshot data */
10040 mSnapshotData.mLastState = mData->mMachineState;
10041 mSnapshotData.mProgressId = Guid(progressId);
10042 mSnapshotData.mStateFilePath = stateFilePath;
10043
10044 /* set the state to Saving (this is expected by Console::SaveState()) */
10045 setMachineState(MachineState_Saving);
10046
10047 stateFilePath.cloneTo(aStateFilePath);
10048
10049 return S_OK;
10050}
10051
10052/**
10053 * @note Locks mParent + this object for writing.
10054 */
10055STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10056{
10057 LogFlowThisFunc(("\n"));
10058
10059 AutoCaller autoCaller(this);
10060 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10061
10062 /* endSavingState() need mParent lock */
10063 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10064
10065 AssertReturn( mData->mMachineState == MachineState_Saving
10066 && mSnapshotData.mLastState != MachineState_Null
10067 && !mSnapshotData.mProgressId.isEmpty()
10068 && !mSnapshotData.mStateFilePath.isEmpty(),
10069 E_FAIL);
10070
10071 /*
10072 * on success, set the state to Saved;
10073 * on failure, set the state to the state we had when BeginSavingState() was
10074 * called (this is expected by Console::SaveState() and
10075 * Console::saveStateThread())
10076 */
10077 if (aSuccess)
10078 setMachineState(MachineState_Saved);
10079 else
10080 setMachineState(mSnapshotData.mLastState);
10081
10082 return endSavingState(aSuccess);
10083}
10084
10085/**
10086 * @note Locks this object for writing.
10087 */
10088STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10089{
10090 LogFlowThisFunc(("\n"));
10091
10092 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10093
10094 AutoCaller autoCaller(this);
10095 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10096
10097 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10098
10099 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10100 || mData->mMachineState == MachineState_Teleported
10101 || mData->mMachineState == MachineState_Aborted
10102 , E_FAIL); /** @todo setError. */
10103
10104 Utf8Str stateFilePathFull = aSavedStateFile;
10105 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10106 if (RT_FAILURE(vrc))
10107 return setError(VBOX_E_FILE_ERROR,
10108 tr("Invalid saved state file path '%ls' (%Rrc)"),
10109 aSavedStateFile,
10110 vrc);
10111
10112 mSSData->mStateFilePath = stateFilePathFull;
10113
10114 /* The below setMachineState() will detect the state transition and will
10115 * update the settings file */
10116
10117 return setMachineState(MachineState_Saved);
10118}
10119
10120STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10121 ComSafeArrayOut(BSTR, aValues),
10122 ComSafeArrayOut(ULONG64, aTimestamps),
10123 ComSafeArrayOut(BSTR, aFlags))
10124{
10125 LogFlowThisFunc(("\n"));
10126
10127#ifdef VBOX_WITH_GUEST_PROPS
10128 using namespace guestProp;
10129
10130 AutoCaller autoCaller(this);
10131 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10132
10133 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10134
10135 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10136 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10137 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10138 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10139
10140 size_t cEntries = mHWData->mGuestProperties.size();
10141 com::SafeArray<BSTR> names(cEntries);
10142 com::SafeArray<BSTR> values(cEntries);
10143 com::SafeArray<ULONG64> timestamps(cEntries);
10144 com::SafeArray<BSTR> flags(cEntries);
10145 unsigned i = 0;
10146 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10147 it != mHWData->mGuestProperties.end();
10148 ++it)
10149 {
10150 char szFlags[MAX_FLAGS_LEN + 1];
10151 it->strName.cloneTo(&names[i]);
10152 it->strValue.cloneTo(&values[i]);
10153 timestamps[i] = it->mTimestamp;
10154 /* If it is NULL, keep it NULL. */
10155 if (it->mFlags)
10156 {
10157 writeFlags(it->mFlags, szFlags);
10158 Bstr(szFlags).cloneTo(&flags[i]);
10159 }
10160 else
10161 flags[i] = NULL;
10162 ++i;
10163 }
10164 names.detachTo(ComSafeArrayOutArg(aNames));
10165 values.detachTo(ComSafeArrayOutArg(aValues));
10166 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10167 flags.detachTo(ComSafeArrayOutArg(aFlags));
10168 return S_OK;
10169#else
10170 ReturnComNotImplemented();
10171#endif
10172}
10173
10174STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10175 IN_BSTR aValue,
10176 ULONG64 aTimestamp,
10177 IN_BSTR aFlags)
10178{
10179 LogFlowThisFunc(("\n"));
10180
10181#ifdef VBOX_WITH_GUEST_PROPS
10182 using namespace guestProp;
10183
10184 CheckComArgStrNotEmptyOrNull(aName);
10185 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10186 return E_POINTER; /* aValue can be NULL to indicate deletion */
10187
10188 try
10189 {
10190 /*
10191 * Convert input up front.
10192 */
10193 Utf8Str utf8Name(aName);
10194 uint32_t fFlags = NILFLAG;
10195 if (aFlags)
10196 {
10197 Utf8Str utf8Flags(aFlags);
10198 int vrc = validateFlags(utf8Flags.raw(), &fFlags);
10199 AssertRCReturn(vrc, E_INVALIDARG);
10200 }
10201
10202 /*
10203 * Now grab the object lock, validate the state and do the update.
10204 */
10205 AutoCaller autoCaller(this);
10206 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10207
10208 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10209
10210 switch (mData->mMachineState)
10211 {
10212 case MachineState_Paused:
10213 case MachineState_Running:
10214 case MachineState_Teleporting:
10215 case MachineState_TeleportingPausedVM:
10216 case MachineState_LiveSnapshotting:
10217 case MachineState_Saving:
10218 break;
10219
10220 default:
10221 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10222 VBOX_E_INVALID_VM_STATE);
10223 }
10224
10225 setModified(IsModified_MachineData);
10226 mHWData.backup();
10227
10228 /** @todo r=bird: The careful memory handling doesn't work out here because
10229 * the catch block won't undo any damange we've done. So, if push_back throws
10230 * bad_alloc then you've lost the value.
10231 *
10232 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10233 * since values that changes actually bubbles to the end of the list. Using
10234 * something that has an efficient lookup and can tollerate a bit of updates
10235 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10236 * combination of RTStrCache (for sharing names and getting uniqueness into
10237 * the bargain) and hash/tree is another. */
10238 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10239 iter != mHWData->mGuestProperties.end();
10240 ++iter)
10241 if (utf8Name == iter->strName)
10242 {
10243 mHWData->mGuestProperties.erase(iter);
10244 mData->mGuestPropertiesModified = TRUE;
10245 break;
10246 }
10247 if (aValue != NULL)
10248 {
10249 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10250 mHWData->mGuestProperties.push_back(property);
10251 mData->mGuestPropertiesModified = TRUE;
10252 }
10253
10254 /*
10255 * Send a callback notification if appropriate
10256 */
10257 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10258 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(),
10259 RTSTR_MAX,
10260 utf8Name.raw(),
10261 RTSTR_MAX, NULL)
10262 )
10263 {
10264 alock.leave();
10265
10266 mParent->onGuestPropertyChange(mData->mUuid,
10267 aName,
10268 aValue,
10269 aFlags);
10270 }
10271 }
10272 catch (...)
10273 {
10274 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10275 }
10276 return S_OK;
10277#else
10278 ReturnComNotImplemented();
10279#endif
10280}
10281
10282// public methods only for internal purposes
10283/////////////////////////////////////////////////////////////////////////////
10284
10285/**
10286 * Called from the client watcher thread to check for expected or unexpected
10287 * death of the client process that has a direct session to this machine.
10288 *
10289 * On Win32 and on OS/2, this method is called only when we've got the
10290 * mutex (i.e. the client has either died or terminated normally) so it always
10291 * returns @c true (the client is terminated, the session machine is
10292 * uninitialized).
10293 *
10294 * On other platforms, the method returns @c true if the client process has
10295 * terminated normally or abnormally and the session machine was uninitialized,
10296 * and @c false if the client process is still alive.
10297 *
10298 * @note Locks this object for writing.
10299 */
10300bool SessionMachine::checkForDeath()
10301{
10302 Uninit::Reason reason;
10303 bool terminated = false;
10304
10305 /* Enclose autoCaller with a block because calling uninit() from under it
10306 * will deadlock. */
10307 {
10308 AutoCaller autoCaller(this);
10309 if (!autoCaller.isOk())
10310 {
10311 /* return true if not ready, to cause the client watcher to exclude
10312 * the corresponding session from watching */
10313 LogFlowThisFunc(("Already uninitialized!\n"));
10314 return true;
10315 }
10316
10317 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10318
10319 /* Determine the reason of death: if the session state is Closing here,
10320 * everything is fine. Otherwise it means that the client did not call
10321 * OnSessionEnd() before it released the IPC semaphore. This may happen
10322 * either because the client process has abnormally terminated, or
10323 * because it simply forgot to call ISession::Close() before exiting. We
10324 * threat the latter also as an abnormal termination (see
10325 * Session::uninit() for details). */
10326 reason = mData->mSession.mState == SessionState_Closing ?
10327 Uninit::Normal :
10328 Uninit::Abnormal;
10329
10330#if defined(RT_OS_WINDOWS)
10331
10332 AssertMsg(mIPCSem, ("semaphore must be created"));
10333
10334 /* release the IPC mutex */
10335 ::ReleaseMutex(mIPCSem);
10336
10337 terminated = true;
10338
10339#elif defined(RT_OS_OS2)
10340
10341 AssertMsg(mIPCSem, ("semaphore must be created"));
10342
10343 /* release the IPC mutex */
10344 ::DosReleaseMutexSem(mIPCSem);
10345
10346 terminated = true;
10347
10348#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10349
10350 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10351
10352 int val = ::semctl(mIPCSem, 0, GETVAL);
10353 if (val > 0)
10354 {
10355 /* the semaphore is signaled, meaning the session is terminated */
10356 terminated = true;
10357 }
10358
10359#else
10360# error "Port me!"
10361#endif
10362
10363 } /* AutoCaller block */
10364
10365 if (terminated)
10366 uninit(reason);
10367
10368 return terminated;
10369}
10370
10371/**
10372 * @note Locks this object for reading.
10373 */
10374HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10375{
10376 LogFlowThisFunc(("\n"));
10377
10378 AutoCaller autoCaller(this);
10379 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10380
10381 ComPtr<IInternalSessionControl> directControl;
10382 {
10383 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10384 directControl = mData->mSession.mDirectControl;
10385 }
10386
10387 /* ignore notifications sent after #OnSessionEnd() is called */
10388 if (!directControl)
10389 return S_OK;
10390
10391 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10392}
10393
10394/**
10395 * @note Locks this object for reading.
10396 */
10397HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10398{
10399 LogFlowThisFunc(("\n"));
10400
10401 AutoCaller autoCaller(this);
10402 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10403
10404 ComPtr<IInternalSessionControl> directControl;
10405 {
10406 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10407 directControl = mData->mSession.mDirectControl;
10408 }
10409
10410 /* ignore notifications sent after #OnSessionEnd() is called */
10411 if (!directControl)
10412 return S_OK;
10413
10414 return directControl->OnSerialPortChange(serialPort);
10415}
10416
10417/**
10418 * @note Locks this object for reading.
10419 */
10420HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10421{
10422 LogFlowThisFunc(("\n"));
10423
10424 AutoCaller autoCaller(this);
10425 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10426
10427 ComPtr<IInternalSessionControl> directControl;
10428 {
10429 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10430 directControl = mData->mSession.mDirectControl;
10431 }
10432
10433 /* ignore notifications sent after #OnSessionEnd() is called */
10434 if (!directControl)
10435 return S_OK;
10436
10437 return directControl->OnParallelPortChange(parallelPort);
10438}
10439
10440/**
10441 * @note Locks this object for reading.
10442 */
10443HRESULT SessionMachine::onStorageControllerChange()
10444{
10445 LogFlowThisFunc(("\n"));
10446
10447 AutoCaller autoCaller(this);
10448 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10449
10450 ComPtr<IInternalSessionControl> directControl;
10451 {
10452 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10453 directControl = mData->mSession.mDirectControl;
10454 }
10455
10456 /* ignore notifications sent after #OnSessionEnd() is called */
10457 if (!directControl)
10458 return S_OK;
10459
10460 return directControl->OnStorageControllerChange();
10461}
10462
10463/**
10464 * @note Locks this object for reading.
10465 */
10466HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10467{
10468 LogFlowThisFunc(("\n"));
10469
10470 AutoCaller autoCaller(this);
10471 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10472
10473 ComPtr<IInternalSessionControl> directControl;
10474 {
10475 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10476 directControl = mData->mSession.mDirectControl;
10477 }
10478
10479 /* ignore notifications sent after #OnSessionEnd() is called */
10480 if (!directControl)
10481 return S_OK;
10482
10483 return directControl->OnMediumChange(aAttachment, aForce);
10484}
10485
10486/**
10487 * @note Locks this object for reading.
10488 */
10489HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
10490{
10491 LogFlowThisFunc(("\n"));
10492
10493 AutoCaller autoCaller(this);
10494 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10495
10496 ComPtr<IInternalSessionControl> directControl;
10497 {
10498 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10499 directControl = mData->mSession.mDirectControl;
10500 }
10501
10502 /* ignore notifications sent after #OnSessionEnd() is called */
10503 if (!directControl)
10504 return S_OK;
10505
10506 return directControl->OnCPUChange(aCPU, aRemove);
10507}
10508
10509/**
10510 * @note Locks this object for reading.
10511 */
10512HRESULT SessionMachine::onVRDPServerChange()
10513{
10514 LogFlowThisFunc(("\n"));
10515
10516 AutoCaller autoCaller(this);
10517 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10518
10519 ComPtr<IInternalSessionControl> directControl;
10520 {
10521 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10522 directControl = mData->mSession.mDirectControl;
10523 }
10524
10525 /* ignore notifications sent after #OnSessionEnd() is called */
10526 if (!directControl)
10527 return S_OK;
10528
10529 return directControl->OnVRDPServerChange();
10530}
10531
10532/**
10533 * @note Locks this object for reading.
10534 */
10535HRESULT SessionMachine::onUSBControllerChange()
10536{
10537 LogFlowThisFunc(("\n"));
10538
10539 AutoCaller autoCaller(this);
10540 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10541
10542 ComPtr<IInternalSessionControl> directControl;
10543 {
10544 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10545 directControl = mData->mSession.mDirectControl;
10546 }
10547
10548 /* ignore notifications sent after #OnSessionEnd() is called */
10549 if (!directControl)
10550 return S_OK;
10551
10552 return directControl->OnUSBControllerChange();
10553}
10554
10555/**
10556 * @note Locks this object for reading.
10557 */
10558HRESULT SessionMachine::onSharedFolderChange()
10559{
10560 LogFlowThisFunc(("\n"));
10561
10562 AutoCaller autoCaller(this);
10563 AssertComRCReturnRC(autoCaller.rc());
10564
10565 ComPtr<IInternalSessionControl> directControl;
10566 {
10567 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10568 directControl = mData->mSession.mDirectControl;
10569 }
10570
10571 /* ignore notifications sent after #OnSessionEnd() is called */
10572 if (!directControl)
10573 return S_OK;
10574
10575 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
10576}
10577
10578/**
10579 * Returns @c true if this machine's USB controller reports it has a matching
10580 * filter for the given USB device and @c false otherwise.
10581 *
10582 * @note Caller must have requested machine read lock.
10583 */
10584bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
10585{
10586 AutoCaller autoCaller(this);
10587 /* silently return if not ready -- this method may be called after the
10588 * direct machine session has been called */
10589 if (!autoCaller.isOk())
10590 return false;
10591
10592
10593#ifdef VBOX_WITH_USB
10594 switch (mData->mMachineState)
10595 {
10596 case MachineState_Starting:
10597 case MachineState_Restoring:
10598 case MachineState_TeleportingIn:
10599 case MachineState_Paused:
10600 case MachineState_Running:
10601 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
10602 * elsewhere... */
10603 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
10604 default: break;
10605 }
10606#else
10607 NOREF(aDevice);
10608 NOREF(aMaskedIfs);
10609#endif
10610 return false;
10611}
10612
10613/**
10614 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10615 */
10616HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
10617 IVirtualBoxErrorInfo *aError,
10618 ULONG aMaskedIfs)
10619{
10620 LogFlowThisFunc(("\n"));
10621
10622 AutoCaller autoCaller(this);
10623
10624 /* This notification may happen after the machine object has been
10625 * uninitialized (the session was closed), so don't assert. */
10626 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10627
10628 ComPtr<IInternalSessionControl> directControl;
10629 {
10630 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10631 directControl = mData->mSession.mDirectControl;
10632 }
10633
10634 /* fail on notifications sent after #OnSessionEnd() is called, it is
10635 * expected by the caller */
10636 if (!directControl)
10637 return E_FAIL;
10638
10639 /* No locks should be held at this point. */
10640 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10641 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10642
10643 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
10644}
10645
10646/**
10647 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10648 */
10649HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
10650 IVirtualBoxErrorInfo *aError)
10651{
10652 LogFlowThisFunc(("\n"));
10653
10654 AutoCaller autoCaller(this);
10655
10656 /* This notification may happen after the machine object has been
10657 * uninitialized (the session was closed), so don't assert. */
10658 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10659
10660 ComPtr<IInternalSessionControl> directControl;
10661 {
10662 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10663 directControl = mData->mSession.mDirectControl;
10664 }
10665
10666 /* fail on notifications sent after #OnSessionEnd() is called, it is
10667 * expected by the caller */
10668 if (!directControl)
10669 return E_FAIL;
10670
10671 /* No locks should be held at this point. */
10672 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10673 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10674
10675 return directControl->OnUSBDeviceDetach(aId, aError);
10676}
10677
10678// protected methods
10679/////////////////////////////////////////////////////////////////////////////
10680
10681/**
10682 * Helper method to finalize saving the state.
10683 *
10684 * @note Must be called from under this object's lock.
10685 *
10686 * @param aSuccess TRUE if the snapshot has been taken successfully
10687 *
10688 * @note Locks mParent + this objects for writing.
10689 */
10690HRESULT SessionMachine::endSavingState(BOOL aSuccess)
10691{
10692 LogFlowThisFuncEnter();
10693
10694 AutoCaller autoCaller(this);
10695 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10696
10697 /* saveSettings() needs mParent lock */
10698 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10699
10700 HRESULT rc = S_OK;
10701
10702 if (aSuccess)
10703 {
10704 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
10705
10706 /* save all VM settings */
10707 rc = saveSettings(NULL);
10708 // no need to check whether VirtualBox.xml needs saving also since
10709 // we can't have a name change pending at this point
10710 }
10711 else
10712 {
10713 /* delete the saved state file (it might have been already created) */
10714 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
10715 }
10716
10717 /* remove the completed progress object */
10718 mParent->removeProgress(mSnapshotData.mProgressId);
10719
10720 /* clear out the temporary saved state data */
10721 mSnapshotData.mLastState = MachineState_Null;
10722 mSnapshotData.mProgressId.clear();
10723 mSnapshotData.mStateFilePath.setNull();
10724
10725 LogFlowThisFuncLeave();
10726 return rc;
10727}
10728
10729/**
10730 * Locks the attached media.
10731 *
10732 * All attached hard disks are locked for writing and DVD/floppy are locked for
10733 * reading. Parents of attached hard disks (if any) are locked for reading.
10734 *
10735 * This method also performs accessibility check of all media it locks: if some
10736 * media is inaccessible, the method will return a failure and a bunch of
10737 * extended error info objects per each inaccessible medium.
10738 *
10739 * Note that this method is atomic: if it returns a success, all media are
10740 * locked as described above; on failure no media is locked at all (all
10741 * succeeded individual locks will be undone).
10742 *
10743 * This method is intended to be called when the machine is in Starting or
10744 * Restoring state and asserts otherwise.
10745 *
10746 * The locks made by this method must be undone by calling #unlockMedia() when
10747 * no more needed.
10748 */
10749HRESULT SessionMachine::lockMedia()
10750{
10751 AutoCaller autoCaller(this);
10752 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10753
10754 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10755
10756 AssertReturn( mData->mMachineState == MachineState_Starting
10757 || mData->mMachineState == MachineState_Restoring
10758 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
10759
10760 try
10761 {
10762 HRESULT rc = S_OK;
10763
10764 ErrorInfoKeeper eik(true /* aIsNull */);
10765 MultiResult mrc(S_OK);
10766
10767 /* Lock all medium objects attached to the VM.
10768 * Get status for inaccessible media as well. */
10769 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10770 it != mMediaData->mAttachments.end();
10771 ++it)
10772 {
10773 DeviceType_T devType = (*it)->getType();
10774 ComObjPtr<Medium> medium = (*it)->getMedium();
10775
10776 bool first = true;
10777
10778 /** @todo split out the media locking, and put it into
10779 * MediumImpl.cpp, as it needs this functionality too. */
10780 while (!medium.isNull())
10781 {
10782 MediumState_T mediumState = medium->getState();
10783
10784 /* accessibility check must be first, otherwise locking
10785 * interferes with getting the medium state. */
10786 if (mediumState == MediumState_Inaccessible)
10787 {
10788 rc = medium->RefreshState(&mediumState);
10789 if (FAILED(rc)) throw rc;
10790
10791 if (mediumState == MediumState_Inaccessible)
10792 {
10793 Bstr error;
10794 rc = medium->COMGETTER(LastAccessError)(error.asOutParam());
10795 if (FAILED(rc)) throw rc;
10796
10797 Bstr loc;
10798 rc = medium->COMGETTER(Location)(loc.asOutParam());
10799 if (FAILED(rc)) throw rc;
10800
10801 /* collect multiple errors */
10802 eik.restore();
10803
10804 /* be in sync with MediumBase::setStateError() */
10805 Assert(!error.isEmpty());
10806 mrc = setError(E_FAIL,
10807 tr("Medium '%ls' is not accessible. %ls"),
10808 loc.raw(),
10809 error.raw());
10810
10811 eik.fetch();
10812 }
10813 }
10814
10815 if (first)
10816 {
10817 if (devType != DeviceType_DVD)
10818 {
10819 /* HardDisk and Floppy medium must be locked for writing */
10820 rc = medium->LockWrite(NULL);
10821 if (FAILED(rc)) throw rc;
10822 }
10823 else
10824 {
10825 /* DVD medium must be locked for reading */
10826 rc = medium->LockRead(NULL);
10827 if (FAILED(rc)) throw rc;
10828 }
10829
10830 mData->mSession.mLockedMedia.push_back(
10831 Data::Session::LockedMedia::value_type(
10832 ComPtr<IMedium>(medium), true));
10833
10834 first = false;
10835 }
10836 else
10837 {
10838 rc = medium->LockRead(NULL);
10839 if (FAILED(rc)) throw rc;
10840
10841 mData->mSession.mLockedMedia.push_back(
10842 Data::Session::LockedMedia::value_type(
10843 ComPtr<IMedium>(medium), false));
10844 }
10845
10846
10847 /* no locks or callers here since there should be no way to
10848 * change the hard disk parent at this point (as it is still
10849 * attached to the machine) */
10850 medium = medium->getParent();
10851 }
10852 }
10853
10854 /* @todo r=dj is this correct? first restoring the eik and then throwing? */
10855 eik.restore();
10856 HRESULT rc2 = (HRESULT)mrc;
10857 if (FAILED(rc2)) throw rc2;
10858 }
10859 catch (HRESULT aRC)
10860 {
10861 /* Unlock all locked media on failure */
10862 unlockMedia();
10863 return aRC;
10864 }
10865
10866 return S_OK;
10867}
10868
10869/**
10870 * Undoes the locks made by by #lockMedia().
10871 */
10872void SessionMachine::unlockMedia()
10873{
10874 AutoCaller autoCaller(this);
10875 AssertComRCReturnVoid(autoCaller.rc());
10876
10877 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10878
10879 /* we may be holding important error info on the current thread;
10880 * preserve it */
10881 ErrorInfoKeeper eik;
10882
10883 HRESULT rc = S_OK;
10884
10885 for (Data::Session::LockedMedia::const_iterator
10886 it = mData->mSession.mLockedMedia.begin();
10887 it != mData->mSession.mLockedMedia.end(); ++it)
10888 {
10889 MediumState_T state;
10890 if (it->second)
10891 rc = it->first->UnlockWrite(&state);
10892 else
10893 rc = it->first->UnlockRead(&state);
10894
10895 /* The second can happen if an object was re-locked in
10896 * Machine::fixupMedia(). The last can happen when e.g a DVD/Floppy
10897 * image was unmounted at runtime. */
10898 Assert(SUCCEEDED(rc) || state == MediumState_LockedRead || state == MediumState_Created);
10899 }
10900
10901 mData->mSession.mLockedMedia.clear();
10902}
10903
10904/**
10905 * Helper to change the machine state (reimplementation).
10906 *
10907 * @note Locks this object for writing.
10908 */
10909HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
10910{
10911 LogFlowThisFuncEnter();
10912 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
10913
10914 AutoCaller autoCaller(this);
10915 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10916
10917 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10918
10919 MachineState_T oldMachineState = mData->mMachineState;
10920
10921 AssertMsgReturn(oldMachineState != aMachineState,
10922 ("oldMachineState=%s, aMachineState=%s\n",
10923 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
10924 E_FAIL);
10925
10926 HRESULT rc = S_OK;
10927
10928 int stsFlags = 0;
10929 bool deleteSavedState = false;
10930
10931 /* detect some state transitions */
10932
10933 if ( ( oldMachineState == MachineState_Saved
10934 && aMachineState == MachineState_Restoring)
10935 || ( ( oldMachineState == MachineState_PoweredOff
10936 || oldMachineState == MachineState_Teleported
10937 || oldMachineState == MachineState_Aborted
10938 )
10939 && ( aMachineState == MachineState_TeleportingIn
10940 || aMachineState == MachineState_Starting
10941 )
10942 )
10943 )
10944 {
10945 /* The EMT thread is about to start */
10946
10947 /* Nothing to do here for now... */
10948
10949 /// @todo NEWMEDIA don't let mDVDDrive and other children
10950 /// change anything when in the Starting/Restoring state
10951 }
10952 else if ( ( oldMachineState == MachineState_Running
10953 || oldMachineState == MachineState_Paused
10954 || oldMachineState == MachineState_Teleporting
10955 || oldMachineState == MachineState_LiveSnapshotting
10956 || oldMachineState == MachineState_Stuck
10957 || oldMachineState == MachineState_Starting
10958 || oldMachineState == MachineState_Stopping
10959 || oldMachineState == MachineState_Saving
10960 || oldMachineState == MachineState_Restoring
10961 || oldMachineState == MachineState_TeleportingPausedVM
10962 || oldMachineState == MachineState_TeleportingIn
10963 )
10964 && ( aMachineState == MachineState_PoweredOff
10965 || aMachineState == MachineState_Saved
10966 || aMachineState == MachineState_Teleported
10967 || aMachineState == MachineState_Aborted
10968 )
10969 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
10970 * snapshot */
10971 && ( mSnapshotData.mSnapshot.isNull()
10972 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
10973 )
10974 )
10975 {
10976 /* The EMT thread has just stopped, unlock attached media. Note that as
10977 * opposed to locking that is done from Console, we do unlocking here
10978 * because the VM process may have aborted before having a chance to
10979 * properly unlock all media it locked. */
10980
10981 unlockMedia();
10982 }
10983
10984 if (oldMachineState == MachineState_Restoring)
10985 {
10986 if (aMachineState != MachineState_Saved)
10987 {
10988 /*
10989 * delete the saved state file once the machine has finished
10990 * restoring from it (note that Console sets the state from
10991 * Restoring to Saved if the VM couldn't restore successfully,
10992 * to give the user an ability to fix an error and retry --
10993 * we keep the saved state file in this case)
10994 */
10995 deleteSavedState = true;
10996 }
10997 }
10998 else if ( oldMachineState == MachineState_Saved
10999 && ( aMachineState == MachineState_PoweredOff
11000 || aMachineState == MachineState_Aborted
11001 || aMachineState == MachineState_Teleported
11002 )
11003 )
11004 {
11005 /*
11006 * delete the saved state after Console::DiscardSavedState() is called
11007 * or if the VM process (owning a direct VM session) crashed while the
11008 * VM was Saved
11009 */
11010
11011 /// @todo (dmik)
11012 // Not sure that deleting the saved state file just because of the
11013 // client death before it attempted to restore the VM is a good
11014 // thing. But when it crashes we need to go to the Aborted state
11015 // which cannot have the saved state file associated... The only
11016 // way to fix this is to make the Aborted condition not a VM state
11017 // but a bool flag: i.e., when a crash occurs, set it to true and
11018 // change the state to PoweredOff or Saved depending on the
11019 // saved state presence.
11020
11021 deleteSavedState = true;
11022 mData->mCurrentStateModified = TRUE;
11023 stsFlags |= SaveSTS_CurStateModified;
11024 }
11025
11026 if ( aMachineState == MachineState_Starting
11027 || aMachineState == MachineState_Restoring
11028 || aMachineState == MachineState_TeleportingIn
11029 )
11030 {
11031 /* set the current state modified flag to indicate that the current
11032 * state is no more identical to the state in the
11033 * current snapshot */
11034 if (!mData->mCurrentSnapshot.isNull())
11035 {
11036 mData->mCurrentStateModified = TRUE;
11037 stsFlags |= SaveSTS_CurStateModified;
11038 }
11039 }
11040
11041 if (deleteSavedState)
11042 {
11043 if (mRemoveSavedState)
11044 {
11045 Assert(!mSSData->mStateFilePath.isEmpty());
11046 RTFileDelete(mSSData->mStateFilePath.c_str());
11047 }
11048 mSSData->mStateFilePath.setNull();
11049 stsFlags |= SaveSTS_StateFilePath;
11050 }
11051
11052 /* redirect to the underlying peer machine */
11053 mPeer->setMachineState(aMachineState);
11054
11055 if ( aMachineState == MachineState_PoweredOff
11056 || aMachineState == MachineState_Teleported
11057 || aMachineState == MachineState_Aborted
11058 || aMachineState == MachineState_Saved)
11059 {
11060 /* the machine has stopped execution
11061 * (or the saved state file was adopted) */
11062 stsFlags |= SaveSTS_StateTimeStamp;
11063 }
11064
11065 if ( ( oldMachineState == MachineState_PoweredOff
11066 || oldMachineState == MachineState_Aborted
11067 || oldMachineState == MachineState_Teleported
11068 )
11069 && aMachineState == MachineState_Saved)
11070 {
11071 /* the saved state file was adopted */
11072 Assert(!mSSData->mStateFilePath.isEmpty());
11073 stsFlags |= SaveSTS_StateFilePath;
11074 }
11075
11076 if ( aMachineState == MachineState_PoweredOff
11077 || aMachineState == MachineState_Aborted
11078 || aMachineState == MachineState_Teleported)
11079 {
11080 /* Make sure any transient guest properties get removed from the
11081 * property store on shutdown. */
11082
11083 HWData::GuestPropertyList::iterator it;
11084 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11085 if (!fNeedsSaving)
11086 for (it = mHWData->mGuestProperties.begin();
11087 it != mHWData->mGuestProperties.end(); ++it)
11088 if (it->mFlags & guestProp::TRANSIENT)
11089 {
11090 fNeedsSaving = true;
11091 break;
11092 }
11093 if (fNeedsSaving)
11094 {
11095 mData->mCurrentStateModified = TRUE;
11096 stsFlags |= SaveSTS_CurStateModified;
11097 SaveSettings();
11098 }
11099 }
11100
11101 rc = saveStateSettings(stsFlags);
11102
11103 if ( ( oldMachineState != MachineState_PoweredOff
11104 && oldMachineState != MachineState_Aborted
11105 && oldMachineState != MachineState_Teleported
11106 )
11107 && ( aMachineState == MachineState_PoweredOff
11108 || aMachineState == MachineState_Aborted
11109 || aMachineState == MachineState_Teleported
11110 )
11111 )
11112 {
11113 /* we've been shut down for any reason */
11114 /* no special action so far */
11115 }
11116
11117 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11118 LogFlowThisFuncLeave();
11119 return rc;
11120}
11121
11122/**
11123 * Sends the current machine state value to the VM process.
11124 *
11125 * @note Locks this object for reading, then calls a client process.
11126 */
11127HRESULT SessionMachine::updateMachineStateOnClient()
11128{
11129 AutoCaller autoCaller(this);
11130 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11131
11132 ComPtr<IInternalSessionControl> directControl;
11133 {
11134 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11135 AssertReturn(!!mData, E_FAIL);
11136 directControl = mData->mSession.mDirectControl;
11137
11138 /* directControl may be already set to NULL here in #OnSessionEnd()
11139 * called too early by the direct session process while there is still
11140 * some operation (like discarding the snapshot) in progress. The client
11141 * process in this case is waiting inside Session::close() for the
11142 * "end session" process object to complete, while #uninit() called by
11143 * #checkForDeath() on the Watcher thread is waiting for the pending
11144 * operation to complete. For now, we accept this inconsitent behavior
11145 * and simply do nothing here. */
11146
11147 if (mData->mSession.mState == SessionState_Closing)
11148 return S_OK;
11149
11150 AssertReturn(!directControl.isNull(), E_FAIL);
11151 }
11152
11153 return directControl->UpdateMachineState(mData->mMachineState);
11154}
Note: See TracBrowser for help on using the repository browser.

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