VirtualBox

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

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

Main: rename ISession::close() to ISession::unlockMachine(); API documentation

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