VirtualBox

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

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

Main: convert more Medium and MediumFormat internals to Utf8Str

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