VirtualBox

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

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

Main: A little bit more logging.

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

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