VirtualBox

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

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

Main: storage controller/attachment cleanup

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

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