VirtualBox

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

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

Main: undo rename, readability

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

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