VirtualBox

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

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

Main: rename LockForSession() API to LockMachine() and fix parameters; move code from internal open*Session() methods into LockMachine()

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

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