VirtualBox

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

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

build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 372.5 KB
Line 
1/* $Id: MachineImpl.cpp 31225 2010-07-29 16:39:05Z 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->attachTo(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, &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->detachFrom(mData->mUuid);
3767 if (!medium.isNull())
3768 medium->attachTo(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->detachFrom(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->attachTo(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 MediaList llMedia;
4073 if (mData->mSession.mState != SessionState_Unlocked)
4074 return setError(VBOX_E_INVALID_OBJECT_STATE,
4075 tr("Cannot unregister the machine '%ls' while it is locked"),
4076 mUserData->mName.raw());
4077
4078 HRESULT rc = S_OK;
4079
4080 // this list collects the files that should be reported
4081 // as to be deleted to the caller in aFiles
4082 std::list<Bstr> 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(Bstr(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 // @todo optionally nuke snapshots
4099 size_t snapshotCount = 0;
4100 if (mData->mFirstSnapshot)
4101 snapshotCount = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4102 if (snapshotCount)
4103 return setError(VBOX_E_INVALID_OBJECT_STATE,
4104 tr("Cannot unregister the machine '%ls' because it has %d snapshots"),
4105 mUserData->mName.raw(), snapshotCount);
4106
4107 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4108 && mMediaData->mAttachments.size()
4109 )
4110 {
4111 // we have media attachments:
4112 if (fAutoCleanup)
4113 {
4114 // caller wants automatic detachment: then do that and report all media to the array
4115
4116 // make a temporary list because detachDevice invalidates iterators into
4117 // mMediaData->mAttachments
4118 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
4119
4120 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
4121 it != llAttachments2.end();
4122 ++it)
4123 {
4124 ComObjPtr<MediumAttachment> pAttach = *it;
4125 ComObjPtr<Medium> pMedium = pAttach->getMedium();
4126
4127 if (!pMedium.isNull())
4128 llMedia.push_back(pMedium);
4129
4130 rc = detachDevice(pAttach,
4131 alock,
4132 NULL /* pfNeedsSaveSettings */);
4133 if (FAILED(rc))
4134 break;
4135 };
4136 }
4137 else
4138 return setError(VBOX_E_INVALID_OBJECT_STATE,
4139 tr("Cannot unregister the machine '%ls' because it has %d media attachments"),
4140 mUserData->mName.raw(), mMediaData->mAttachments.size());
4141 }
4142
4143 if (FAILED(rc))
4144 {
4145 rollbackMedia();
4146 return rc;
4147 }
4148
4149 // commit all the media changes made above
4150 commitMedia();
4151
4152 mData->mRegistered = false;
4153
4154 // machine lock no longer needed
4155 alock.release();
4156
4157 if (fAutoCleanup)
4158 {
4159 // now go thru the list of attached media reported by prepareUnregister() and close them all
4160 for (MediaList::const_iterator it = llMedia.begin();
4161 it != llMedia.end();
4162 ++it)
4163 {
4164 ComObjPtr<Medium> pMedium = *it;
4165 Bstr bstrFile = pMedium->getLocationFull();
4166
4167 AutoCaller autoCaller2(pMedium);
4168 if (FAILED(autoCaller2.rc())) return autoCaller2.rc();
4169
4170 ErrorInfoKeeper eik;
4171 rc = pMedium->close(NULL /*fNeedsSaveSettings*/, // we'll call saveSettings() in any case below
4172 autoCaller2);
4173 // this uninitializes the medium
4174
4175 if (rc == VBOX_E_OBJECT_IN_USE)
4176 // can happen if the medium was still attached to another machine;
4177 // do not report the file to the caller then, but don't report
4178 // an error either
4179 eik.setNull();
4180 else if (SUCCEEDED(rc))
4181 // report the path to the caller
4182 llFilesForCaller.push_back(bstrFile);
4183 }
4184 }
4185
4186 // report all paths to the caller
4187 SafeArray<BSTR> sfaFiles(llFilesForCaller.size());
4188 size_t i = 0;
4189 for (std::list<Bstr>::iterator it = llFilesForCaller.begin();
4190 it != llFilesForCaller.end();
4191 ++it)
4192 it->detachTo(&sfaFiles[i++]);
4193 sfaFiles.detachTo(ComSafeArrayOutArg(aFiles));
4194
4195 mParent->unregisterMachine(this);
4196 // calls VirtualBox::saveSettings()
4197
4198 return S_OK;
4199}
4200
4201STDMETHODIMP Machine::Delete()
4202{
4203 AutoCaller autoCaller(this);
4204 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4205
4206 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4207
4208 HRESULT rc = checkStateDependency(MutableStateDep);
4209 if (FAILED(rc)) return rc;
4210
4211 if (mData->mRegistered)
4212 return setError(VBOX_E_INVALID_VM_STATE,
4213 tr("Cannot delete settings of a registered machine"));
4214
4215 ULONG uLogHistoryCount = 3;
4216 ComPtr<ISystemProperties> systemProperties;
4217 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4218 if (!systemProperties.isNull())
4219 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4220
4221 /* delete the settings only when the file actually exists */
4222 if (mData->pMachineConfigFile->fileExists())
4223 {
4224 int vrc = RTFileDelete(mData->m_strConfigFileFull.c_str());
4225 if (RT_FAILURE(vrc))
4226 return setError(VBOX_E_IPRT_ERROR,
4227 tr("Could not delete the settings file '%s' (%Rrc)"),
4228 mData->m_strConfigFileFull.raw(),
4229 vrc);
4230
4231 /* Delete any backup or uncommitted XML files. Ignore failures.
4232 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4233 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4234 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4235 RTFileDelete(otherXml.c_str());
4236 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4237 RTFileDelete(otherXml.c_str());
4238
4239 /* delete the Logs folder, nothing important should be left
4240 * there (we don't check for errors because the user might have
4241 * some private files there that we don't want to delete) */
4242 Utf8Str logFolder;
4243 getLogFolder(logFolder);
4244 Assert(logFolder.length());
4245 if (RTDirExists(logFolder.c_str()))
4246 {
4247 /* Delete all VBox.log[.N] files from the Logs folder
4248 * (this must be in sync with the rotation logic in
4249 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4250 * files that may have been created by the GUI. */
4251 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4252 logFolder.raw(), RTPATH_DELIMITER);
4253 RTFileDelete(log.c_str());
4254 log = Utf8StrFmt("%s%cVBox.png",
4255 logFolder.raw(), RTPATH_DELIMITER);
4256 RTFileDelete(log.c_str());
4257 for (int i = uLogHistoryCount; i > 0; i--)
4258 {
4259 log = Utf8StrFmt("%s%cVBox.log.%d",
4260 logFolder.raw(), RTPATH_DELIMITER, i);
4261 RTFileDelete(log.c_str());
4262 log = Utf8StrFmt("%s%cVBox.png.%d",
4263 logFolder.raw(), RTPATH_DELIMITER, i);
4264 RTFileDelete(log.c_str());
4265 }
4266
4267 RTDirRemove(logFolder.c_str());
4268 }
4269
4270 /* delete the Snapshots folder, nothing important should be left
4271 * there (we don't check for errors because the user might have
4272 * some private files there that we don't want to delete) */
4273 Utf8Str snapshotFolder(mUserData->mSnapshotFolderFull);
4274 Assert(snapshotFolder.length());
4275 if (RTDirExists(snapshotFolder.c_str()))
4276 RTDirRemove(snapshotFolder.c_str());
4277
4278 /* delete the directory that contains the settings file, but only
4279 * if it matches the VM name (i.e. a structure created by default in
4280 * prepareSaveSettings()) */
4281 {
4282 Utf8Str settingsDir;
4283 if (isInOwnDir(&settingsDir))
4284 RTDirRemove(settingsDir.c_str());
4285 }
4286 }
4287
4288 return S_OK;
4289}
4290
4291STDMETHODIMP Machine::GetSnapshot(IN_BSTR aId, ISnapshot **aSnapshot)
4292{
4293 CheckComArgOutPointerValid(aSnapshot);
4294
4295 AutoCaller autoCaller(this);
4296 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4297
4298 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4299
4300 Guid uuid(aId);
4301 /* Todo: fix this properly by perhaps introducing an isValid method for the Guid class */
4302 if ( (aId)
4303 && (*aId != '\0') // an empty Bstr means "get root snapshot", so don't fail on that
4304 && (uuid.isEmpty()))
4305 {
4306 RTUUID uuidTemp;
4307 /* Either it's a null UUID or the conversion failed. (null uuid has a special meaning in findSnapshot) */
4308 if (RT_FAILURE(RTUuidFromUtf16(&uuidTemp, aId)))
4309 return setError(E_FAIL,
4310 tr("Could not find a snapshot with UUID {%ls}"),
4311 aId);
4312 }
4313
4314 ComObjPtr<Snapshot> snapshot;
4315
4316 HRESULT rc = findSnapshot(uuid, snapshot, true /* aSetError */);
4317 snapshot.queryInterfaceTo(aSnapshot);
4318
4319 return rc;
4320}
4321
4322STDMETHODIMP Machine::FindSnapshot(IN_BSTR aName, ISnapshot **aSnapshot)
4323{
4324 CheckComArgStrNotEmptyOrNull(aName);
4325 CheckComArgOutPointerValid(aSnapshot);
4326
4327 AutoCaller autoCaller(this);
4328 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4329
4330 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4331
4332 ComObjPtr<Snapshot> snapshot;
4333
4334 HRESULT rc = findSnapshot(aName, snapshot, true /* aSetError */);
4335 snapshot.queryInterfaceTo(aSnapshot);
4336
4337 return rc;
4338}
4339
4340STDMETHODIMP Machine::SetCurrentSnapshot(IN_BSTR /* aId */)
4341{
4342 /// @todo (dmik) don't forget to set
4343 // mData->mCurrentStateModified to FALSE
4344
4345 return setError(E_NOTIMPL, "Not implemented");
4346}
4347
4348STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4349{
4350 CheckComArgStrNotEmptyOrNull(aName);
4351 CheckComArgStrNotEmptyOrNull(aHostPath);
4352
4353 AutoCaller autoCaller(this);
4354 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4355
4356 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4357
4358 HRESULT rc = checkStateDependency(MutableStateDep);
4359 if (FAILED(rc)) return rc;
4360
4361 ComObjPtr<SharedFolder> sharedFolder;
4362 rc = findSharedFolder(aName, sharedFolder, false /* aSetError */);
4363 if (SUCCEEDED(rc))
4364 return setError(VBOX_E_OBJECT_IN_USE,
4365 tr("Shared folder named '%ls' already exists"),
4366 aName);
4367
4368 sharedFolder.createObject();
4369 rc = sharedFolder->init(getMachine(), aName, aHostPath, aWritable, aAutoMount);
4370 if (FAILED(rc)) return rc;
4371
4372 setModified(IsModified_SharedFolders);
4373 mHWData.backup();
4374 mHWData->mSharedFolders.push_back(sharedFolder);
4375
4376 /* inform the direct session if any */
4377 alock.leave();
4378 onSharedFolderChange();
4379
4380 return S_OK;
4381}
4382
4383STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4384{
4385 CheckComArgStrNotEmptyOrNull(aName);
4386
4387 AutoCaller autoCaller(this);
4388 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4389
4390 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4391
4392 HRESULT rc = checkStateDependency(MutableStateDep);
4393 if (FAILED(rc)) return rc;
4394
4395 ComObjPtr<SharedFolder> sharedFolder;
4396 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4397 if (FAILED(rc)) return rc;
4398
4399 setModified(IsModified_SharedFolders);
4400 mHWData.backup();
4401 mHWData->mSharedFolders.remove(sharedFolder);
4402
4403 /* inform the direct session if any */
4404 alock.leave();
4405 onSharedFolderChange();
4406
4407 return S_OK;
4408}
4409
4410STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4411{
4412 CheckComArgOutPointerValid(aCanShow);
4413
4414 /* start with No */
4415 *aCanShow = FALSE;
4416
4417 AutoCaller autoCaller(this);
4418 AssertComRCReturnRC(autoCaller.rc());
4419
4420 ComPtr<IInternalSessionControl> directControl;
4421 {
4422 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4423
4424 if (mData->mSession.mState != SessionState_Locked)
4425 return setError(VBOX_E_INVALID_VM_STATE,
4426 tr("Machine is not locked for session (session state: %s)"),
4427 Global::stringifySessionState(mData->mSession.mState));
4428
4429 directControl = mData->mSession.mDirectControl;
4430 }
4431
4432 /* ignore calls made after #OnSessionEnd() is called */
4433 if (!directControl)
4434 return S_OK;
4435
4436 ULONG64 dummy;
4437 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
4438}
4439
4440STDMETHODIMP Machine::ShowConsoleWindow(ULONG64 *aWinId)
4441{
4442 CheckComArgOutPointerValid(aWinId);
4443
4444 AutoCaller autoCaller(this);
4445 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4446
4447 ComPtr<IInternalSessionControl> directControl;
4448 {
4449 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4450
4451 if (mData->mSession.mState != SessionState_Locked)
4452 return setError(E_FAIL,
4453 tr("Machine is not locked for session (session state: %s)"),
4454 Global::stringifySessionState(mData->mSession.mState));
4455
4456 directControl = mData->mSession.mDirectControl;
4457 }
4458
4459 /* ignore calls made after #OnSessionEnd() is called */
4460 if (!directControl)
4461 return S_OK;
4462
4463 BOOL dummy;
4464 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
4465}
4466
4467#ifdef VBOX_WITH_GUEST_PROPS
4468/**
4469 * Look up a guest property in VBoxSVC's internal structures.
4470 */
4471HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4472 BSTR *aValue,
4473 ULONG64 *aTimestamp,
4474 BSTR *aFlags) const
4475{
4476 using namespace guestProp;
4477
4478 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4479 Utf8Str strName(aName);
4480 HWData::GuestPropertyList::const_iterator it;
4481
4482 for (it = mHWData->mGuestProperties.begin();
4483 it != mHWData->mGuestProperties.end(); ++it)
4484 {
4485 if (it->strName == strName)
4486 {
4487 char szFlags[MAX_FLAGS_LEN + 1];
4488 it->strValue.cloneTo(aValue);
4489 *aTimestamp = it->mTimestamp;
4490 writeFlags(it->mFlags, szFlags);
4491 Bstr(szFlags).cloneTo(aFlags);
4492 break;
4493 }
4494 }
4495 return S_OK;
4496}
4497
4498/**
4499 * Query the VM that a guest property belongs to for the property.
4500 * @returns E_ACCESSDENIED if the VM process is not available or not
4501 * currently handling queries and the lookup should then be done in
4502 * VBoxSVC.
4503 */
4504HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4505 BSTR *aValue,
4506 ULONG64 *aTimestamp,
4507 BSTR *aFlags) const
4508{
4509 HRESULT rc;
4510 ComPtr<IInternalSessionControl> directControl;
4511 directControl = mData->mSession.mDirectControl;
4512
4513 /* fail if we were called after #OnSessionEnd() is called. This is a
4514 * silly race condition. */
4515
4516 if (!directControl)
4517 rc = E_ACCESSDENIED;
4518 else
4519 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4520 false /* isSetter */,
4521 aValue, aTimestamp, aFlags);
4522 return rc;
4523}
4524#endif // VBOX_WITH_GUEST_PROPS
4525
4526STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4527 BSTR *aValue,
4528 ULONG64 *aTimestamp,
4529 BSTR *aFlags)
4530{
4531#ifndef VBOX_WITH_GUEST_PROPS
4532 ReturnComNotImplemented();
4533#else // VBOX_WITH_GUEST_PROPS
4534 CheckComArgStrNotEmptyOrNull(aName);
4535 CheckComArgOutPointerValid(aValue);
4536 CheckComArgOutPointerValid(aTimestamp);
4537 CheckComArgOutPointerValid(aFlags);
4538
4539 AutoCaller autoCaller(this);
4540 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4541
4542 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4543 if (rc == E_ACCESSDENIED)
4544 /* The VM is not running or the service is not (yet) accessible */
4545 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4546 return rc;
4547#endif // VBOX_WITH_GUEST_PROPS
4548}
4549
4550STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4551{
4552 ULONG64 dummyTimestamp;
4553 Bstr dummyFlags;
4554 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
4555}
4556
4557STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, ULONG64 *aTimestamp)
4558{
4559 Bstr dummyValue;
4560 Bstr dummyFlags;
4561 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
4562}
4563
4564#ifdef VBOX_WITH_GUEST_PROPS
4565/**
4566 * Set a guest property in VBoxSVC's internal structures.
4567 */
4568HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4569 IN_BSTR aFlags)
4570{
4571 using namespace guestProp;
4572
4573 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4574 HRESULT rc = S_OK;
4575 HWData::GuestProperty property;
4576 property.mFlags = NILFLAG;
4577 bool found = false;
4578
4579 rc = checkStateDependency(MutableStateDep);
4580 if (FAILED(rc)) return rc;
4581
4582 try
4583 {
4584 Utf8Str utf8Name(aName);
4585 Utf8Str utf8Flags(aFlags);
4586 uint32_t fFlags = NILFLAG;
4587 if ( (aFlags != NULL)
4588 && RT_FAILURE(validateFlags(utf8Flags.raw(), &fFlags))
4589 )
4590 return setError(E_INVALIDARG,
4591 tr("Invalid flag values: '%ls'"),
4592 aFlags);
4593
4594 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
4595 * know, this is simple and do an OK job atm.) */
4596 HWData::GuestPropertyList::iterator it;
4597 for (it = mHWData->mGuestProperties.begin();
4598 it != mHWData->mGuestProperties.end(); ++it)
4599 if (it->strName == utf8Name)
4600 {
4601 property = *it;
4602 if (it->mFlags & (RDONLYHOST))
4603 rc = setError(E_ACCESSDENIED,
4604 tr("The property '%ls' cannot be changed by the host"),
4605 aName);
4606 else
4607 {
4608 setModified(IsModified_MachineData);
4609 mHWData.backup(); // @todo r=dj backup in a loop?!?
4610
4611 /* The backup() operation invalidates our iterator, so
4612 * get a new one. */
4613 for (it = mHWData->mGuestProperties.begin();
4614 it->strName != utf8Name;
4615 ++it)
4616 ;
4617 mHWData->mGuestProperties.erase(it);
4618 }
4619 found = true;
4620 break;
4621 }
4622 if (found && SUCCEEDED(rc))
4623 {
4624 if (*aValue)
4625 {
4626 RTTIMESPEC time;
4627 property.strValue = aValue;
4628 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4629 if (aFlags != NULL)
4630 property.mFlags = fFlags;
4631 mHWData->mGuestProperties.push_back(property);
4632 }
4633 }
4634 else if (SUCCEEDED(rc) && *aValue)
4635 {
4636 RTTIMESPEC time;
4637 setModified(IsModified_MachineData);
4638 mHWData.backup();
4639 property.strName = aName;
4640 property.strValue = aValue;
4641 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4642 property.mFlags = fFlags;
4643 mHWData->mGuestProperties.push_back(property);
4644 }
4645 if ( SUCCEEDED(rc)
4646 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
4647 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(), RTSTR_MAX,
4648 utf8Name.raw(), RTSTR_MAX, NULL) )
4649 )
4650 {
4651 /** @todo r=bird: Why aren't we leaving the lock here? The
4652 * same code in PushGuestProperty does... */
4653 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
4654 }
4655 }
4656 catch (std::bad_alloc &)
4657 {
4658 rc = E_OUTOFMEMORY;
4659 }
4660
4661 return rc;
4662}
4663
4664/**
4665 * Set a property on the VM that that property belongs to.
4666 * @returns E_ACCESSDENIED if the VM process is not available or not
4667 * currently handling queries and the setting should then be done in
4668 * VBoxSVC.
4669 */
4670HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
4671 IN_BSTR aFlags)
4672{
4673 HRESULT rc;
4674
4675 try {
4676 ComPtr<IInternalSessionControl> directControl =
4677 mData->mSession.mDirectControl;
4678
4679 BSTR dummy = NULL; /* will not be changed (setter) */
4680 ULONG64 dummy64;
4681 if (!directControl)
4682 rc = E_ACCESSDENIED;
4683 else
4684 rc = directControl->AccessGuestProperty
4685 (aName,
4686 /** @todo Fix when adding DeleteGuestProperty(),
4687 see defect. */
4688 *aValue ? aValue : NULL, aFlags, true /* isSetter */,
4689 &dummy, &dummy64, &dummy);
4690 }
4691 catch (std::bad_alloc &)
4692 {
4693 rc = E_OUTOFMEMORY;
4694 }
4695
4696 return rc;
4697}
4698#endif // VBOX_WITH_GUEST_PROPS
4699
4700STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
4701 IN_BSTR aFlags)
4702{
4703#ifndef VBOX_WITH_GUEST_PROPS
4704 ReturnComNotImplemented();
4705#else // VBOX_WITH_GUEST_PROPS
4706 CheckComArgStrNotEmptyOrNull(aName);
4707 if ((aFlags != NULL) && !VALID_PTR(aFlags))
4708 return E_INVALIDARG;
4709 AutoCaller autoCaller(this);
4710 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4711
4712 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
4713 if (rc == E_ACCESSDENIED)
4714 /* The VM is not running or the service is not (yet) accessible */
4715 rc = setGuestPropertyToService(aName, aValue, aFlags);
4716 return rc;
4717#endif // VBOX_WITH_GUEST_PROPS
4718}
4719
4720STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
4721{
4722 return SetGuestProperty(aName, aValue, NULL);
4723}
4724
4725#ifdef VBOX_WITH_GUEST_PROPS
4726/**
4727 * Enumerate the guest properties in VBoxSVC's internal structures.
4728 */
4729HRESULT Machine::enumerateGuestPropertiesInService
4730 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4731 ComSafeArrayOut(BSTR, aValues),
4732 ComSafeArrayOut(ULONG64, aTimestamps),
4733 ComSafeArrayOut(BSTR, aFlags))
4734{
4735 using namespace guestProp;
4736
4737 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4738 Utf8Str strPatterns(aPatterns);
4739
4740 /*
4741 * Look for matching patterns and build up a list.
4742 */
4743 HWData::GuestPropertyList propList;
4744 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
4745 it != mHWData->mGuestProperties.end();
4746 ++it)
4747 if ( strPatterns.isEmpty()
4748 || RTStrSimplePatternMultiMatch(strPatterns.raw(),
4749 RTSTR_MAX,
4750 it->strName.raw(),
4751 RTSTR_MAX, NULL)
4752 )
4753 propList.push_back(*it);
4754
4755 /*
4756 * And build up the arrays for returning the property information.
4757 */
4758 size_t cEntries = propList.size();
4759 SafeArray<BSTR> names(cEntries);
4760 SafeArray<BSTR> values(cEntries);
4761 SafeArray<ULONG64> timestamps(cEntries);
4762 SafeArray<BSTR> flags(cEntries);
4763 size_t iProp = 0;
4764 for (HWData::GuestPropertyList::iterator it = propList.begin();
4765 it != propList.end();
4766 ++it)
4767 {
4768 char szFlags[MAX_FLAGS_LEN + 1];
4769 it->strName.cloneTo(&names[iProp]);
4770 it->strValue.cloneTo(&values[iProp]);
4771 timestamps[iProp] = it->mTimestamp;
4772 writeFlags(it->mFlags, szFlags);
4773 Bstr(szFlags).cloneTo(&flags[iProp]);
4774 ++iProp;
4775 }
4776 names.detachTo(ComSafeArrayOutArg(aNames));
4777 values.detachTo(ComSafeArrayOutArg(aValues));
4778 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
4779 flags.detachTo(ComSafeArrayOutArg(aFlags));
4780 return S_OK;
4781}
4782
4783/**
4784 * Enumerate the properties managed by a VM.
4785 * @returns E_ACCESSDENIED if the VM process is not available or not
4786 * currently handling queries and the setting should then be done in
4787 * VBoxSVC.
4788 */
4789HRESULT Machine::enumerateGuestPropertiesOnVM
4790 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4791 ComSafeArrayOut(BSTR, aValues),
4792 ComSafeArrayOut(ULONG64, aTimestamps),
4793 ComSafeArrayOut(BSTR, aFlags))
4794{
4795 HRESULT rc;
4796 ComPtr<IInternalSessionControl> directControl;
4797 directControl = mData->mSession.mDirectControl;
4798
4799 if (!directControl)
4800 rc = E_ACCESSDENIED;
4801 else
4802 rc = directControl->EnumerateGuestProperties
4803 (aPatterns, ComSafeArrayOutArg(aNames),
4804 ComSafeArrayOutArg(aValues),
4805 ComSafeArrayOutArg(aTimestamps),
4806 ComSafeArrayOutArg(aFlags));
4807 return rc;
4808}
4809#endif // VBOX_WITH_GUEST_PROPS
4810
4811STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
4812 ComSafeArrayOut(BSTR, aNames),
4813 ComSafeArrayOut(BSTR, aValues),
4814 ComSafeArrayOut(ULONG64, aTimestamps),
4815 ComSafeArrayOut(BSTR, aFlags))
4816{
4817#ifndef VBOX_WITH_GUEST_PROPS
4818 ReturnComNotImplemented();
4819#else // VBOX_WITH_GUEST_PROPS
4820 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
4821 return E_POINTER;
4822
4823 CheckComArgOutSafeArrayPointerValid(aNames);
4824 CheckComArgOutSafeArrayPointerValid(aValues);
4825 CheckComArgOutSafeArrayPointerValid(aTimestamps);
4826 CheckComArgOutSafeArrayPointerValid(aFlags);
4827
4828 AutoCaller autoCaller(this);
4829 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4830
4831 HRESULT rc = enumerateGuestPropertiesOnVM
4832 (aPatterns, ComSafeArrayOutArg(aNames),
4833 ComSafeArrayOutArg(aValues),
4834 ComSafeArrayOutArg(aTimestamps),
4835 ComSafeArrayOutArg(aFlags));
4836 if (rc == E_ACCESSDENIED)
4837 /* The VM is not running or the service is not (yet) accessible */
4838 rc = enumerateGuestPropertiesInService
4839 (aPatterns, ComSafeArrayOutArg(aNames),
4840 ComSafeArrayOutArg(aValues),
4841 ComSafeArrayOutArg(aTimestamps),
4842 ComSafeArrayOutArg(aFlags));
4843 return rc;
4844#endif // VBOX_WITH_GUEST_PROPS
4845}
4846
4847STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
4848 ComSafeArrayOut(IMediumAttachment*, aAttachments))
4849{
4850 MediaData::AttachmentList atts;
4851
4852 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
4853 if (FAILED(rc)) return rc;
4854
4855 SafeIfaceArray<IMediumAttachment> attachments(atts);
4856 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
4857
4858 return S_OK;
4859}
4860
4861STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
4862 LONG aControllerPort,
4863 LONG aDevice,
4864 IMediumAttachment **aAttachment)
4865{
4866 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4867 aControllerName, aControllerPort, aDevice));
4868
4869 CheckComArgStrNotEmptyOrNull(aControllerName);
4870 CheckComArgOutPointerValid(aAttachment);
4871
4872 AutoCaller autoCaller(this);
4873 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4874
4875 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4876
4877 *aAttachment = NULL;
4878
4879 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4880 aControllerName,
4881 aControllerPort,
4882 aDevice);
4883 if (pAttach.isNull())
4884 return setError(VBOX_E_OBJECT_NOT_FOUND,
4885 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4886 aDevice, aControllerPort, aControllerName);
4887
4888 pAttach.queryInterfaceTo(aAttachment);
4889
4890 return S_OK;
4891}
4892
4893STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
4894 StorageBus_T aConnectionType,
4895 IStorageController **controller)
4896{
4897 CheckComArgStrNotEmptyOrNull(aName);
4898
4899 if ( (aConnectionType <= StorageBus_Null)
4900 || (aConnectionType > StorageBus_SAS))
4901 return setError(E_INVALIDARG,
4902 tr("Invalid connection type: %d"),
4903 aConnectionType);
4904
4905 AutoCaller autoCaller(this);
4906 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4907
4908 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4909
4910 HRESULT rc = checkStateDependency(MutableStateDep);
4911 if (FAILED(rc)) return rc;
4912
4913 /* try to find one with the name first. */
4914 ComObjPtr<StorageController> ctrl;
4915
4916 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
4917 if (SUCCEEDED(rc))
4918 return setError(VBOX_E_OBJECT_IN_USE,
4919 tr("Storage controller named '%ls' already exists"),
4920 aName);
4921
4922 ctrl.createObject();
4923
4924 /* get a new instance number for the storage controller */
4925 ULONG ulInstance = 0;
4926 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4927 it != mStorageControllers->end();
4928 ++it)
4929 {
4930 if ((*it)->getStorageBus() == aConnectionType)
4931 {
4932 ULONG ulCurInst = (*it)->getInstance();
4933
4934 if (ulCurInst >= ulInstance)
4935 ulInstance = ulCurInst + 1;
4936 }
4937 }
4938
4939 rc = ctrl->init(this, aName, aConnectionType, ulInstance);
4940 if (FAILED(rc)) return rc;
4941
4942 setModified(IsModified_Storage);
4943 mStorageControllers.backup();
4944 mStorageControllers->push_back(ctrl);
4945
4946 ctrl.queryInterfaceTo(controller);
4947
4948 /* inform the direct session if any */
4949 alock.leave();
4950 onStorageControllerChange();
4951
4952 return S_OK;
4953}
4954
4955STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
4956 IStorageController **aStorageController)
4957{
4958 CheckComArgStrNotEmptyOrNull(aName);
4959
4960 AutoCaller autoCaller(this);
4961 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4962
4963 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4964
4965 ComObjPtr<StorageController> ctrl;
4966
4967 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
4968 if (SUCCEEDED(rc))
4969 ctrl.queryInterfaceTo(aStorageController);
4970
4971 return rc;
4972}
4973
4974STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
4975 IStorageController **aStorageController)
4976{
4977 AutoCaller autoCaller(this);
4978 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4979
4980 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4981
4982 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4983 it != mStorageControllers->end();
4984 ++it)
4985 {
4986 if ((*it)->getInstance() == aInstance)
4987 {
4988 (*it).queryInterfaceTo(aStorageController);
4989 return S_OK;
4990 }
4991 }
4992
4993 return setError(VBOX_E_OBJECT_NOT_FOUND,
4994 tr("Could not find a storage controller with instance number '%lu'"),
4995 aInstance);
4996}
4997
4998STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
4999{
5000 CheckComArgStrNotEmptyOrNull(aName);
5001
5002 AutoCaller autoCaller(this);
5003 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5004
5005 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5006
5007 HRESULT rc = checkStateDependency(MutableStateDep);
5008 if (FAILED(rc)) return rc;
5009
5010 ComObjPtr<StorageController> ctrl;
5011 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5012 if (FAILED(rc)) return rc;
5013
5014 /* We can remove the controller only if there is no device attached. */
5015 /* check if the device slot is already busy */
5016 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5017 it != mMediaData->mAttachments.end();
5018 ++it)
5019 {
5020 if ((*it)->getControllerName() == aName)
5021 return setError(VBOX_E_OBJECT_IN_USE,
5022 tr("Storage controller named '%ls' has still devices attached"),
5023 aName);
5024 }
5025
5026 /* We can remove it now. */
5027 setModified(IsModified_Storage);
5028 mStorageControllers.backup();
5029
5030 ctrl->unshare();
5031
5032 mStorageControllers->remove(ctrl);
5033
5034 /* inform the direct session if any */
5035 alock.leave();
5036 onStorageControllerChange();
5037
5038 return S_OK;
5039}
5040
5041/* @todo where is the right place for this? */
5042#define sSSMDisplayScreenshotVer 0x00010001
5043
5044static int readSavedDisplayScreenshot(Utf8Str *pStateFilePath, uint32_t u32Type, uint8_t **ppu8Data, uint32_t *pcbData, uint32_t *pu32Width, uint32_t *pu32Height)
5045{
5046 LogFlowFunc(("u32Type = %d [%s]\n", u32Type, pStateFilePath->raw()));
5047
5048 /* @todo cache read data */
5049 if (pStateFilePath->isEmpty())
5050 {
5051 /* No saved state data. */
5052 return VERR_NOT_SUPPORTED;
5053 }
5054
5055 uint8_t *pu8Data = NULL;
5056 uint32_t cbData = 0;
5057 uint32_t u32Width = 0;
5058 uint32_t u32Height = 0;
5059
5060 PSSMHANDLE pSSM;
5061 int vrc = SSMR3Open(pStateFilePath->raw(), 0 /*fFlags*/, &pSSM);
5062 if (RT_SUCCESS(vrc))
5063 {
5064 uint32_t uVersion;
5065 vrc = SSMR3Seek(pSSM, "DisplayScreenshot", 1100 /*iInstance*/, &uVersion);
5066 if (RT_SUCCESS(vrc))
5067 {
5068 if (uVersion == sSSMDisplayScreenshotVer)
5069 {
5070 uint32_t cBlocks;
5071 vrc = SSMR3GetU32(pSSM, &cBlocks);
5072 AssertRCReturn(vrc, vrc);
5073
5074 for (uint32_t i = 0; i < cBlocks; i++)
5075 {
5076 uint32_t cbBlock;
5077 vrc = SSMR3GetU32(pSSM, &cbBlock);
5078 AssertRCBreak(vrc);
5079
5080 uint32_t typeOfBlock;
5081 vrc = SSMR3GetU32(pSSM, &typeOfBlock);
5082 AssertRCBreak(vrc);
5083
5084 LogFlowFunc(("[%d] type %d, size %d bytes\n", i, typeOfBlock, cbBlock));
5085
5086 if (typeOfBlock == u32Type)
5087 {
5088 if (cbBlock > 2 * sizeof(uint32_t))
5089 {
5090 cbData = cbBlock - 2 * sizeof(uint32_t);
5091 pu8Data = (uint8_t *)RTMemAlloc(cbData);
5092 if (pu8Data == NULL)
5093 {
5094 vrc = VERR_NO_MEMORY;
5095 break;
5096 }
5097
5098 vrc = SSMR3GetU32(pSSM, &u32Width);
5099 AssertRCBreak(vrc);
5100 vrc = SSMR3GetU32(pSSM, &u32Height);
5101 AssertRCBreak(vrc);
5102 vrc = SSMR3GetMem(pSSM, pu8Data, cbData);
5103 AssertRCBreak(vrc);
5104 }
5105 else
5106 {
5107 /* No saved state data. */
5108 vrc = VERR_NOT_SUPPORTED;
5109 }
5110
5111 break;
5112 }
5113 else
5114 {
5115 /* displaySSMSaveScreenshot did not write any data, if
5116 * cbBlock was == 2 * sizeof (uint32_t).
5117 */
5118 if (cbBlock > 2 * sizeof (uint32_t))
5119 {
5120 vrc = SSMR3Skip(pSSM, cbBlock);
5121 AssertRCBreak(vrc);
5122 }
5123 }
5124 }
5125 }
5126 else
5127 {
5128 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
5129 }
5130 }
5131
5132 SSMR3Close(pSSM);
5133 }
5134
5135 if (RT_SUCCESS(vrc))
5136 {
5137 if (u32Type == 0 && cbData % 4 != 0)
5138 {
5139 /* Bitmap is 32bpp, so data is invalid. */
5140 vrc = VERR_SSM_UNEXPECTED_DATA;
5141 }
5142 }
5143
5144 if (RT_SUCCESS(vrc))
5145 {
5146 *ppu8Data = pu8Data;
5147 *pcbData = cbData;
5148 *pu32Width = u32Width;
5149 *pu32Height = u32Height;
5150 LogFlowFunc(("cbData %d, u32Width %d, u32Height %d\n", cbData, u32Width, u32Height));
5151 }
5152
5153 LogFlowFunc(("vrc %Rrc\n", vrc));
5154 return vrc;
5155}
5156
5157static void freeSavedDisplayScreenshot(uint8_t *pu8Data)
5158{
5159 /* @todo not necessary when caching is implemented. */
5160 RTMemFree(pu8Data);
5161}
5162
5163STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5164{
5165 LogFlowThisFunc(("\n"));
5166
5167 CheckComArgNotNull(aSize);
5168 CheckComArgNotNull(aWidth);
5169 CheckComArgNotNull(aHeight);
5170
5171 if (aScreenId != 0)
5172 return E_NOTIMPL;
5173
5174 AutoCaller autoCaller(this);
5175 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5176
5177 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5178
5179 uint8_t *pu8Data = NULL;
5180 uint32_t cbData = 0;
5181 uint32_t u32Width = 0;
5182 uint32_t u32Height = 0;
5183
5184 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5185
5186 if (RT_FAILURE(vrc))
5187 return setError(VBOX_E_IPRT_ERROR,
5188 tr("Saved screenshot data is not available (%Rrc)"),
5189 vrc);
5190
5191 *aSize = cbData;
5192 *aWidth = u32Width;
5193 *aHeight = u32Height;
5194
5195 freeSavedDisplayScreenshot(pu8Data);
5196
5197 return S_OK;
5198}
5199
5200STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5201{
5202 LogFlowThisFunc(("\n"));
5203
5204 CheckComArgNotNull(aWidth);
5205 CheckComArgNotNull(aHeight);
5206 CheckComArgOutSafeArrayPointerValid(aData);
5207
5208 if (aScreenId != 0)
5209 return E_NOTIMPL;
5210
5211 AutoCaller autoCaller(this);
5212 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5213
5214 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5215
5216 uint8_t *pu8Data = NULL;
5217 uint32_t cbData = 0;
5218 uint32_t u32Width = 0;
5219 uint32_t u32Height = 0;
5220
5221 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5222
5223 if (RT_FAILURE(vrc))
5224 return setError(VBOX_E_IPRT_ERROR,
5225 tr("Saved screenshot data is not available (%Rrc)"),
5226 vrc);
5227
5228 *aWidth = u32Width;
5229 *aHeight = u32Height;
5230
5231 com::SafeArray<BYTE> bitmap(cbData);
5232 /* Convert pixels to format expected by the API caller. */
5233 if (aBGR)
5234 {
5235 /* [0] B, [1] G, [2] R, [3] A. */
5236 for (unsigned i = 0; i < cbData; i += 4)
5237 {
5238 bitmap[i] = pu8Data[i];
5239 bitmap[i + 1] = pu8Data[i + 1];
5240 bitmap[i + 2] = pu8Data[i + 2];
5241 bitmap[i + 3] = 0xff;
5242 }
5243 }
5244 else
5245 {
5246 /* [0] R, [1] G, [2] B, [3] A. */
5247 for (unsigned i = 0; i < cbData; i += 4)
5248 {
5249 bitmap[i] = pu8Data[i + 2];
5250 bitmap[i + 1] = pu8Data[i + 1];
5251 bitmap[i + 2] = pu8Data[i];
5252 bitmap[i + 3] = 0xff;
5253 }
5254 }
5255 bitmap.detachTo(ComSafeArrayOutArg(aData));
5256
5257 freeSavedDisplayScreenshot(pu8Data);
5258
5259 return S_OK;
5260}
5261
5262STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5263{
5264 LogFlowThisFunc(("\n"));
5265
5266 CheckComArgNotNull(aSize);
5267 CheckComArgNotNull(aWidth);
5268 CheckComArgNotNull(aHeight);
5269
5270 if (aScreenId != 0)
5271 return E_NOTIMPL;
5272
5273 AutoCaller autoCaller(this);
5274 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5275
5276 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5277
5278 uint8_t *pu8Data = NULL;
5279 uint32_t cbData = 0;
5280 uint32_t u32Width = 0;
5281 uint32_t u32Height = 0;
5282
5283 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5284
5285 if (RT_FAILURE(vrc))
5286 return setError(VBOX_E_IPRT_ERROR,
5287 tr("Saved screenshot data is not available (%Rrc)"),
5288 vrc);
5289
5290 *aSize = cbData;
5291 *aWidth = u32Width;
5292 *aHeight = u32Height;
5293
5294 freeSavedDisplayScreenshot(pu8Data);
5295
5296 return S_OK;
5297}
5298
5299STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5300{
5301 LogFlowThisFunc(("\n"));
5302
5303 CheckComArgNotNull(aWidth);
5304 CheckComArgNotNull(aHeight);
5305 CheckComArgOutSafeArrayPointerValid(aData);
5306
5307 if (aScreenId != 0)
5308 return E_NOTIMPL;
5309
5310 AutoCaller autoCaller(this);
5311 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5312
5313 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5314
5315 uint8_t *pu8Data = NULL;
5316 uint32_t cbData = 0;
5317 uint32_t u32Width = 0;
5318 uint32_t u32Height = 0;
5319
5320 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5321
5322 if (RT_FAILURE(vrc))
5323 return setError(VBOX_E_IPRT_ERROR,
5324 tr("Saved screenshot data is not available (%Rrc)"),
5325 vrc);
5326
5327 *aWidth = u32Width;
5328 *aHeight = u32Height;
5329
5330 com::SafeArray<BYTE> png(cbData);
5331 for (unsigned i = 0; i < cbData; i++)
5332 png[i] = pu8Data[i];
5333 png.detachTo(ComSafeArrayOutArg(aData));
5334
5335 freeSavedDisplayScreenshot(pu8Data);
5336
5337 return S_OK;
5338}
5339
5340STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5341{
5342 HRESULT rc = S_OK;
5343 LogFlowThisFunc(("\n"));
5344
5345 AutoCaller autoCaller(this);
5346 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5347
5348 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5349
5350 if (!mHWData->mCPUHotPlugEnabled)
5351 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5352
5353 if (aCpu >= mHWData->mCPUCount)
5354 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5355
5356 if (mHWData->mCPUAttached[aCpu])
5357 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5358
5359 alock.release();
5360 rc = onCPUChange(aCpu, false);
5361 alock.acquire();
5362 if (FAILED(rc)) return rc;
5363
5364 setModified(IsModified_MachineData);
5365 mHWData.backup();
5366 mHWData->mCPUAttached[aCpu] = true;
5367
5368 /* Save settings if online */
5369 if (Global::IsOnline(mData->mMachineState))
5370 saveSettings(NULL);
5371
5372 return S_OK;
5373}
5374
5375STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5376{
5377 HRESULT rc = S_OK;
5378 LogFlowThisFunc(("\n"));
5379
5380 AutoCaller autoCaller(this);
5381 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5382
5383 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5384
5385 if (!mHWData->mCPUHotPlugEnabled)
5386 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5387
5388 if (aCpu >= SchemaDefs::MaxCPUCount)
5389 return setError(E_INVALIDARG,
5390 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5391 SchemaDefs::MaxCPUCount);
5392
5393 if (!mHWData->mCPUAttached[aCpu])
5394 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5395
5396 /* CPU 0 can't be detached */
5397 if (aCpu == 0)
5398 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5399
5400 alock.release();
5401 rc = onCPUChange(aCpu, true);
5402 alock.acquire();
5403 if (FAILED(rc)) return rc;
5404
5405 setModified(IsModified_MachineData);
5406 mHWData.backup();
5407 mHWData->mCPUAttached[aCpu] = false;
5408
5409 /* Save settings if online */
5410 if (Global::IsOnline(mData->mMachineState))
5411 saveSettings(NULL);
5412
5413 return S_OK;
5414}
5415
5416STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5417{
5418 LogFlowThisFunc(("\n"));
5419
5420 CheckComArgNotNull(aCpuAttached);
5421
5422 *aCpuAttached = false;
5423
5424 AutoCaller autoCaller(this);
5425 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5426
5427 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5428
5429 /* If hotplug is enabled the CPU is always enabled. */
5430 if (!mHWData->mCPUHotPlugEnabled)
5431 {
5432 if (aCpu < mHWData->mCPUCount)
5433 *aCpuAttached = true;
5434 }
5435 else
5436 {
5437 if (aCpu < SchemaDefs::MaxCPUCount)
5438 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5439 }
5440
5441 return S_OK;
5442}
5443
5444STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5445{
5446 CheckComArgOutPointerValid(aName);
5447
5448 AutoCaller autoCaller(this);
5449 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5450
5451 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5452
5453 Utf8Str log = queryLogFilename(aIdx);
5454 if (!RTFileExists(log.c_str()))
5455 log.setNull();
5456 log.cloneTo(aName);
5457
5458 return S_OK;
5459}
5460
5461STDMETHODIMP Machine::ReadLog(ULONG aIdx, ULONG64 aOffset, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
5462{
5463 LogFlowThisFunc(("\n"));
5464 CheckComArgOutSafeArrayPointerValid(aData);
5465
5466 AutoCaller autoCaller(this);
5467 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5468
5469 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5470
5471 HRESULT rc = S_OK;
5472 Utf8Str log = queryLogFilename(aIdx);
5473
5474 /* do not unnecessarily hold the lock while doing something which does
5475 * not need the lock and potentially takes a long time. */
5476 alock.release();
5477
5478 /* Limit the chunk size to 32K for now, as that gives better performance
5479 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5480 * One byte expands to approx. 25 bytes of breathtaking XML. */
5481 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5482 com::SafeArray<BYTE> logData(cbData);
5483
5484 RTFILE LogFile;
5485 int vrc = RTFileOpen(&LogFile, log.raw(),
5486 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5487 if (RT_SUCCESS(vrc))
5488 {
5489 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5490 if (RT_SUCCESS(vrc))
5491 logData.resize(cbData);
5492 else
5493 rc = setError(VBOX_E_IPRT_ERROR,
5494 tr("Could not read log file '%s' (%Rrc)"),
5495 log.raw(), vrc);
5496 RTFileClose(LogFile);
5497 }
5498 else
5499 rc = setError(VBOX_E_IPRT_ERROR,
5500 tr("Could not open log file '%s' (%Rrc)"),
5501 log.raw(), vrc);
5502
5503 if (FAILED(rc))
5504 logData.resize(0);
5505 logData.detachTo(ComSafeArrayOutArg(aData));
5506
5507 return rc;
5508}
5509
5510
5511// public methods for internal purposes
5512/////////////////////////////////////////////////////////////////////////////
5513
5514/**
5515 * Adds the given IsModified_* flag to the dirty flags of the machine.
5516 * This must be called either during loadSettings or under the machine write lock.
5517 * @param fl
5518 */
5519void Machine::setModified(uint32_t fl)
5520{
5521 mData->flModifications |= fl;
5522}
5523
5524/**
5525 * Saves the registry entry of this machine to the given configuration node.
5526 *
5527 * @param aEntryNode Node to save the registry entry to.
5528 *
5529 * @note locks this object for reading.
5530 */
5531HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5532{
5533 AutoLimitedCaller autoCaller(this);
5534 AssertComRCReturnRC(autoCaller.rc());
5535
5536 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5537
5538 data.uuid = mData->mUuid;
5539 data.strSettingsFile = mData->m_strConfigFile;
5540
5541 return S_OK;
5542}
5543
5544/**
5545 * Calculates the absolute path of the given path taking the directory of the
5546 * machine settings file as the current directory.
5547 *
5548 * @param aPath Path to calculate the absolute path for.
5549 * @param aResult Where to put the result (used only on success, can be the
5550 * same Utf8Str instance as passed in @a aPath).
5551 * @return IPRT result.
5552 *
5553 * @note Locks this object for reading.
5554 */
5555int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5556{
5557 AutoCaller autoCaller(this);
5558 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5559
5560 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5561
5562 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5563
5564 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5565
5566 strSettingsDir.stripFilename();
5567 char folder[RTPATH_MAX];
5568 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5569 if (RT_SUCCESS(vrc))
5570 aResult = folder;
5571
5572 return vrc;
5573}
5574
5575/**
5576 * Copies strSource to strTarget, making it relative to the machine folder
5577 * if it is a subdirectory thereof, or simply copying it otherwise.
5578 *
5579 * @param strSource Path to evalue and copy.
5580 * @param strTarget Buffer to receive target path.
5581 *
5582 * @note Locks this object for reading.
5583 */
5584void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5585 Utf8Str &strTarget)
5586{
5587 AutoCaller autoCaller(this);
5588 AssertComRCReturn(autoCaller.rc(), (void)0);
5589
5590 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5591
5592 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5593 // use strTarget as a temporary buffer to hold the machine settings dir
5594 strTarget = mData->m_strConfigFileFull;
5595 strTarget.stripFilename();
5596 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5597 // is relative: then append what's left
5598 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
5599 else
5600 // is not relative: then overwrite
5601 strTarget = strSource;
5602}
5603
5604/**
5605 * Returns the full path to the machine's log folder in the
5606 * \a aLogFolder argument.
5607 */
5608void Machine::getLogFolder(Utf8Str &aLogFolder)
5609{
5610 AutoCaller autoCaller(this);
5611 AssertComRCReturnVoid(autoCaller.rc());
5612
5613 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5614
5615 Utf8Str settingsDir;
5616 if (isInOwnDir(&settingsDir))
5617 {
5618 /* Log folder is <Machines>/<VM_Name>/Logs */
5619 aLogFolder = Utf8StrFmt("%s%cLogs", settingsDir.raw(), RTPATH_DELIMITER);
5620 }
5621 else
5622 {
5623 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5624 Assert(!mUserData->mSnapshotFolderFull.isEmpty());
5625 aLogFolder = Utf8StrFmt ("%ls%cLogs", mUserData->mSnapshotFolderFull.raw(),
5626 RTPATH_DELIMITER);
5627 }
5628}
5629
5630/**
5631 * Returns the full path to the machine's log file for an given index.
5632 */
5633Utf8Str Machine::queryLogFilename(ULONG idx)
5634{
5635 Utf8Str logFolder;
5636 getLogFolder(logFolder);
5637 Assert(logFolder.length());
5638 Utf8Str log;
5639 if (idx == 0)
5640 log = Utf8StrFmt("%s%cVBox.log",
5641 logFolder.raw(), RTPATH_DELIMITER);
5642 else
5643 log = Utf8StrFmt("%s%cVBox.log.%d",
5644 logFolder.raw(), RTPATH_DELIMITER, idx);
5645 return log;
5646}
5647
5648/**
5649 * @note Locks this object for writing, calls the client process
5650 * (inside the lock).
5651 */
5652HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5653 IN_BSTR aType,
5654 IN_BSTR aEnvironment,
5655 ProgressProxy *aProgress)
5656{
5657 LogFlowThisFuncEnter();
5658
5659 AssertReturn(aControl, E_FAIL);
5660 AssertReturn(aProgress, E_FAIL);
5661
5662 AutoCaller autoCaller(this);
5663 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5664
5665 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5666
5667 if (!mData->mRegistered)
5668 return setError(E_UNEXPECTED,
5669 tr("The machine '%ls' is not registered"),
5670 mUserData->mName.raw());
5671
5672 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5673
5674 if ( mData->mSession.mState == SessionState_Locked
5675 || mData->mSession.mState == SessionState_Spawning
5676 || mData->mSession.mState == SessionState_Unlocking)
5677 return setError(VBOX_E_INVALID_OBJECT_STATE,
5678 tr("The machine '%ls' is already locked by a session (or being locked or unlocked)"),
5679 mUserData->mName.raw());
5680
5681 /* may not be busy */
5682 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5683
5684 /* get the path to the executable */
5685 char szPath[RTPATH_MAX];
5686 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5687 size_t sz = strlen(szPath);
5688 szPath[sz++] = RTPATH_DELIMITER;
5689 szPath[sz] = 0;
5690 char *cmd = szPath + sz;
5691 sz = RTPATH_MAX - sz;
5692
5693 int vrc = VINF_SUCCESS;
5694 RTPROCESS pid = NIL_RTPROCESS;
5695
5696 RTENV env = RTENV_DEFAULT;
5697
5698 if (aEnvironment != NULL && *aEnvironment)
5699 {
5700 char *newEnvStr = NULL;
5701
5702 do
5703 {
5704 /* clone the current environment */
5705 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5706 AssertRCBreakStmt(vrc2, vrc = vrc2);
5707
5708 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5709 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5710
5711 /* put new variables to the environment
5712 * (ignore empty variable names here since RTEnv API
5713 * intentionally doesn't do that) */
5714 char *var = newEnvStr;
5715 for (char *p = newEnvStr; *p; ++p)
5716 {
5717 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5718 {
5719 *p = '\0';
5720 if (*var)
5721 {
5722 char *val = strchr(var, '=');
5723 if (val)
5724 {
5725 *val++ = '\0';
5726 vrc2 = RTEnvSetEx(env, var, val);
5727 }
5728 else
5729 vrc2 = RTEnvUnsetEx(env, var);
5730 if (RT_FAILURE(vrc2))
5731 break;
5732 }
5733 var = p + 1;
5734 }
5735 }
5736 if (RT_SUCCESS(vrc2) && *var)
5737 vrc2 = RTEnvPutEx(env, var);
5738
5739 AssertRCBreakStmt(vrc2, vrc = vrc2);
5740 }
5741 while (0);
5742
5743 if (newEnvStr != NULL)
5744 RTStrFree(newEnvStr);
5745 }
5746
5747 Utf8Str strType(aType);
5748
5749 /* Qt is default */
5750#ifdef VBOX_WITH_QTGUI
5751 if (strType == "gui" || strType == "GUI/Qt")
5752 {
5753# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5754 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5755# else
5756 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5757# endif
5758 Assert(sz >= sizeof(VirtualBox_exe));
5759 strcpy(cmd, VirtualBox_exe);
5760
5761 Utf8Str idStr = mData->mUuid.toString();
5762 Utf8Str strName = mUserData->mName;
5763 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5764 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5765 }
5766#else /* !VBOX_WITH_QTGUI */
5767 if (0)
5768 ;
5769#endif /* VBOX_WITH_QTGUI */
5770
5771 else
5772
5773#ifdef VBOX_WITH_VBOXSDL
5774 if (strType == "sdl" || strType == "GUI/SDL")
5775 {
5776 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5777 Assert(sz >= sizeof(VBoxSDL_exe));
5778 strcpy(cmd, VBoxSDL_exe);
5779
5780 Utf8Str idStr = mData->mUuid.toString();
5781 Utf8Str strName = mUserData->mName;
5782 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0 };
5783 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5784 }
5785#else /* !VBOX_WITH_VBOXSDL */
5786 if (0)
5787 ;
5788#endif /* !VBOX_WITH_VBOXSDL */
5789
5790 else
5791
5792#ifdef VBOX_WITH_HEADLESS
5793 if ( strType == "headless"
5794 || strType == "capture"
5795#ifdef VBOX_WITH_VRDP
5796 || strType == "vrdp"
5797#endif
5798 )
5799 {
5800 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
5801 Assert(sz >= sizeof(VBoxHeadless_exe));
5802 strcpy(cmd, VBoxHeadless_exe);
5803
5804 Utf8Str idStr = mData->mUuid.toString();
5805 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
5806 Utf8Str strName = mUserData->mName;
5807 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
5808#ifdef VBOX_WITH_VRDP
5809 if (strType == "headless")
5810 {
5811 unsigned pos = RT_ELEMENTS(args) - 3;
5812 args[pos++] = "--vrdp";
5813 args[pos] = "off";
5814 }
5815#endif
5816 if (strType == "capture")
5817 {
5818 unsigned pos = RT_ELEMENTS(args) - 3;
5819 args[pos] = "--capture";
5820 }
5821 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5822 }
5823#else /* !VBOX_WITH_HEADLESS */
5824 if (0)
5825 ;
5826#endif /* !VBOX_WITH_HEADLESS */
5827 else
5828 {
5829 RTEnvDestroy(env);
5830 return setError(E_INVALIDARG,
5831 tr("Invalid session type: '%s'"),
5832 strType.c_str());
5833 }
5834
5835 RTEnvDestroy(env);
5836
5837 if (RT_FAILURE(vrc))
5838 return setError(VBOX_E_IPRT_ERROR,
5839 tr("Could not launch a process for the machine '%ls' (%Rrc)"),
5840 mUserData->mName.raw(), vrc);
5841
5842 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
5843
5844 /*
5845 * Note that we don't leave the lock here before calling the client,
5846 * because it doesn't need to call us back if called with a NULL argument.
5847 * Leaving the lock herer is dangerous because we didn't prepare the
5848 * launch data yet, but the client we've just started may happen to be
5849 * too fast and call openSession() that will fail (because of PID, etc.),
5850 * so that the Machine will never get out of the Spawning session state.
5851 */
5852
5853 /* inform the session that it will be a remote one */
5854 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
5855 HRESULT rc = aControl->AssignMachine(NULL);
5856 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
5857
5858 if (FAILED(rc))
5859 {
5860 /* restore the session state */
5861 mData->mSession.mState = SessionState_Unlocked;
5862 /* The failure may occur w/o any error info (from RPC), so provide one */
5863 return setError(VBOX_E_VM_ERROR,
5864 tr("Failed to assign the machine to the session (%Rrc)"), rc);
5865 }
5866
5867 /* attach launch data to the machine */
5868 Assert(mData->mSession.mPid == NIL_RTPROCESS);
5869 mData->mSession.mRemoteControls.push_back (aControl);
5870 mData->mSession.mProgress = aProgress;
5871 mData->mSession.mPid = pid;
5872 mData->mSession.mState = SessionState_Spawning;
5873 mData->mSession.mType = strType;
5874
5875 LogFlowThisFuncLeave();
5876 return S_OK;
5877}
5878
5879/**
5880 * Returns @c true if the given machine has an open direct session and returns
5881 * the session machine instance and additional session data (on some platforms)
5882 * if so.
5883 *
5884 * Note that when the method returns @c false, the arguments remain unchanged.
5885 *
5886 * @param aMachine Session machine object.
5887 * @param aControl Direct session control object (optional).
5888 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
5889 *
5890 * @note locks this object for reading.
5891 */
5892#if defined(RT_OS_WINDOWS)
5893bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5894 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5895 HANDLE *aIPCSem /*= NULL*/,
5896 bool aAllowClosing /*= false*/)
5897#elif defined(RT_OS_OS2)
5898bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5899 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5900 HMTX *aIPCSem /*= NULL*/,
5901 bool aAllowClosing /*= false*/)
5902#else
5903bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5904 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5905 bool aAllowClosing /*= false*/)
5906#endif
5907{
5908 AutoLimitedCaller autoCaller(this);
5909 AssertComRCReturn(autoCaller.rc(), false);
5910
5911 /* just return false for inaccessible machines */
5912 if (autoCaller.state() != Ready)
5913 return false;
5914
5915 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5916
5917 if ( mData->mSession.mState == SessionState_Locked
5918 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
5919 )
5920 {
5921 AssertReturn(!mData->mSession.mMachine.isNull(), false);
5922
5923 aMachine = mData->mSession.mMachine;
5924
5925 if (aControl != NULL)
5926 *aControl = mData->mSession.mDirectControl;
5927
5928#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5929 /* Additional session data */
5930 if (aIPCSem != NULL)
5931 *aIPCSem = aMachine->mIPCSem;
5932#endif
5933 return true;
5934 }
5935
5936 return false;
5937}
5938
5939/**
5940 * Returns @c true if the given machine has an spawning direct session and
5941 * returns and additional session data (on some platforms) if so.
5942 *
5943 * Note that when the method returns @c false, the arguments remain unchanged.
5944 *
5945 * @param aPID PID of the spawned direct session process.
5946 *
5947 * @note locks this object for reading.
5948 */
5949#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5950bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
5951#else
5952bool Machine::isSessionSpawning()
5953#endif
5954{
5955 AutoLimitedCaller autoCaller(this);
5956 AssertComRCReturn(autoCaller.rc(), false);
5957
5958 /* just return false for inaccessible machines */
5959 if (autoCaller.state() != Ready)
5960 return false;
5961
5962 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5963
5964 if (mData->mSession.mState == SessionState_Spawning)
5965 {
5966#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5967 /* Additional session data */
5968 if (aPID != NULL)
5969 {
5970 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
5971 *aPID = mData->mSession.mPid;
5972 }
5973#endif
5974 return true;
5975 }
5976
5977 return false;
5978}
5979
5980/**
5981 * Called from the client watcher thread to check for unexpected client process
5982 * death during Session_Spawning state (e.g. before it successfully opened a
5983 * direct session).
5984 *
5985 * On Win32 and on OS/2, this method is called only when we've got the
5986 * direct client's process termination notification, so it always returns @c
5987 * true.
5988 *
5989 * On other platforms, this method returns @c true if the client process is
5990 * terminated and @c false if it's still alive.
5991 *
5992 * @note Locks this object for writing.
5993 */
5994bool Machine::checkForSpawnFailure()
5995{
5996 AutoCaller autoCaller(this);
5997 if (!autoCaller.isOk())
5998 {
5999 /* nothing to do */
6000 LogFlowThisFunc(("Already uninitialized!\n"));
6001 return true;
6002 }
6003
6004 /* VirtualBox::addProcessToReap() needs a write lock */
6005 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6006
6007 if (mData->mSession.mState != SessionState_Spawning)
6008 {
6009 /* nothing to do */
6010 LogFlowThisFunc(("Not spawning any more!\n"));
6011 return true;
6012 }
6013
6014 HRESULT rc = S_OK;
6015
6016#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6017
6018 /* the process was already unexpectedly terminated, we just need to set an
6019 * error and finalize session spawning */
6020 rc = setError(E_FAIL,
6021 tr("The virtual machine '%ls' has terminated unexpectedly during startup"),
6022 getName().raw());
6023#else
6024
6025 /* PID not yet initialized, skip check. */
6026 if (mData->mSession.mPid == NIL_RTPROCESS)
6027 return false;
6028
6029 RTPROCSTATUS status;
6030 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6031 &status);
6032
6033 if (vrc != VERR_PROCESS_RUNNING)
6034 {
6035 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6036 rc = setError(E_FAIL,
6037 tr("The virtual machine '%ls' has terminated unexpectedly during startup with exit code %d"),
6038 getName().raw(), status.iStatus);
6039 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6040 rc = setError(E_FAIL,
6041 tr("The virtual machine '%ls' has terminated unexpectedly during startup because of signal %d"),
6042 getName().raw(), status.iStatus);
6043 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6044 rc = setError(E_FAIL,
6045 tr("The virtual machine '%ls' has terminated abnormally"),
6046 getName().raw(), status.iStatus);
6047 else
6048 rc = setError(E_FAIL,
6049 tr("The virtual machine '%ls' has terminated unexpectedly during startup (%Rrc)"),
6050 getName().raw(), rc);
6051 }
6052
6053#endif
6054
6055 if (FAILED(rc))
6056 {
6057 /* Close the remote session, remove the remote control from the list
6058 * and reset session state to Closed (@note keep the code in sync with
6059 * the relevant part in checkForSpawnFailure()). */
6060
6061 Assert(mData->mSession.mRemoteControls.size() == 1);
6062 if (mData->mSession.mRemoteControls.size() == 1)
6063 {
6064 ErrorInfoKeeper eik;
6065 mData->mSession.mRemoteControls.front()->Uninitialize();
6066 }
6067
6068 mData->mSession.mRemoteControls.clear();
6069 mData->mSession.mState = SessionState_Unlocked;
6070
6071 /* finalize the progress after setting the state */
6072 if (!mData->mSession.mProgress.isNull())
6073 {
6074 mData->mSession.mProgress->notifyComplete(rc);
6075 mData->mSession.mProgress.setNull();
6076 }
6077
6078 mParent->addProcessToReap(mData->mSession.mPid);
6079 mData->mSession.mPid = NIL_RTPROCESS;
6080
6081 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6082 return true;
6083 }
6084
6085 return false;
6086}
6087
6088/**
6089 * Checks whether the machine can be registered. If so, commits and saves
6090 * all settings.
6091 *
6092 * @note Must be called from mParent's write lock. Locks this object and
6093 * children for writing.
6094 */
6095HRESULT Machine::prepareRegister()
6096{
6097 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6098
6099 AutoLimitedCaller autoCaller(this);
6100 AssertComRCReturnRC(autoCaller.rc());
6101
6102 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6103
6104 /* wait for state dependants to drop to zero */
6105 ensureNoStateDependencies();
6106
6107 if (!mData->mAccessible)
6108 return setError(VBOX_E_INVALID_OBJECT_STATE,
6109 tr("The machine '%ls' with UUID {%s} is inaccessible and cannot be registered"),
6110 mUserData->mName.raw(),
6111 mData->mUuid.toString().raw());
6112
6113 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6114
6115 if (mData->mRegistered)
6116 return setError(VBOX_E_INVALID_OBJECT_STATE,
6117 tr("The machine '%ls' with UUID {%s} is already registered"),
6118 mUserData->mName.raw(),
6119 mData->mUuid.toString().raw());
6120
6121 HRESULT rc = S_OK;
6122
6123 // Ensure the settings are saved. If we are going to be registered and
6124 // no config file exists yet, create it by calling saveSettings() too.
6125 if ( (mData->flModifications)
6126 || (!mData->pMachineConfigFile->fileExists())
6127 )
6128 {
6129 rc = saveSettings(NULL);
6130 // no need to check whether VirtualBox.xml needs saving too since
6131 // we can't have a machine XML file rename pending
6132 if (FAILED(rc)) return rc;
6133 }
6134
6135 /* more config checking goes here */
6136
6137 if (SUCCEEDED(rc))
6138 {
6139 /* we may have had implicit modifications we want to fix on success */
6140 commit();
6141
6142 mData->mRegistered = true;
6143 }
6144 else
6145 {
6146 /* we may have had implicit modifications we want to cancel on failure*/
6147 rollback(false /* aNotify */);
6148 }
6149
6150 return rc;
6151}
6152
6153/**
6154 * Increases the number of objects dependent on the machine state or on the
6155 * registered state. Guarantees that these two states will not change at least
6156 * until #releaseStateDependency() is called.
6157 *
6158 * Depending on the @a aDepType value, additional state checks may be made.
6159 * These checks will set extended error info on failure. See
6160 * #checkStateDependency() for more info.
6161 *
6162 * If this method returns a failure, the dependency is not added and the caller
6163 * is not allowed to rely on any particular machine state or registration state
6164 * value and may return the failed result code to the upper level.
6165 *
6166 * @param aDepType Dependency type to add.
6167 * @param aState Current machine state (NULL if not interested).
6168 * @param aRegistered Current registered state (NULL if not interested).
6169 *
6170 * @note Locks this object for writing.
6171 */
6172HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6173 MachineState_T *aState /* = NULL */,
6174 BOOL *aRegistered /* = NULL */)
6175{
6176 AutoCaller autoCaller(this);
6177 AssertComRCReturnRC(autoCaller.rc());
6178
6179 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6180
6181 HRESULT rc = checkStateDependency(aDepType);
6182 if (FAILED(rc)) return rc;
6183
6184 {
6185 if (mData->mMachineStateChangePending != 0)
6186 {
6187 /* ensureNoStateDependencies() is waiting for state dependencies to
6188 * drop to zero so don't add more. It may make sense to wait a bit
6189 * and retry before reporting an error (since the pending state
6190 * transition should be really quick) but let's just assert for
6191 * now to see if it ever happens on practice. */
6192
6193 AssertFailed();
6194
6195 return setError(E_ACCESSDENIED,
6196 tr("Machine state change is in progress. Please retry the operation later."));
6197 }
6198
6199 ++mData->mMachineStateDeps;
6200 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6201 }
6202
6203 if (aState)
6204 *aState = mData->mMachineState;
6205 if (aRegistered)
6206 *aRegistered = mData->mRegistered;
6207
6208 return S_OK;
6209}
6210
6211/**
6212 * Decreases the number of objects dependent on the machine state.
6213 * Must always complete the #addStateDependency() call after the state
6214 * dependency is no more necessary.
6215 */
6216void Machine::releaseStateDependency()
6217{
6218 AutoCaller autoCaller(this);
6219 AssertComRCReturnVoid(autoCaller.rc());
6220
6221 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6222
6223 /* releaseStateDependency() w/o addStateDependency()? */
6224 AssertReturnVoid(mData->mMachineStateDeps != 0);
6225 -- mData->mMachineStateDeps;
6226
6227 if (mData->mMachineStateDeps == 0)
6228 {
6229 /* inform ensureNoStateDependencies() that there are no more deps */
6230 if (mData->mMachineStateChangePending != 0)
6231 {
6232 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6233 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6234 }
6235 }
6236}
6237
6238// protected methods
6239/////////////////////////////////////////////////////////////////////////////
6240
6241/**
6242 * Performs machine state checks based on the @a aDepType value. If a check
6243 * fails, this method will set extended error info, otherwise it will return
6244 * S_OK. It is supposed, that on failure, the caller will immedieately return
6245 * the return value of this method to the upper level.
6246 *
6247 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6248 *
6249 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6250 * current state of this machine object allows to change settings of the
6251 * machine (i.e. the machine is not registered, or registered but not running
6252 * and not saved). It is useful to call this method from Machine setters
6253 * before performing any change.
6254 *
6255 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6256 * as for MutableStateDep except that if the machine is saved, S_OK is also
6257 * returned. This is useful in setters which allow changing machine
6258 * properties when it is in the saved state.
6259 *
6260 * @param aDepType Dependency type to check.
6261 *
6262 * @note Non Machine based classes should use #addStateDependency() and
6263 * #releaseStateDependency() methods or the smart AutoStateDependency
6264 * template.
6265 *
6266 * @note This method must be called from under this object's read or write
6267 * lock.
6268 */
6269HRESULT Machine::checkStateDependency(StateDependency aDepType)
6270{
6271 switch (aDepType)
6272 {
6273 case AnyStateDep:
6274 {
6275 break;
6276 }
6277 case MutableStateDep:
6278 {
6279 if ( mData->mRegistered
6280 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6281 || ( mData->mMachineState != MachineState_Paused
6282 && mData->mMachineState != MachineState_Running
6283 && mData->mMachineState != MachineState_Aborted
6284 && mData->mMachineState != MachineState_Teleported
6285 && mData->mMachineState != MachineState_PoweredOff
6286 )
6287 )
6288 )
6289 return setError(VBOX_E_INVALID_VM_STATE,
6290 tr("The machine is not mutable (state is %s)"),
6291 Global::stringifyMachineState(mData->mMachineState));
6292 break;
6293 }
6294 case MutableOrSavedStateDep:
6295 {
6296 if ( mData->mRegistered
6297 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6298 || ( mData->mMachineState != MachineState_Paused
6299 && mData->mMachineState != MachineState_Running
6300 && mData->mMachineState != MachineState_Aborted
6301 && mData->mMachineState != MachineState_Teleported
6302 && mData->mMachineState != MachineState_Saved
6303 && mData->mMachineState != MachineState_PoweredOff
6304 )
6305 )
6306 )
6307 return setError(VBOX_E_INVALID_VM_STATE,
6308 tr("The machine is not mutable (state is %s)"),
6309 Global::stringifyMachineState(mData->mMachineState));
6310 break;
6311 }
6312 }
6313
6314 return S_OK;
6315}
6316
6317/**
6318 * Helper to initialize all associated child objects and allocate data
6319 * structures.
6320 *
6321 * This method must be called as a part of the object's initialization procedure
6322 * (usually done in the #init() method).
6323 *
6324 * @note Must be called only from #init() or from #registeredInit().
6325 */
6326HRESULT Machine::initDataAndChildObjects()
6327{
6328 AutoCaller autoCaller(this);
6329 AssertComRCReturnRC(autoCaller.rc());
6330 AssertComRCReturn(autoCaller.state() == InInit ||
6331 autoCaller.state() == Limited, E_FAIL);
6332
6333 AssertReturn(!mData->mAccessible, E_FAIL);
6334
6335 /* allocate data structures */
6336 mSSData.allocate();
6337 mUserData.allocate();
6338 mHWData.allocate();
6339 mMediaData.allocate();
6340 mStorageControllers.allocate();
6341
6342 /* initialize mOSTypeId */
6343 mUserData->mOSTypeId = mParent->getUnknownOSType()->id();
6344
6345 /* create associated BIOS settings object */
6346 unconst(mBIOSSettings).createObject();
6347 mBIOSSettings->init(this);
6348
6349#ifdef VBOX_WITH_VRDP
6350 /* create an associated VRDPServer object (default is disabled) */
6351 unconst(mVRDPServer).createObject();
6352 mVRDPServer->init(this);
6353#endif
6354
6355 /* create associated serial port objects */
6356 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6357 {
6358 unconst(mSerialPorts[slot]).createObject();
6359 mSerialPorts[slot]->init(this, slot);
6360 }
6361
6362 /* create associated parallel port objects */
6363 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6364 {
6365 unconst(mParallelPorts[slot]).createObject();
6366 mParallelPorts[slot]->init(this, slot);
6367 }
6368
6369 /* create the audio adapter object (always present, default is disabled) */
6370 unconst(mAudioAdapter).createObject();
6371 mAudioAdapter->init(this);
6372
6373 /* create the USB controller object (always present, default is disabled) */
6374 unconst(mUSBController).createObject();
6375 mUSBController->init(this);
6376
6377 /* create associated network adapter objects */
6378 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6379 {
6380 unconst(mNetworkAdapters[slot]).createObject();
6381 mNetworkAdapters[slot]->init(this, slot);
6382 }
6383
6384 return S_OK;
6385}
6386
6387/**
6388 * Helper to uninitialize all associated child objects and to free all data
6389 * structures.
6390 *
6391 * This method must be called as a part of the object's uninitialization
6392 * procedure (usually done in the #uninit() method).
6393 *
6394 * @note Must be called only from #uninit() or from #registeredInit().
6395 */
6396void Machine::uninitDataAndChildObjects()
6397{
6398 AutoCaller autoCaller(this);
6399 AssertComRCReturnVoid(autoCaller.rc());
6400 AssertComRCReturnVoid( autoCaller.state() == InUninit
6401 || autoCaller.state() == Limited);
6402
6403 /* uninit all children using addDependentChild()/removeDependentChild()
6404 * in their init()/uninit() methods */
6405 uninitDependentChildren();
6406
6407 /* tell all our other child objects we've been uninitialized */
6408
6409 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6410 {
6411 if (mNetworkAdapters[slot])
6412 {
6413 mNetworkAdapters[slot]->uninit();
6414 unconst(mNetworkAdapters[slot]).setNull();
6415 }
6416 }
6417
6418 if (mUSBController)
6419 {
6420 mUSBController->uninit();
6421 unconst(mUSBController).setNull();
6422 }
6423
6424 if (mAudioAdapter)
6425 {
6426 mAudioAdapter->uninit();
6427 unconst(mAudioAdapter).setNull();
6428 }
6429
6430 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6431 {
6432 if (mParallelPorts[slot])
6433 {
6434 mParallelPorts[slot]->uninit();
6435 unconst(mParallelPorts[slot]).setNull();
6436 }
6437 }
6438
6439 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6440 {
6441 if (mSerialPorts[slot])
6442 {
6443 mSerialPorts[slot]->uninit();
6444 unconst(mSerialPorts[slot]).setNull();
6445 }
6446 }
6447
6448#ifdef VBOX_WITH_VRDP
6449 if (mVRDPServer)
6450 {
6451 mVRDPServer->uninit();
6452 unconst(mVRDPServer).setNull();
6453 }
6454#endif
6455
6456 if (mBIOSSettings)
6457 {
6458 mBIOSSettings->uninit();
6459 unconst(mBIOSSettings).setNull();
6460 }
6461
6462 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6463 * instance is uninitialized; SessionMachine instances refer to real
6464 * Machine hard disks). This is necessary for a clean re-initialization of
6465 * the VM after successfully re-checking the accessibility state. Note
6466 * that in case of normal Machine or SnapshotMachine uninitialization (as
6467 * a result of unregistering or deleting the snapshot), outdated hard
6468 * disk attachments will already be uninitialized and deleted, so this
6469 * code will not affect them. */
6470 if ( !!mMediaData
6471 && (!isSessionMachine())
6472 )
6473 {
6474 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6475 it != mMediaData->mAttachments.end();
6476 ++it)
6477 {
6478 ComObjPtr<Medium> hd = (*it)->getMedium();
6479 if (hd.isNull())
6480 continue;
6481 HRESULT rc = hd->detachFrom(mData->mUuid, getSnapshotId());
6482 AssertComRC(rc);
6483 }
6484 }
6485
6486 if (!isSessionMachine() && !isSnapshotMachine())
6487 {
6488 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6489 if (mData->mFirstSnapshot)
6490 {
6491 // snapshots tree is protected by media write lock; strictly
6492 // this isn't necessary here since we're deleting the entire
6493 // machine, but otherwise we assert in Snapshot::uninit()
6494 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6495 mData->mFirstSnapshot->uninit();
6496 mData->mFirstSnapshot.setNull();
6497 }
6498
6499 mData->mCurrentSnapshot.setNull();
6500 }
6501
6502 /* free data structures (the essential mData structure is not freed here
6503 * since it may be still in use) */
6504 mMediaData.free();
6505 mStorageControllers.free();
6506 mHWData.free();
6507 mUserData.free();
6508 mSSData.free();
6509}
6510
6511/**
6512 * Returns a pointer to the Machine object for this machine that acts like a
6513 * parent for complex machine data objects such as shared folders, etc.
6514 *
6515 * For primary Machine objects and for SnapshotMachine objects, returns this
6516 * object's pointer itself. For SessoinMachine objects, returns the peer
6517 * (primary) machine pointer.
6518 */
6519Machine* Machine::getMachine()
6520{
6521 if (isSessionMachine())
6522 return (Machine*)mPeer;
6523 return this;
6524}
6525
6526/**
6527 * Makes sure that there are no machine state dependants. If necessary, waits
6528 * for the number of dependants to drop to zero.
6529 *
6530 * Make sure this method is called from under this object's write lock to
6531 * guarantee that no new dependants may be added when this method returns
6532 * control to the caller.
6533 *
6534 * @note Locks this object for writing. The lock will be released while waiting
6535 * (if necessary).
6536 *
6537 * @warning To be used only in methods that change the machine state!
6538 */
6539void Machine::ensureNoStateDependencies()
6540{
6541 AssertReturnVoid(isWriteLockOnCurrentThread());
6542
6543 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6544
6545 /* Wait for all state dependants if necessary */
6546 if (mData->mMachineStateDeps != 0)
6547 {
6548 /* lazy semaphore creation */
6549 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6550 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6551
6552 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6553 mData->mMachineStateDeps));
6554
6555 ++mData->mMachineStateChangePending;
6556
6557 /* reset the semaphore before waiting, the last dependant will signal
6558 * it */
6559 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6560
6561 alock.leave();
6562
6563 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6564
6565 alock.enter();
6566
6567 -- mData->mMachineStateChangePending;
6568 }
6569}
6570
6571/**
6572 * Changes the machine state and informs callbacks.
6573 *
6574 * This method is not intended to fail so it either returns S_OK or asserts (and
6575 * returns a failure).
6576 *
6577 * @note Locks this object for writing.
6578 */
6579HRESULT Machine::setMachineState(MachineState_T aMachineState)
6580{
6581 LogFlowThisFuncEnter();
6582 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6583
6584 AutoCaller autoCaller(this);
6585 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6586
6587 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6588
6589 /* wait for state dependants to drop to zero */
6590 ensureNoStateDependencies();
6591
6592 if (mData->mMachineState != aMachineState)
6593 {
6594 mData->mMachineState = aMachineState;
6595
6596 RTTimeNow(&mData->mLastStateChange);
6597
6598 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6599 }
6600
6601 LogFlowThisFuncLeave();
6602 return S_OK;
6603}
6604
6605/**
6606 * Searches for a shared folder with the given logical name
6607 * in the collection of shared folders.
6608 *
6609 * @param aName logical name of the shared folder
6610 * @param aSharedFolder where to return the found object
6611 * @param aSetError whether to set the error info if the folder is
6612 * not found
6613 * @return
6614 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6615 *
6616 * @note
6617 * must be called from under the object's lock!
6618 */
6619HRESULT Machine::findSharedFolder(CBSTR aName,
6620 ComObjPtr<SharedFolder> &aSharedFolder,
6621 bool aSetError /* = false */)
6622{
6623 bool found = false;
6624 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6625 !found && it != mHWData->mSharedFolders.end();
6626 ++it)
6627 {
6628 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6629 found = (*it)->getName() == aName;
6630 if (found)
6631 aSharedFolder = *it;
6632 }
6633
6634 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6635
6636 if (aSetError && !found)
6637 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6638
6639 return rc;
6640}
6641
6642/**
6643 * Initializes all machine instance data from the given settings structures
6644 * from XML. The exception is the machine UUID which needs special handling
6645 * depending on the caller's use case, so the caller needs to set that herself.
6646 *
6647 * @param config
6648 * @param fAllowStorage
6649 */
6650HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config)
6651{
6652 /* name (required) */
6653 mUserData->mName = config.strName;
6654
6655 /* nameSync (optional, default is true) */
6656 mUserData->mNameSync = config.fNameSync;
6657
6658 mUserData->mDescription = config.strDescription;
6659
6660 // guest OS type
6661 mUserData->mOSTypeId = config.strOsType;
6662 /* look up the object by Id to check it is valid */
6663 ComPtr<IGuestOSType> guestOSType;
6664 HRESULT rc = mParent->GetGuestOSType(mUserData->mOSTypeId,
6665 guestOSType.asOutParam());
6666 if (FAILED(rc)) return rc;
6667
6668 // stateFile (optional)
6669 if (config.strStateFile.isEmpty())
6670 mSSData->mStateFilePath.setNull();
6671 else
6672 {
6673 Utf8Str stateFilePathFull(config.strStateFile);
6674 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6675 if (RT_FAILURE(vrc))
6676 return setError(E_FAIL,
6677 tr("Invalid saved state file path '%s' (%Rrc)"),
6678 config.strStateFile.raw(),
6679 vrc);
6680 mSSData->mStateFilePath = stateFilePathFull;
6681 }
6682
6683 /* snapshotFolder (optional) */
6684 rc = COMSETTER(SnapshotFolder)(Bstr(config.strSnapshotFolder));
6685 if (FAILED(rc)) return rc;
6686
6687 /* currentStateModified (optional, default is true) */
6688 mData->mCurrentStateModified = config.fCurrentStateModified;
6689
6690 mData->mLastStateChange = config.timeLastStateChange;
6691
6692 /* teleportation */
6693 mUserData->mTeleporterEnabled = config.fTeleporterEnabled;
6694 mUserData->mTeleporterPort = config.uTeleporterPort;
6695 mUserData->mTeleporterAddress = config.strTeleporterAddress;
6696 mUserData->mTeleporterPassword = config.strTeleporterPassword;
6697
6698 /* RTC */
6699 mUserData->mRTCUseUTC = config.fRTCUseUTC;
6700
6701 /*
6702 * note: all mUserData members must be assigned prior this point because
6703 * we need to commit changes in order to let mUserData be shared by all
6704 * snapshot machine instances.
6705 */
6706 mUserData.commitCopy();
6707
6708 /* Snapshot node (optional) */
6709 size_t cRootSnapshots;
6710 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6711 {
6712 // there must be only one root snapshot
6713 Assert(cRootSnapshots == 1);
6714
6715 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6716
6717 rc = loadSnapshot(snap,
6718 config.uuidCurrentSnapshot,
6719 NULL); // no parent == first snapshot
6720 if (FAILED(rc)) return rc;
6721 }
6722
6723 /* Hardware node (required) */
6724 rc = loadHardware(config.hardwareMachine);
6725 if (FAILED(rc)) return rc;
6726
6727 /* Load storage controllers */
6728 rc = loadStorageControllers(config.storageMachine);
6729 if (FAILED(rc)) return rc;
6730
6731 /*
6732 * NOTE: the assignment below must be the last thing to do,
6733 * otherwise it will be not possible to change the settings
6734 * somewehere in the code above because all setters will be
6735 * blocked by checkStateDependency(MutableStateDep).
6736 */
6737
6738 /* set the machine state to Aborted or Saved when appropriate */
6739 if (config.fAborted)
6740 {
6741 Assert(!mSSData->mStateFilePath.isEmpty());
6742 mSSData->mStateFilePath.setNull();
6743
6744 /* no need to use setMachineState() during init() */
6745 mData->mMachineState = MachineState_Aborted;
6746 }
6747 else if (!mSSData->mStateFilePath.isEmpty())
6748 {
6749 /* no need to use setMachineState() during init() */
6750 mData->mMachineState = MachineState_Saved;
6751 }
6752
6753 // after loading settings, we are no longer different from the XML on disk
6754 mData->flModifications = 0;
6755
6756 return S_OK;
6757}
6758
6759/**
6760 * Recursively loads all snapshots starting from the given.
6761 *
6762 * @param aNode <Snapshot> node.
6763 * @param aCurSnapshotId Current snapshot ID from the settings file.
6764 * @param aParentSnapshot Parent snapshot.
6765 */
6766HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6767 const Guid &aCurSnapshotId,
6768 Snapshot *aParentSnapshot)
6769{
6770 AssertReturn(!isSnapshotMachine(), E_FAIL);
6771 AssertReturn(!isSessionMachine(), E_FAIL);
6772
6773 HRESULT rc = S_OK;
6774
6775 Utf8Str strStateFile;
6776 if (!data.strStateFile.isEmpty())
6777 {
6778 /* optional */
6779 strStateFile = data.strStateFile;
6780 int vrc = calculateFullPath(strStateFile, strStateFile);
6781 if (RT_FAILURE(vrc))
6782 return setError(E_FAIL,
6783 tr("Invalid saved state file path '%s' (%Rrc)"),
6784 strStateFile.raw(),
6785 vrc);
6786 }
6787
6788 /* create a snapshot machine object */
6789 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6790 pSnapshotMachine.createObject();
6791 rc = pSnapshotMachine->init(this,
6792 data.hardware,
6793 data.storage,
6794 data.uuid,
6795 strStateFile);
6796 if (FAILED(rc)) return rc;
6797
6798 /* create a snapshot object */
6799 ComObjPtr<Snapshot> pSnapshot;
6800 pSnapshot.createObject();
6801 /* initialize the snapshot */
6802 rc = pSnapshot->init(mParent, // VirtualBox object
6803 data.uuid,
6804 data.strName,
6805 data.strDescription,
6806 data.timestamp,
6807 pSnapshotMachine,
6808 aParentSnapshot);
6809 if (FAILED(rc)) return rc;
6810
6811 /* memorize the first snapshot if necessary */
6812 if (!mData->mFirstSnapshot)
6813 mData->mFirstSnapshot = pSnapshot;
6814
6815 /* memorize the current snapshot when appropriate */
6816 if ( !mData->mCurrentSnapshot
6817 && pSnapshot->getId() == aCurSnapshotId
6818 )
6819 mData->mCurrentSnapshot = pSnapshot;
6820
6821 // now create the children
6822 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
6823 it != data.llChildSnapshots.end();
6824 ++it)
6825 {
6826 const settings::Snapshot &childData = *it;
6827 // recurse
6828 rc = loadSnapshot(childData,
6829 aCurSnapshotId,
6830 pSnapshot); // parent = the one we created above
6831 if (FAILED(rc)) return rc;
6832 }
6833
6834 return rc;
6835}
6836
6837/**
6838 * @param aNode <Hardware> node.
6839 */
6840HRESULT Machine::loadHardware(const settings::Hardware &data)
6841{
6842 AssertReturn(!isSessionMachine(), E_FAIL);
6843
6844 HRESULT rc = S_OK;
6845
6846 try
6847 {
6848 /* The hardware version attribute (optional). */
6849 mHWData->mHWVersion = data.strVersion;
6850 mHWData->mHardwareUUID = data.uuid;
6851
6852 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
6853 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
6854 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
6855 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
6856 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
6857 mHWData->mPAEEnabled = data.fPAE;
6858 mHWData->mSyntheticCpu = data.fSyntheticCpu;
6859
6860 mHWData->mCPUCount = data.cCPUs;
6861 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
6862
6863 // cpu
6864 if (mHWData->mCPUHotPlugEnabled)
6865 {
6866 for (settings::CpuList::const_iterator it = data.llCpus.begin();
6867 it != data.llCpus.end();
6868 ++it)
6869 {
6870 const settings::Cpu &cpu = *it;
6871
6872 mHWData->mCPUAttached[cpu.ulId] = true;
6873 }
6874 }
6875
6876 // cpuid leafs
6877 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
6878 it != data.llCpuIdLeafs.end();
6879 ++it)
6880 {
6881 const settings::CpuIdLeaf &leaf = *it;
6882
6883 switch (leaf.ulId)
6884 {
6885 case 0x0:
6886 case 0x1:
6887 case 0x2:
6888 case 0x3:
6889 case 0x4:
6890 case 0x5:
6891 case 0x6:
6892 case 0x7:
6893 case 0x8:
6894 case 0x9:
6895 case 0xA:
6896 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
6897 break;
6898
6899 case 0x80000000:
6900 case 0x80000001:
6901 case 0x80000002:
6902 case 0x80000003:
6903 case 0x80000004:
6904 case 0x80000005:
6905 case 0x80000006:
6906 case 0x80000007:
6907 case 0x80000008:
6908 case 0x80000009:
6909 case 0x8000000A:
6910 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
6911 break;
6912
6913 default:
6914 /* just ignore */
6915 break;
6916 }
6917 }
6918
6919 mHWData->mMemorySize = data.ulMemorySizeMB;
6920 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
6921
6922 // boot order
6923 for (size_t i = 0;
6924 i < RT_ELEMENTS(mHWData->mBootOrder);
6925 i++)
6926 {
6927 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
6928 if (it == data.mapBootOrder.end())
6929 mHWData->mBootOrder[i] = DeviceType_Null;
6930 else
6931 mHWData->mBootOrder[i] = it->second;
6932 }
6933
6934 mHWData->mVRAMSize = data.ulVRAMSizeMB;
6935 mHWData->mMonitorCount = data.cMonitors;
6936 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
6937 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
6938 mHWData->mFirmwareType = data.firmwareType;
6939 mHWData->mPointingHidType = data.pointingHidType;
6940 mHWData->mKeyboardHidType = data.keyboardHidType;
6941 mHWData->mHpetEnabled = data.fHpetEnabled;
6942
6943#ifdef VBOX_WITH_VRDP
6944 /* RemoteDisplay */
6945 rc = mVRDPServer->loadSettings(data.vrdpSettings);
6946 if (FAILED(rc)) return rc;
6947#endif
6948
6949 /* BIOS */
6950 rc = mBIOSSettings->loadSettings(data.biosSettings);
6951 if (FAILED(rc)) return rc;
6952
6953 /* USB Controller */
6954 rc = mUSBController->loadSettings(data.usbController);
6955 if (FAILED(rc)) return rc;
6956
6957 // network adapters
6958 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
6959 it != data.llNetworkAdapters.end();
6960 ++it)
6961 {
6962 const settings::NetworkAdapter &nic = *it;
6963
6964 /* slot unicity is guaranteed by XML Schema */
6965 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
6966 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
6967 if (FAILED(rc)) return rc;
6968 }
6969
6970 // serial ports
6971 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
6972 it != data.llSerialPorts.end();
6973 ++it)
6974 {
6975 const settings::SerialPort &s = *it;
6976
6977 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
6978 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
6979 if (FAILED(rc)) return rc;
6980 }
6981
6982 // parallel ports (optional)
6983 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
6984 it != data.llParallelPorts.end();
6985 ++it)
6986 {
6987 const settings::ParallelPort &p = *it;
6988
6989 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
6990 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
6991 if (FAILED(rc)) return rc;
6992 }
6993
6994 /* AudioAdapter */
6995 rc = mAudioAdapter->loadSettings(data.audioAdapter);
6996 if (FAILED(rc)) return rc;
6997
6998 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
6999 it != data.llSharedFolders.end();
7000 ++it)
7001 {
7002 const settings::SharedFolder &sf = *it;
7003 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable, sf.fAutoMount);
7004 if (FAILED(rc)) return rc;
7005 }
7006
7007 // Clipboard
7008 mHWData->mClipboardMode = data.clipboardMode;
7009
7010 // guest settings
7011 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7012
7013 // IO settings
7014 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7015 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7016 mHWData->mIoBandwidthMax = data.ioSettings.ulIoBandwidthMax;
7017
7018#ifdef VBOX_WITH_GUEST_PROPS
7019 /* Guest properties (optional) */
7020 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7021 it != data.llGuestProperties.end();
7022 ++it)
7023 {
7024 const settings::GuestProperty &prop = *it;
7025 uint32_t fFlags = guestProp::NILFLAG;
7026 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7027 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7028 mHWData->mGuestProperties.push_back(property);
7029 }
7030
7031 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7032#endif /* VBOX_WITH_GUEST_PROPS defined */
7033 }
7034 catch(std::bad_alloc &)
7035 {
7036 return E_OUTOFMEMORY;
7037 }
7038
7039 AssertComRC(rc);
7040 return rc;
7041}
7042
7043 /**
7044 * @param aNode <StorageControllers> node.
7045 */
7046HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7047 const Guid *aSnapshotId /* = NULL */)
7048{
7049 AssertReturn(!isSessionMachine(), E_FAIL);
7050
7051 HRESULT rc = S_OK;
7052
7053 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7054 it != data.llStorageControllers.end();
7055 ++it)
7056 {
7057 const settings::StorageController &ctlData = *it;
7058
7059 ComObjPtr<StorageController> pCtl;
7060 /* Try to find one with the name first. */
7061 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7062 if (SUCCEEDED(rc))
7063 return setError(VBOX_E_OBJECT_IN_USE,
7064 tr("Storage controller named '%s' already exists"),
7065 ctlData.strName.raw());
7066
7067 pCtl.createObject();
7068 rc = pCtl->init(this,
7069 ctlData.strName,
7070 ctlData.storageBus,
7071 ctlData.ulInstance);
7072 if (FAILED(rc)) return rc;
7073
7074 mStorageControllers->push_back(pCtl);
7075
7076 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7077 if (FAILED(rc)) return rc;
7078
7079 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7080 if (FAILED(rc)) return rc;
7081
7082 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7083 if (FAILED(rc)) return rc;
7084
7085 /* Set IDE emulation settings (only for AHCI controller). */
7086 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7087 {
7088 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7089 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7090 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7091 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7092 )
7093 return rc;
7094 }
7095
7096 /* Load the attached devices now. */
7097 rc = loadStorageDevices(pCtl,
7098 ctlData,
7099 aSnapshotId);
7100 if (FAILED(rc)) return rc;
7101 }
7102
7103 return S_OK;
7104}
7105
7106/**
7107 * @param aNode <HardDiskAttachments> node.
7108 * @param fAllowStorage if false, we produce an error if the config requests media attachments
7109 * (used with importing unregistered machines which cannot have media attachments)
7110 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7111 *
7112 * @note Lock mParent for reading and hard disks for writing before calling.
7113 */
7114HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7115 const settings::StorageController &data,
7116 const Guid *aSnapshotId /*= NULL*/)
7117{
7118 HRESULT rc = S_OK;
7119
7120 /* paranoia: detect duplicate attachments */
7121 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7122 it != data.llAttachedDevices.end();
7123 ++it)
7124 {
7125 for (settings::AttachedDevicesList::const_iterator it2 = it;
7126 it2 != data.llAttachedDevices.end();
7127 ++it2)
7128 {
7129 if (it == it2)
7130 continue;
7131
7132 if ( (*it).lPort == (*it2).lPort
7133 && (*it).lDevice == (*it2).lDevice)
7134 {
7135 return setError(E_FAIL,
7136 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%ls'"),
7137 aStorageController->getName().raw(), (*it).lPort, (*it).lDevice, mUserData->mName.raw());
7138 }
7139 }
7140 }
7141
7142 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7143 it != data.llAttachedDevices.end();
7144 ++it)
7145 {
7146 const settings::AttachedDevice &dev = *it;
7147 ComObjPtr<Medium> medium;
7148
7149 switch (dev.deviceType)
7150 {
7151 case DeviceType_Floppy:
7152 /* find a floppy by UUID */
7153 if (!dev.uuid.isEmpty())
7154 rc = mParent->findFloppyImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7155 /* find a floppy by host device name */
7156 else if (!dev.strHostDriveSrc.isEmpty())
7157 {
7158 SafeIfaceArray<IMedium> drivevec;
7159 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
7160 if (SUCCEEDED(rc))
7161 {
7162 for (size_t i = 0; i < drivevec.size(); ++i)
7163 {
7164 /// @todo eliminate this conversion
7165 ComObjPtr<Medium> med = (Medium *)drivevec[i];
7166 if ( dev.strHostDriveSrc == med->getName()
7167 || dev.strHostDriveSrc == med->getLocation())
7168 {
7169 medium = med;
7170 break;
7171 }
7172 }
7173 }
7174 }
7175 break;
7176
7177 case DeviceType_DVD:
7178 /* find a DVD by UUID */
7179 if (!dev.uuid.isEmpty())
7180 rc = mParent->findDVDImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7181 /* find a DVD by host device name */
7182 else if (!dev.strHostDriveSrc.isEmpty())
7183 {
7184 SafeIfaceArray<IMedium> drivevec;
7185 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
7186 if (SUCCEEDED(rc))
7187 {
7188 for (size_t i = 0; i < drivevec.size(); ++i)
7189 {
7190 Bstr hostDriveSrc(dev.strHostDriveSrc);
7191 /// @todo eliminate this conversion
7192 ComObjPtr<Medium> med = (Medium *)drivevec[i];
7193 if ( hostDriveSrc == med->getName()
7194 || hostDriveSrc == med->getLocation())
7195 {
7196 medium = med;
7197 break;
7198 }
7199 }
7200 }
7201 }
7202 break;
7203
7204 case DeviceType_HardDisk:
7205 {
7206 /* find a hard disk by UUID */
7207 rc = mParent->findHardDisk(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7208 if (FAILED(rc))
7209 {
7210 if (isSnapshotMachine())
7211 {
7212 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7213 // so the user knows that the bad disk is in a snapshot somewhere
7214 com::ErrorInfo info;
7215 return setError(E_FAIL,
7216 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7217 aSnapshotId->raw(),
7218 info.getText().raw());
7219 }
7220 else
7221 return rc;
7222 }
7223
7224 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7225
7226 if (medium->getType() == MediumType_Immutable)
7227 {
7228 if (isSnapshotMachine())
7229 return setError(E_FAIL,
7230 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7231 "of the virtual machine '%ls' ('%s')"),
7232 medium->getLocationFull().raw(),
7233 dev.uuid.raw(),
7234 aSnapshotId->raw(),
7235 mUserData->mName.raw(),
7236 mData->m_strConfigFileFull.raw());
7237
7238 return setError(E_FAIL,
7239 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s')"),
7240 medium->getLocationFull().raw(),
7241 dev.uuid.raw(),
7242 mUserData->mName.raw(),
7243 mData->m_strConfigFileFull.raw());
7244 }
7245
7246 if ( !isSnapshotMachine()
7247 && medium->getChildren().size() != 0
7248 )
7249 return setError(E_FAIL,
7250 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s') "
7251 "because it has %d differencing child hard disks"),
7252 medium->getLocationFull().raw(),
7253 dev.uuid.raw(),
7254 mUserData->mName.raw(),
7255 mData->m_strConfigFileFull.raw(),
7256 medium->getChildren().size());
7257
7258 if (findAttachment(mMediaData->mAttachments,
7259 medium))
7260 return setError(E_FAIL,
7261 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%ls' ('%s')"),
7262 medium->getLocationFull().raw(),
7263 dev.uuid.raw(),
7264 mUserData->mName.raw(),
7265 mData->m_strConfigFileFull.raw());
7266
7267 break;
7268 }
7269
7270 default:
7271 return setError(E_FAIL,
7272 tr("Device with unknown type is attached to the virtual machine '%s' ('%s')"),
7273 medium->getLocationFull().raw(),
7274 mUserData->mName.raw(),
7275 mData->m_strConfigFileFull.raw());
7276 }
7277
7278 if (FAILED(rc))
7279 break;
7280
7281 const Bstr controllerName = aStorageController->getName();
7282 ComObjPtr<MediumAttachment> pAttachment;
7283 pAttachment.createObject();
7284 rc = pAttachment->init(this,
7285 medium,
7286 controllerName,
7287 dev.lPort,
7288 dev.lDevice,
7289 dev.deviceType,
7290 dev.fPassThrough);
7291 if (FAILED(rc)) break;
7292
7293 /* associate the medium with this machine and snapshot */
7294 if (!medium.isNull())
7295 {
7296 if (isSnapshotMachine())
7297 rc = medium->attachTo(mData->mUuid, *aSnapshotId);
7298 else
7299 rc = medium->attachTo(mData->mUuid);
7300 }
7301
7302 if (FAILED(rc))
7303 break;
7304
7305 /* back up mMediaData to let registeredInit() properly rollback on failure
7306 * (= limited accessibility) */
7307 setModified(IsModified_Storage);
7308 mMediaData.backup();
7309 mMediaData->mAttachments.push_back(pAttachment);
7310 }
7311
7312 return rc;
7313}
7314
7315/**
7316 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7317 *
7318 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7319 * @param aSnapshot where to return the found snapshot
7320 * @param aSetError true to set extended error info on failure
7321 */
7322HRESULT Machine::findSnapshot(const Guid &aId,
7323 ComObjPtr<Snapshot> &aSnapshot,
7324 bool aSetError /* = false */)
7325{
7326 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7327
7328 if (!mData->mFirstSnapshot)
7329 {
7330 if (aSetError)
7331 return setError(E_FAIL,
7332 tr("This machine does not have any snapshots"));
7333 return E_FAIL;
7334 }
7335
7336 if (aId.isEmpty())
7337 aSnapshot = mData->mFirstSnapshot;
7338 else
7339 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
7340
7341 if (!aSnapshot)
7342 {
7343 if (aSetError)
7344 return setError(E_FAIL,
7345 tr("Could not find a snapshot with UUID {%s}"),
7346 aId.toString().raw());
7347 return E_FAIL;
7348 }
7349
7350 return S_OK;
7351}
7352
7353/**
7354 * Returns the snapshot with the given name or fails of no such snapshot.
7355 *
7356 * @param aName snapshot name to find
7357 * @param aSnapshot where to return the found snapshot
7358 * @param aSetError true to set extended error info on failure
7359 */
7360HRESULT Machine::findSnapshot(IN_BSTR aName,
7361 ComObjPtr<Snapshot> &aSnapshot,
7362 bool aSetError /* = false */)
7363{
7364 AssertReturn(aName, E_INVALIDARG);
7365
7366 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7367
7368 if (!mData->mFirstSnapshot)
7369 {
7370 if (aSetError)
7371 return setError(VBOX_E_OBJECT_NOT_FOUND,
7372 tr("This machine does not have any snapshots"));
7373 return VBOX_E_OBJECT_NOT_FOUND;
7374 }
7375
7376 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aName);
7377
7378 if (!aSnapshot)
7379 {
7380 if (aSetError)
7381 return setError(VBOX_E_OBJECT_NOT_FOUND,
7382 tr("Could not find a snapshot named '%ls'"), aName);
7383 return VBOX_E_OBJECT_NOT_FOUND;
7384 }
7385
7386 return S_OK;
7387}
7388
7389/**
7390 * Returns a storage controller object with the given name.
7391 *
7392 * @param aName storage controller name to find
7393 * @param aStorageController where to return the found storage controller
7394 * @param aSetError true to set extended error info on failure
7395 */
7396HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7397 ComObjPtr<StorageController> &aStorageController,
7398 bool aSetError /* = false */)
7399{
7400 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7401
7402 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7403 it != mStorageControllers->end();
7404 ++it)
7405 {
7406 if ((*it)->getName() == aName)
7407 {
7408 aStorageController = (*it);
7409 return S_OK;
7410 }
7411 }
7412
7413 if (aSetError)
7414 return setError(VBOX_E_OBJECT_NOT_FOUND,
7415 tr("Could not find a storage controller named '%s'"),
7416 aName.raw());
7417 return VBOX_E_OBJECT_NOT_FOUND;
7418}
7419
7420HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7421 MediaData::AttachmentList &atts)
7422{
7423 AutoCaller autoCaller(this);
7424 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7425
7426 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7427
7428 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7429 it != mMediaData->mAttachments.end();
7430 ++it)
7431 {
7432 const ComObjPtr<MediumAttachment> &pAtt = *it;
7433
7434 // should never happen, but deal with NULL pointers in the list.
7435 AssertStmt(!pAtt.isNull(), continue);
7436
7437 // getControllerName() needs caller+read lock
7438 AutoCaller autoAttCaller(pAtt);
7439 if (FAILED(autoAttCaller.rc()))
7440 {
7441 atts.clear();
7442 return autoAttCaller.rc();
7443 }
7444 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7445
7446 if (pAtt->getControllerName() == aName)
7447 atts.push_back(pAtt);
7448 }
7449
7450 return S_OK;
7451}
7452
7453/**
7454 * Helper for #saveSettings. Cares about renaming the settings directory and
7455 * file if the machine name was changed and about creating a new settings file
7456 * if this is a new machine.
7457 *
7458 * @note Must be never called directly but only from #saveSettings().
7459 */
7460HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7461{
7462 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7463
7464 HRESULT rc = S_OK;
7465
7466 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7467
7468 /* attempt to rename the settings file if machine name is changed */
7469 if ( mUserData->mNameSync
7470 && mUserData.isBackedUp()
7471 && mUserData.backedUpData()->mName != mUserData->mName
7472 )
7473 {
7474 bool dirRenamed = false;
7475 bool fileRenamed = false;
7476
7477 Utf8Str configFile, newConfigFile;
7478 Utf8Str configDir, newConfigDir;
7479
7480 do
7481 {
7482 int vrc = VINF_SUCCESS;
7483
7484 Utf8Str name = mUserData.backedUpData()->mName;
7485 Utf8Str newName = mUserData->mName;
7486
7487 configFile = mData->m_strConfigFileFull;
7488
7489 /* first, rename the directory if it matches the machine name */
7490 configDir = configFile;
7491 configDir.stripFilename();
7492 newConfigDir = configDir;
7493 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7494 {
7495 newConfigDir.stripFilename();
7496 newConfigDir = Utf8StrFmt("%s%c%s",
7497 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
7498 /* new dir and old dir cannot be equal here because of 'if'
7499 * above and because name != newName */
7500 Assert(configDir != newConfigDir);
7501 if (!fSettingsFileIsNew)
7502 {
7503 /* perform real rename only if the machine is not new */
7504 vrc = RTPathRename(configDir.raw(), newConfigDir.raw(), 0);
7505 if (RT_FAILURE(vrc))
7506 {
7507 rc = setError(E_FAIL,
7508 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7509 configDir.raw(),
7510 newConfigDir.raw(),
7511 vrc);
7512 break;
7513 }
7514 dirRenamed = true;
7515 }
7516 }
7517
7518 newConfigFile = Utf8StrFmt("%s%c%s.xml",
7519 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
7520
7521 /* then try to rename the settings file itself */
7522 if (newConfigFile != configFile)
7523 {
7524 /* get the path to old settings file in renamed directory */
7525 configFile = Utf8StrFmt("%s%c%s",
7526 newConfigDir.raw(),
7527 RTPATH_DELIMITER,
7528 RTPathFilename(configFile.c_str()));
7529 if (!fSettingsFileIsNew)
7530 {
7531 /* perform real rename only if the machine is not new */
7532 vrc = RTFileRename(configFile.raw(), newConfigFile.raw(), 0);
7533 if (RT_FAILURE(vrc))
7534 {
7535 rc = setError(E_FAIL,
7536 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7537 configFile.raw(),
7538 newConfigFile.raw(),
7539 vrc);
7540 break;
7541 }
7542 fileRenamed = true;
7543 }
7544 }
7545
7546 /* update m_strConfigFileFull amd mConfigFile */
7547 mData->m_strConfigFileFull = newConfigFile;
7548 // compute the relative path too
7549 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7550
7551 // store the old and new so that VirtualBox::saveSettings() can update
7552 // the media registry
7553 if ( mData->mRegistered
7554 && configDir != newConfigDir)
7555 {
7556 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7557
7558 if (pfNeedsGlobalSaveSettings)
7559 *pfNeedsGlobalSaveSettings = true;
7560 }
7561
7562 /* update the snapshot folder */
7563 Utf8Str path = mUserData->mSnapshotFolderFull;
7564 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7565 {
7566 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
7567 path.raw() + configDir.length());
7568 mUserData->mSnapshotFolderFull = path;
7569 Utf8Str strTemp;
7570 copyPathRelativeToMachine(path, strTemp);
7571 mUserData->mSnapshotFolder = strTemp;
7572 }
7573
7574 /* update the saved state file path */
7575 path = mSSData->mStateFilePath;
7576 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7577 {
7578 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
7579 path.raw() + configDir.length());
7580 mSSData->mStateFilePath = path;
7581 }
7582
7583 /* Update saved state file paths of all online snapshots.
7584 * Note that saveSettings() will recognize name change
7585 * and will save all snapshots in this case. */
7586 if (mData->mFirstSnapshot)
7587 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7588 newConfigDir.c_str());
7589 }
7590 while (0);
7591
7592 if (FAILED(rc))
7593 {
7594 /* silently try to rename everything back */
7595 if (fileRenamed)
7596 RTFileRename(newConfigFile.raw(), configFile.raw(), 0);
7597 if (dirRenamed)
7598 RTPathRename(newConfigDir.raw(), configDir.raw(), 0);
7599 }
7600
7601 if (FAILED(rc)) return rc;
7602 }
7603
7604 if (fSettingsFileIsNew)
7605 {
7606 /* create a virgin config file */
7607 int vrc = VINF_SUCCESS;
7608
7609 /* ensure the settings directory exists */
7610 Utf8Str path(mData->m_strConfigFileFull);
7611 path.stripFilename();
7612 if (!RTDirExists(path.c_str()))
7613 {
7614 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7615 if (RT_FAILURE(vrc))
7616 {
7617 return setError(E_FAIL,
7618 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7619 path.raw(),
7620 vrc);
7621 }
7622 }
7623
7624 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7625 path = Utf8Str(mData->m_strConfigFileFull);
7626 RTFILE f = NIL_RTFILE;
7627 vrc = RTFileOpen(&f, path.c_str(),
7628 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7629 if (RT_FAILURE(vrc))
7630 return setError(E_FAIL,
7631 tr("Could not create the settings file '%s' (%Rrc)"),
7632 path.raw(),
7633 vrc);
7634 RTFileClose(f);
7635 }
7636
7637 return rc;
7638}
7639
7640/**
7641 * Saves and commits machine data, user data and hardware data.
7642 *
7643 * Note that on failure, the data remains uncommitted.
7644 *
7645 * @a aFlags may combine the following flags:
7646 *
7647 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7648 * Used when saving settings after an operation that makes them 100%
7649 * correspond to the settings from the current snapshot.
7650 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7651 * #isReallyModified() returns false. This is necessary for cases when we
7652 * change machine data directly, not through the backup()/commit() mechanism.
7653 * - SaveS_Force: settings will be saved without doing a deep compare of the
7654 * settings structures. This is used when this is called because snapshots
7655 * have changed to avoid the overhead of the deep compare.
7656 *
7657 * @note Must be called from under this object's write lock. Locks children for
7658 * writing.
7659 *
7660 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7661 * initialized to false and that will be set to true by this function if
7662 * the caller must invoke VirtualBox::saveSettings() because the global
7663 * settings have changed. This will happen if a machine rename has been
7664 * saved and the global machine and media registries will therefore need
7665 * updating.
7666 */
7667HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7668 int aFlags /*= 0*/)
7669{
7670 LogFlowThisFuncEnter();
7671
7672 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7673
7674 /* make sure child objects are unable to modify the settings while we are
7675 * saving them */
7676 ensureNoStateDependencies();
7677
7678 AssertReturn(!isSnapshotMachine(),
7679 E_FAIL);
7680
7681 HRESULT rc = S_OK;
7682 bool fNeedsWrite = false;
7683
7684 /* First, prepare to save settings. It will care about renaming the
7685 * settings directory and file if the machine name was changed and about
7686 * creating a new settings file if this is a new machine. */
7687 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7688 if (FAILED(rc)) return rc;
7689
7690 // keep a pointer to the current settings structures
7691 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7692 settings::MachineConfigFile *pNewConfig = NULL;
7693
7694 try
7695 {
7696 // make a fresh one to have everyone write stuff into
7697 pNewConfig = new settings::MachineConfigFile(NULL);
7698 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7699
7700 // now go and copy all the settings data from COM to the settings structures
7701 // (this calles saveSettings() on all the COM objects in the machine)
7702 copyMachineDataToSettings(*pNewConfig);
7703
7704 if (aFlags & SaveS_ResetCurStateModified)
7705 {
7706 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7707 mData->mCurrentStateModified = FALSE;
7708 fNeedsWrite = true; // always, no need to compare
7709 }
7710 else if (aFlags & SaveS_Force)
7711 {
7712 fNeedsWrite = true; // always, no need to compare
7713 }
7714 else
7715 {
7716 if (!mData->mCurrentStateModified)
7717 {
7718 // do a deep compare of the settings that we just saved with the settings
7719 // previously stored in the config file; this invokes MachineConfigFile::operator==
7720 // which does a deep compare of all the settings, which is expensive but less expensive
7721 // than writing out XML in vain
7722 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7723
7724 // could still be modified if any settings changed
7725 mData->mCurrentStateModified = fAnySettingsChanged;
7726
7727 fNeedsWrite = fAnySettingsChanged;
7728 }
7729 else
7730 fNeedsWrite = true;
7731 }
7732
7733 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7734
7735 if (fNeedsWrite)
7736 // now spit it all out!
7737 pNewConfig->write(mData->m_strConfigFileFull);
7738
7739 mData->pMachineConfigFile = pNewConfig;
7740 delete pOldConfig;
7741 commit();
7742
7743 // after saving settings, we are no longer different from the XML on disk
7744 mData->flModifications = 0;
7745 }
7746 catch (HRESULT err)
7747 {
7748 // we assume that error info is set by the thrower
7749 rc = err;
7750
7751 // restore old config
7752 delete pNewConfig;
7753 mData->pMachineConfigFile = pOldConfig;
7754 }
7755 catch (...)
7756 {
7757 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7758 }
7759
7760 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7761 {
7762 /* Fire the data change event, even on failure (since we've already
7763 * committed all data). This is done only for SessionMachines because
7764 * mutable Machine instances are always not registered (i.e. private
7765 * to the client process that creates them) and thus don't need to
7766 * inform callbacks. */
7767 if (isSessionMachine())
7768 mParent->onMachineDataChange(mData->mUuid);
7769 }
7770
7771 LogFlowThisFunc(("rc=%08X\n", rc));
7772 LogFlowThisFuncLeave();
7773 return rc;
7774}
7775
7776/**
7777 * Implementation for saving the machine settings into the given
7778 * settings::MachineConfigFile instance. This copies machine extradata
7779 * from the previous machine config file in the instance data, if any.
7780 *
7781 * This gets called from two locations:
7782 *
7783 * -- Machine::saveSettings(), during the regular XML writing;
7784 *
7785 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7786 * exported to OVF and we write the VirtualBox proprietary XML
7787 * into a <vbox:Machine> tag.
7788 *
7789 * This routine fills all the fields in there, including snapshots, *except*
7790 * for the following:
7791 *
7792 * -- fCurrentStateModified. There is some special logic associated with that.
7793 *
7794 * The caller can then call MachineConfigFile::write() or do something else
7795 * with it.
7796 *
7797 * Caller must hold the machine lock!
7798 *
7799 * This throws XML errors and HRESULT, so the caller must have a catch block!
7800 */
7801void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7802{
7803 // deep copy extradata
7804 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7805
7806 config.uuid = mData->mUuid;
7807 config.strName = mUserData->mName;
7808 config.fNameSync = !!mUserData->mNameSync;
7809 config.strDescription = mUserData->mDescription;
7810 config.strOsType = mUserData->mOSTypeId;
7811
7812 if ( mData->mMachineState == MachineState_Saved
7813 || mData->mMachineState == MachineState_Restoring
7814 // when deleting a snapshot we may or may not have a saved state in the current state,
7815 // so let's not assert here please
7816 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7817 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7818 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7819 && (!mSSData->mStateFilePath.isEmpty())
7820 )
7821 )
7822 {
7823 Assert(!mSSData->mStateFilePath.isEmpty());
7824 /* try to make the file name relative to the settings file dir */
7825 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
7826 }
7827 else
7828 {
7829 Assert(mSSData->mStateFilePath.isEmpty());
7830 config.strStateFile.setNull();
7831 }
7832
7833 if (mData->mCurrentSnapshot)
7834 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7835 else
7836 config.uuidCurrentSnapshot.clear();
7837
7838 config.strSnapshotFolder = mUserData->mSnapshotFolder;
7839 // config.fCurrentStateModified is special, see below
7840 config.timeLastStateChange = mData->mLastStateChange;
7841 config.fAborted = (mData->mMachineState == MachineState_Aborted);
7842 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
7843
7844 config.fTeleporterEnabled = !!mUserData->mTeleporterEnabled;
7845 config.uTeleporterPort = mUserData->mTeleporterPort;
7846 config.strTeleporterAddress = mUserData->mTeleporterAddress;
7847 config.strTeleporterPassword = mUserData->mTeleporterPassword;
7848
7849 config.fRTCUseUTC = !!mUserData->mRTCUseUTC;
7850
7851 HRESULT rc = saveHardware(config.hardwareMachine);
7852 if (FAILED(rc)) throw rc;
7853
7854 rc = saveStorageControllers(config.storageMachine);
7855 if (FAILED(rc)) throw rc;
7856
7857 // save snapshots
7858 rc = saveAllSnapshots(config);
7859 if (FAILED(rc)) throw rc;
7860}
7861
7862/**
7863 * Saves all snapshots of the machine into the given machine config file. Called
7864 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
7865 * @param config
7866 * @return
7867 */
7868HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
7869{
7870 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7871
7872 HRESULT rc = S_OK;
7873
7874 try
7875 {
7876 config.llFirstSnapshot.clear();
7877
7878 if (mData->mFirstSnapshot)
7879 {
7880 settings::Snapshot snapNew;
7881 config.llFirstSnapshot.push_back(snapNew);
7882
7883 // get reference to the fresh copy of the snapshot on the list and
7884 // work on that copy directly to avoid excessive copying later
7885 settings::Snapshot &snap = config.llFirstSnapshot.front();
7886
7887 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
7888 if (FAILED(rc)) throw rc;
7889 }
7890
7891// if (mType == IsSessionMachine)
7892// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
7893
7894 }
7895 catch (HRESULT err)
7896 {
7897 /* we assume that error info is set by the thrower */
7898 rc = err;
7899 }
7900 catch (...)
7901 {
7902 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7903 }
7904
7905 return rc;
7906}
7907
7908/**
7909 * Saves the VM hardware configuration. It is assumed that the
7910 * given node is empty.
7911 *
7912 * @param aNode <Hardware> node to save the VM hardware confguration to.
7913 */
7914HRESULT Machine::saveHardware(settings::Hardware &data)
7915{
7916 HRESULT rc = S_OK;
7917
7918 try
7919 {
7920 /* The hardware version attribute (optional).
7921 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
7922 if ( mHWData->mHWVersion == "1"
7923 && mSSData->mStateFilePath.isEmpty()
7924 )
7925 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. */
7926
7927 data.strVersion = mHWData->mHWVersion;
7928 data.uuid = mHWData->mHardwareUUID;
7929
7930 // CPU
7931 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
7932 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
7933 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
7934 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
7935 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
7936 data.fPAE = !!mHWData->mPAEEnabled;
7937 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
7938
7939 /* Standard and Extended CPUID leafs. */
7940 data.llCpuIdLeafs.clear();
7941 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
7942 {
7943 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
7944 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
7945 }
7946 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
7947 {
7948 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
7949 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
7950 }
7951
7952 data.cCPUs = mHWData->mCPUCount;
7953 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
7954
7955 data.llCpus.clear();
7956 if (data.fCpuHotPlug)
7957 {
7958 for (unsigned idx = 0; idx < data.cCPUs; idx++)
7959 {
7960 if (mHWData->mCPUAttached[idx])
7961 {
7962 settings::Cpu cpu;
7963 cpu.ulId = idx;
7964 data.llCpus.push_back(cpu);
7965 }
7966 }
7967 }
7968
7969 // memory
7970 data.ulMemorySizeMB = mHWData->mMemorySize;
7971 data.fPageFusionEnabled = mHWData->mPageFusionEnabled;
7972
7973 // firmware
7974 data.firmwareType = mHWData->mFirmwareType;
7975
7976 // HID
7977 data.pointingHidType = mHWData->mPointingHidType;
7978 data.keyboardHidType = mHWData->mKeyboardHidType;
7979
7980 // HPET
7981 data.fHpetEnabled = !!mHWData->mHpetEnabled;
7982
7983 // boot order
7984 data.mapBootOrder.clear();
7985 for (size_t i = 0;
7986 i < RT_ELEMENTS(mHWData->mBootOrder);
7987 ++i)
7988 data.mapBootOrder[i] = mHWData->mBootOrder[i];
7989
7990 // display
7991 data.ulVRAMSizeMB = mHWData->mVRAMSize;
7992 data.cMonitors = mHWData->mMonitorCount;
7993 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
7994 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
7995
7996#ifdef VBOX_WITH_VRDP
7997 /* VRDP settings (optional) */
7998 rc = mVRDPServer->saveSettings(data.vrdpSettings);
7999 if (FAILED(rc)) throw rc;
8000#endif
8001
8002 /* BIOS (required) */
8003 rc = mBIOSSettings->saveSettings(data.biosSettings);
8004 if (FAILED(rc)) throw rc;
8005
8006 /* USB Controller (required) */
8007 rc = mUSBController->saveSettings(data.usbController);
8008 if (FAILED(rc)) throw rc;
8009
8010 /* Network adapters (required) */
8011 data.llNetworkAdapters.clear();
8012 for (ULONG slot = 0;
8013 slot < RT_ELEMENTS(mNetworkAdapters);
8014 ++slot)
8015 {
8016 settings::NetworkAdapter nic;
8017 nic.ulSlot = slot;
8018 rc = mNetworkAdapters[slot]->saveSettings(nic);
8019 if (FAILED(rc)) throw rc;
8020
8021 data.llNetworkAdapters.push_back(nic);
8022 }
8023
8024 /* Serial ports */
8025 data.llSerialPorts.clear();
8026 for (ULONG slot = 0;
8027 slot < RT_ELEMENTS(mSerialPorts);
8028 ++slot)
8029 {
8030 settings::SerialPort s;
8031 s.ulSlot = slot;
8032 rc = mSerialPorts[slot]->saveSettings(s);
8033 if (FAILED(rc)) return rc;
8034
8035 data.llSerialPorts.push_back(s);
8036 }
8037
8038 /* Parallel ports */
8039 data.llParallelPorts.clear();
8040 for (ULONG slot = 0;
8041 slot < RT_ELEMENTS(mParallelPorts);
8042 ++slot)
8043 {
8044 settings::ParallelPort p;
8045 p.ulSlot = slot;
8046 rc = mParallelPorts[slot]->saveSettings(p);
8047 if (FAILED(rc)) return rc;
8048
8049 data.llParallelPorts.push_back(p);
8050 }
8051
8052 /* Audio adapter */
8053 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8054 if (FAILED(rc)) return rc;
8055
8056 /* Shared folders */
8057 data.llSharedFolders.clear();
8058 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8059 it != mHWData->mSharedFolders.end();
8060 ++it)
8061 {
8062 ComObjPtr<SharedFolder> pFolder = *it;
8063 settings::SharedFolder sf;
8064 sf.strName = pFolder->getName();
8065 sf.strHostPath = pFolder->getHostPath();
8066 sf.fWritable = !!pFolder->isWritable();
8067 sf.fAutoMount = !!pFolder->isAutoMounted();
8068
8069 data.llSharedFolders.push_back(sf);
8070 }
8071
8072 // clipboard
8073 data.clipboardMode = mHWData->mClipboardMode;
8074
8075 /* Guest */
8076 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8077
8078 // IO settings
8079 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8080 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8081 data.ioSettings.ulIoBandwidthMax = mHWData->mIoBandwidthMax;
8082
8083 // guest properties
8084 data.llGuestProperties.clear();
8085#ifdef VBOX_WITH_GUEST_PROPS
8086 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8087 it != mHWData->mGuestProperties.end();
8088 ++it)
8089 {
8090 HWData::GuestProperty property = *it;
8091
8092 /* Remove transient guest properties at shutdown unless we
8093 * are saving state */
8094 if ( ( mData->mMachineState == MachineState_PoweredOff
8095 || mData->mMachineState == MachineState_Aborted
8096 || mData->mMachineState == MachineState_Teleported)
8097 && property.mFlags & guestProp::TRANSIENT)
8098 continue;
8099 settings::GuestProperty prop;
8100 prop.strName = property.strName;
8101 prop.strValue = property.strValue;
8102 prop.timestamp = property.mTimestamp;
8103 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8104 guestProp::writeFlags(property.mFlags, szFlags);
8105 prop.strFlags = szFlags;
8106
8107 data.llGuestProperties.push_back(prop);
8108 }
8109
8110 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8111 /* I presume this doesn't require a backup(). */
8112 mData->mGuestPropertiesModified = FALSE;
8113#endif /* VBOX_WITH_GUEST_PROPS defined */
8114 }
8115 catch(std::bad_alloc &)
8116 {
8117 return E_OUTOFMEMORY;
8118 }
8119
8120 AssertComRC(rc);
8121 return rc;
8122}
8123
8124/**
8125 * Saves the storage controller configuration.
8126 *
8127 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
8128 */
8129HRESULT Machine::saveStorageControllers(settings::Storage &data)
8130{
8131 data.llStorageControllers.clear();
8132
8133 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8134 it != mStorageControllers->end();
8135 ++it)
8136 {
8137 HRESULT rc;
8138 ComObjPtr<StorageController> pCtl = *it;
8139
8140 settings::StorageController ctl;
8141 ctl.strName = pCtl->getName();
8142 ctl.controllerType = pCtl->getControllerType();
8143 ctl.storageBus = pCtl->getStorageBus();
8144 ctl.ulInstance = pCtl->getInstance();
8145
8146 /* Save the port count. */
8147 ULONG portCount;
8148 rc = pCtl->COMGETTER(PortCount)(&portCount);
8149 ComAssertComRCRet(rc, rc);
8150 ctl.ulPortCount = portCount;
8151
8152 /* Save fUseHostIOCache */
8153 BOOL fUseHostIOCache;
8154 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8155 ComAssertComRCRet(rc, rc);
8156 ctl.fUseHostIOCache = !!fUseHostIOCache;
8157
8158 /* Save IDE emulation settings. */
8159 if (ctl.controllerType == StorageControllerType_IntelAhci)
8160 {
8161 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8162 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8163 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8164 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8165 )
8166 ComAssertComRCRet(rc, rc);
8167 }
8168
8169 /* save the devices now. */
8170 rc = saveStorageDevices(pCtl, ctl);
8171 ComAssertComRCRet(rc, rc);
8172
8173 data.llStorageControllers.push_back(ctl);
8174 }
8175
8176 return S_OK;
8177}
8178
8179/**
8180 * Saves the hard disk confguration.
8181 */
8182HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8183 settings::StorageController &data)
8184{
8185 MediaData::AttachmentList atts;
8186
8187 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()), atts);
8188 if (FAILED(rc)) return rc;
8189
8190 data.llAttachedDevices.clear();
8191 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8192 it != atts.end();
8193 ++it)
8194 {
8195 settings::AttachedDevice dev;
8196
8197 MediumAttachment *pAttach = *it;
8198 Medium *pMedium = pAttach->getMedium();
8199
8200 dev.deviceType = pAttach->getType();
8201 dev.lPort = pAttach->getPort();
8202 dev.lDevice = pAttach->getDevice();
8203 if (pMedium)
8204 {
8205 BOOL fHostDrive = FALSE;
8206 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
8207 if (FAILED(rc))
8208 return rc;
8209 if (fHostDrive)
8210 dev.strHostDriveSrc = pMedium->getLocation();
8211 else
8212 dev.uuid = pMedium->getId();
8213 dev.fPassThrough = pAttach->getPassthrough();
8214 }
8215
8216 data.llAttachedDevices.push_back(dev);
8217 }
8218
8219 return S_OK;
8220}
8221
8222/**
8223 * Saves machine state settings as defined by aFlags
8224 * (SaveSTS_* values).
8225 *
8226 * @param aFlags Combination of SaveSTS_* flags.
8227 *
8228 * @note Locks objects for writing.
8229 */
8230HRESULT Machine::saveStateSettings(int aFlags)
8231{
8232 if (aFlags == 0)
8233 return S_OK;
8234
8235 AutoCaller autoCaller(this);
8236 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8237
8238 /* This object's write lock is also necessary to serialize file access
8239 * (prevent concurrent reads and writes) */
8240 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8241
8242 HRESULT rc = S_OK;
8243
8244 Assert(mData->pMachineConfigFile);
8245
8246 try
8247 {
8248 if (aFlags & SaveSTS_CurStateModified)
8249 mData->pMachineConfigFile->fCurrentStateModified = true;
8250
8251 if (aFlags & SaveSTS_StateFilePath)
8252 {
8253 if (!mSSData->mStateFilePath.isEmpty())
8254 /* try to make the file name relative to the settings file dir */
8255 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8256 else
8257 mData->pMachineConfigFile->strStateFile.setNull();
8258 }
8259
8260 if (aFlags & SaveSTS_StateTimeStamp)
8261 {
8262 Assert( mData->mMachineState != MachineState_Aborted
8263 || mSSData->mStateFilePath.isEmpty());
8264
8265 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8266
8267 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8268//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8269 }
8270
8271 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8272 }
8273 catch (...)
8274 {
8275 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8276 }
8277
8278 return rc;
8279}
8280
8281/**
8282 * Creates differencing hard disks for all normal hard disks attached to this
8283 * machine and a new set of attachments to refer to created disks.
8284 *
8285 * Used when taking a snapshot or when deleting the current state.
8286 *
8287 * This method assumes that mMediaData contains the original hard disk attachments
8288 * it needs to create diffs for. On success, these attachments will be replaced
8289 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8290 * called to delete created diffs which will also rollback mMediaData and restore
8291 * whatever was backed up before calling this method.
8292 *
8293 * Attachments with non-normal hard disks are left as is.
8294 *
8295 * If @a aOnline is @c false then the original hard disks that require implicit
8296 * diffs will be locked for reading. Otherwise it is assumed that they are
8297 * already locked for writing (when the VM was started). Note that in the latter
8298 * case it is responsibility of the caller to lock the newly created diffs for
8299 * writing if this method succeeds.
8300 *
8301 * @param aFolder Folder where to create diff hard disks.
8302 * @param aProgress Progress object to run (must contain at least as
8303 * many operations left as the number of hard disks
8304 * attached).
8305 * @param aOnline Whether the VM was online prior to this operation.
8306 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8307 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8308 *
8309 * @note The progress object is not marked as completed, neither on success nor
8310 * on failure. This is a responsibility of the caller.
8311 *
8312 * @note Locks this object for writing.
8313 */
8314HRESULT Machine::createImplicitDiffs(const Bstr &aFolder,
8315 IProgress *aProgress,
8316 ULONG aWeight,
8317 bool aOnline,
8318 bool *pfNeedsSaveSettings)
8319{
8320 AssertReturn(!aFolder.isEmpty(), E_FAIL);
8321
8322 LogFlowThisFunc(("aFolder='%ls', aOnline=%d\n", aFolder.raw(), aOnline));
8323
8324 AutoCaller autoCaller(this);
8325 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8326
8327 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8328
8329 /* must be in a protective state because we leave the lock below */
8330 AssertReturn( mData->mMachineState == MachineState_Saving
8331 || mData->mMachineState == MachineState_LiveSnapshotting
8332 || mData->mMachineState == MachineState_RestoringSnapshot
8333 || mData->mMachineState == MachineState_DeletingSnapshot
8334 , E_FAIL);
8335
8336 HRESULT rc = S_OK;
8337
8338 MediumLockListMap lockedMediaOffline;
8339 MediumLockListMap *lockedMediaMap;
8340 if (aOnline)
8341 lockedMediaMap = &mData->mSession.mLockedMedia;
8342 else
8343 lockedMediaMap = &lockedMediaOffline;
8344
8345 try
8346 {
8347 if (!aOnline)
8348 {
8349 /* lock all attached hard disks early to detect "in use"
8350 * situations before creating actual diffs */
8351 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8352 it != mMediaData->mAttachments.end();
8353 ++it)
8354 {
8355 MediumAttachment* pAtt = *it;
8356 if (pAtt->getType() == DeviceType_HardDisk)
8357 {
8358 Medium* pMedium = pAtt->getMedium();
8359 Assert(pMedium);
8360
8361 MediumLockList *pMediumLockList(new MediumLockList());
8362 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8363 false /* fMediumLockWrite */,
8364 NULL,
8365 *pMediumLockList);
8366 if (FAILED(rc))
8367 {
8368 delete pMediumLockList;
8369 throw rc;
8370 }
8371 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8372 if (FAILED(rc))
8373 {
8374 throw setError(rc,
8375 tr("Collecting locking information for all attached media failed"));
8376 }
8377 }
8378 }
8379
8380 /* Now lock all media. If this fails, nothing is locked. */
8381 rc = lockedMediaMap->Lock();
8382 if (FAILED(rc))
8383 {
8384 throw setError(rc,
8385 tr("Locking of attached media failed"));
8386 }
8387 }
8388
8389 /* remember the current list (note that we don't use backup() since
8390 * mMediaData may be already backed up) */
8391 MediaData::AttachmentList atts = mMediaData->mAttachments;
8392
8393 /* start from scratch */
8394 mMediaData->mAttachments.clear();
8395
8396 /* go through remembered attachments and create diffs for normal hard
8397 * disks and attach them */
8398 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8399 it != atts.end();
8400 ++it)
8401 {
8402 MediumAttachment* pAtt = *it;
8403
8404 DeviceType_T devType = pAtt->getType();
8405 Medium* pMedium = pAtt->getMedium();
8406
8407 if ( devType != DeviceType_HardDisk
8408 || pMedium == NULL
8409 || pMedium->getType() != MediumType_Normal)
8410 {
8411 /* copy the attachment as is */
8412
8413 /** @todo the progress object created in Console::TakeSnaphot
8414 * only expects operations for hard disks. Later other
8415 * device types need to show up in the progress as well. */
8416 if (devType == DeviceType_HardDisk)
8417 {
8418 if (pMedium == NULL)
8419 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
8420 aWeight); // weight
8421 else
8422 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8423 pMedium->getBase()->getName().raw()),
8424 aWeight); // weight
8425 }
8426
8427 mMediaData->mAttachments.push_back(pAtt);
8428 continue;
8429 }
8430
8431 /* need a diff */
8432 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8433 pMedium->getBase()->getName().raw()),
8434 aWeight); // weight
8435
8436 ComObjPtr<Medium> diff;
8437 diff.createObject();
8438 rc = diff->init(mParent,
8439 pMedium->preferredDiffFormat().raw(),
8440 BstrFmt("%ls"RTPATH_SLASH_STR,
8441 mUserData->mSnapshotFolderFull.raw()).raw(),
8442 pfNeedsSaveSettings);
8443 if (FAILED(rc)) throw rc;
8444
8445 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8446 * the push_back? Looks like we're going to leave medium with the
8447 * wrong kind of lock (general issue with if we fail anywhere at all)
8448 * and an orphaned VDI in the snapshots folder. */
8449
8450 /* update the appropriate lock list */
8451 MediumLockList *pMediumLockList;
8452 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8453 AssertComRCThrowRC(rc);
8454 if (aOnline)
8455 {
8456 rc = pMediumLockList->Update(pMedium, false);
8457 AssertComRCThrowRC(rc);
8458 }
8459
8460 /* leave the lock before the potentially lengthy operation */
8461 alock.leave();
8462 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8463 pMediumLockList,
8464 NULL /* aProgress */,
8465 true /* aWait */,
8466 pfNeedsSaveSettings);
8467 alock.enter();
8468 if (FAILED(rc)) throw rc;
8469
8470 rc = lockedMediaMap->Unlock();
8471 AssertComRCThrowRC(rc);
8472 rc = pMediumLockList->Append(diff, true);
8473 AssertComRCThrowRC(rc);
8474 rc = lockedMediaMap->Lock();
8475 AssertComRCThrowRC(rc);
8476
8477 rc = diff->attachTo(mData->mUuid);
8478 AssertComRCThrowRC(rc);
8479
8480 /* add a new attachment */
8481 ComObjPtr<MediumAttachment> attachment;
8482 attachment.createObject();
8483 rc = attachment->init(this,
8484 diff,
8485 pAtt->getControllerName(),
8486 pAtt->getPort(),
8487 pAtt->getDevice(),
8488 DeviceType_HardDisk,
8489 true /* aImplicit */);
8490 if (FAILED(rc)) throw rc;
8491
8492 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8493 AssertComRCThrowRC(rc);
8494 mMediaData->mAttachments.push_back(attachment);
8495 }
8496 }
8497 catch (HRESULT aRC) { rc = aRC; }
8498
8499 /* unlock all hard disks we locked */
8500 if (!aOnline)
8501 {
8502 ErrorInfoKeeper eik;
8503
8504 rc = lockedMediaMap->Clear();
8505 AssertComRC(rc);
8506 }
8507
8508 if (FAILED(rc))
8509 {
8510 MultiResult mrc = rc;
8511
8512 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8513 }
8514
8515 return rc;
8516}
8517
8518/**
8519 * Deletes implicit differencing hard disks created either by
8520 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8521 *
8522 * Note that to delete hard disks created by #AttachMedium() this method is
8523 * called from #fixupMedia() when the changes are rolled back.
8524 *
8525 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8526 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8527 *
8528 * @note Locks this object for writing.
8529 */
8530HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8531{
8532 AutoCaller autoCaller(this);
8533 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8534
8535 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8536 LogFlowThisFuncEnter();
8537
8538 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8539
8540 HRESULT rc = S_OK;
8541
8542 MediaData::AttachmentList implicitAtts;
8543
8544 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8545
8546 /* enumerate new attachments */
8547 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8548 it != mMediaData->mAttachments.end();
8549 ++it)
8550 {
8551 ComObjPtr<Medium> hd = (*it)->getMedium();
8552 if (hd.isNull())
8553 continue;
8554
8555 if ((*it)->isImplicit())
8556 {
8557 /* deassociate and mark for deletion */
8558 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8559 rc = hd->detachFrom(mData->mUuid);
8560 AssertComRC(rc);
8561 implicitAtts.push_back(*it);
8562 continue;
8563 }
8564
8565 /* was this hard disk attached before? */
8566 if (!findAttachment(oldAtts, hd))
8567 {
8568 /* no: de-associate */
8569 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8570 rc = hd->detachFrom(mData->mUuid);
8571 AssertComRC(rc);
8572 continue;
8573 }
8574 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8575 }
8576
8577 /* rollback hard disk changes */
8578 mMediaData.rollback();
8579
8580 MultiResult mrc(S_OK);
8581
8582 /* delete unused implicit diffs */
8583 if (implicitAtts.size() != 0)
8584 {
8585 /* will leave the lock before the potentially lengthy
8586 * operation, so protect with the special state (unless already
8587 * protected) */
8588 MachineState_T oldState = mData->mMachineState;
8589 if ( oldState != MachineState_Saving
8590 && oldState != MachineState_LiveSnapshotting
8591 && oldState != MachineState_RestoringSnapshot
8592 && oldState != MachineState_DeletingSnapshot
8593 && oldState != MachineState_DeletingSnapshotOnline
8594 && oldState != MachineState_DeletingSnapshotPaused
8595 )
8596 setMachineState(MachineState_SettingUp);
8597
8598 alock.leave();
8599
8600 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8601 it != implicitAtts.end();
8602 ++it)
8603 {
8604 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8605 ComObjPtr<Medium> hd = (*it)->getMedium();
8606
8607 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8608 pfNeedsSaveSettings);
8609 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8610 mrc = rc;
8611 }
8612
8613 alock.enter();
8614
8615 if (mData->mMachineState == MachineState_SettingUp)
8616 {
8617 setMachineState(oldState);
8618 }
8619 }
8620
8621 return mrc;
8622}
8623
8624/**
8625 * Looks through the given list of media attachments for one with the given parameters
8626 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8627 * can be searched as well if needed.
8628 *
8629 * @param list
8630 * @param aControllerName
8631 * @param aControllerPort
8632 * @param aDevice
8633 * @return
8634 */
8635MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8636 IN_BSTR aControllerName,
8637 LONG aControllerPort,
8638 LONG aDevice)
8639{
8640 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8641 it != ll.end();
8642 ++it)
8643 {
8644 MediumAttachment *pAttach = *it;
8645 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8646 return pAttach;
8647 }
8648
8649 return NULL;
8650}
8651
8652/**
8653 * Looks through the given list of media attachments for one with the given parameters
8654 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8655 * can be searched as well if needed.
8656 *
8657 * @param list
8658 * @param aControllerName
8659 * @param aControllerPort
8660 * @param aDevice
8661 * @return
8662 */
8663MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8664 ComObjPtr<Medium> pMedium)
8665{
8666 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8667 it != ll.end();
8668 ++it)
8669 {
8670 MediumAttachment *pAttach = *it;
8671 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8672 if (pMediumThis == pMedium)
8673 return pAttach;
8674 }
8675
8676 return NULL;
8677}
8678
8679/**
8680 * Looks through the given list of media attachments for one with the given parameters
8681 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8682 * can be searched as well if needed.
8683 *
8684 * @param list
8685 * @param aControllerName
8686 * @param aControllerPort
8687 * @param aDevice
8688 * @return
8689 */
8690MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8691 Guid &id)
8692{
8693 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8694 it != ll.end();
8695 ++it)
8696 {
8697 MediumAttachment *pAttach = *it;
8698 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8699 if (pMediumThis->getId() == id)
8700 return pAttach;
8701 }
8702
8703 return NULL;
8704}
8705
8706/**
8707 * Main implementation for Machine::DetachDevice. This also gets called
8708 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8709 *
8710 * @param pAttach Medium attachment to detach.
8711 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8712 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8713 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8714 * @return
8715 */
8716HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8717 AutoWriteLock &writeLock,
8718 bool *pfNeedsSaveSettings)
8719{
8720 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8721 DeviceType_T mediumType = pAttach->getType();
8722
8723 if (pAttach->isImplicit())
8724 {
8725 /* attempt to implicitly delete the implicitly created diff */
8726
8727 /// @todo move the implicit flag from MediumAttachment to Medium
8728 /// and forbid any hard disk operation when it is implicit. Or maybe
8729 /// a special media state for it to make it even more simple.
8730
8731 Assert(mMediaData.isBackedUp());
8732
8733 /* will leave the lock before the potentially lengthy operation, so
8734 * protect with the special state */
8735 MachineState_T oldState = mData->mMachineState;
8736 setMachineState(MachineState_SettingUp);
8737
8738 writeLock.release();
8739
8740 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8741 pfNeedsSaveSettings);
8742
8743 writeLock.acquire();
8744
8745 setMachineState(oldState);
8746
8747 if (FAILED(rc)) return rc;
8748 }
8749
8750 setModified(IsModified_Storage);
8751 mMediaData.backup();
8752
8753 /* we cannot use erase (it) below because backup() above will create
8754 * a copy of the list and make this copy active, but the iterator
8755 * still refers to the original and is not valid for the copy */
8756 mMediaData->mAttachments.remove(pAttach);
8757
8758 /* For non-hard disk media, detach straight away. */
8759 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
8760 oldmedium->detachFrom(mData->mUuid);
8761
8762 return S_OK;
8763}
8764
8765/**
8766 * Perform deferred hard disk detachments.
8767 *
8768 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8769 * backed up).
8770 *
8771 * If @a aOnline is @c true then this method will also unlock the old hard disks
8772 * for which the new implicit diffs were created and will lock these new diffs for
8773 * writing.
8774 *
8775 * @param aOnline Whether the VM was online prior to this operation.
8776 *
8777 * @note Locks this object for writing!
8778 */
8779void Machine::commitMedia(bool aOnline /*= false*/)
8780{
8781 AutoCaller autoCaller(this);
8782 AssertComRCReturnVoid(autoCaller.rc());
8783
8784 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8785
8786 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
8787
8788 HRESULT rc = S_OK;
8789
8790 /* no attach/detach operations -- nothing to do */
8791 if (!mMediaData.isBackedUp())
8792 return;
8793
8794 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8795 bool fMediaNeedsLocking = false;
8796
8797 /* enumerate new attachments */
8798 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8799 it != mMediaData->mAttachments.end();
8800 ++it)
8801 {
8802 MediumAttachment *pAttach = *it;
8803
8804 pAttach->commit();
8805
8806 Medium* pMedium = pAttach->getMedium();
8807 bool fImplicit = pAttach->isImplicit();
8808
8809 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
8810 (pMedium) ? pMedium->getName().raw() : "NULL",
8811 fImplicit));
8812
8813 /** @todo convert all this Machine-based voodoo to MediumAttachment
8814 * based commit logic. */
8815 if (fImplicit)
8816 {
8817 /* convert implicit attachment to normal */
8818 pAttach->setImplicit(false);
8819
8820 if ( aOnline
8821 && pMedium
8822 && pAttach->getType() == DeviceType_HardDisk
8823 )
8824 {
8825 ComObjPtr<Medium> parent = pMedium->getParent();
8826 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8827
8828 /* update the appropriate lock list */
8829 MediumLockList *pMediumLockList;
8830 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8831 AssertComRC(rc);
8832 if (pMediumLockList)
8833 {
8834 /* unlock if there's a need to change the locking */
8835 if (!fMediaNeedsLocking)
8836 {
8837 rc = mData->mSession.mLockedMedia.Unlock();
8838 AssertComRC(rc);
8839 fMediaNeedsLocking = true;
8840 }
8841 rc = pMediumLockList->Update(parent, false);
8842 AssertComRC(rc);
8843 rc = pMediumLockList->Append(pMedium, true);
8844 AssertComRC(rc);
8845 }
8846 }
8847
8848 continue;
8849 }
8850
8851 if (pMedium)
8852 {
8853 /* was this medium attached before? */
8854 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
8855 oldIt != oldAtts.end();
8856 ++oldIt)
8857 {
8858 MediumAttachment *pOldAttach = *oldIt;
8859 if (pOldAttach->getMedium() == pMedium)
8860 {
8861 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().raw()));
8862
8863 /* yes: remove from old to avoid de-association */
8864 oldAtts.erase(oldIt);
8865 break;
8866 }
8867 }
8868 }
8869 }
8870
8871 /* enumerate remaining old attachments and de-associate from the
8872 * current machine state */
8873 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
8874 it != oldAtts.end();
8875 ++it)
8876 {
8877 MediumAttachment *pAttach = *it;
8878 Medium* pMedium = pAttach->getMedium();
8879
8880 /* Detach only hard disks, since DVD/floppy media is detached
8881 * instantly in MountMedium. */
8882 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
8883 {
8884 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().raw()));
8885
8886 /* now de-associate from the current machine state */
8887 rc = pMedium->detachFrom(mData->mUuid);
8888 AssertComRC(rc);
8889
8890 if (aOnline)
8891 {
8892 /* unlock since medium is not used anymore */
8893 MediumLockList *pMediumLockList;
8894 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8895 AssertComRC(rc);
8896 if (pMediumLockList)
8897 {
8898 rc = mData->mSession.mLockedMedia.Remove(pAttach);
8899 AssertComRC(rc);
8900 }
8901 }
8902 }
8903 }
8904
8905 /* take media locks again so that the locking state is consistent */
8906 if (fMediaNeedsLocking)
8907 {
8908 Assert(aOnline);
8909 rc = mData->mSession.mLockedMedia.Lock();
8910 AssertComRC(rc);
8911 }
8912
8913 /* commit the hard disk changes */
8914 mMediaData.commit();
8915
8916 if (isSessionMachine())
8917 {
8918 /* attach new data to the primary machine and reshare it */
8919 mPeer->mMediaData.attach(mMediaData);
8920 }
8921
8922 return;
8923}
8924
8925/**
8926 * Perform deferred deletion of implicitly created diffs.
8927 *
8928 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8929 * backed up).
8930 *
8931 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8932 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8933 *
8934 * @note Locks this object for writing!
8935 */
8936void Machine::rollbackMedia()
8937{
8938 AutoCaller autoCaller(this);
8939 AssertComRCReturnVoid (autoCaller.rc());
8940
8941 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8942
8943 LogFlowThisFunc(("Entering\n"));
8944
8945 HRESULT rc = S_OK;
8946
8947 /* no attach/detach operations -- nothing to do */
8948 if (!mMediaData.isBackedUp())
8949 return;
8950
8951 /* enumerate new attachments */
8952 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8953 it != mMediaData->mAttachments.end();
8954 ++it)
8955 {
8956 MediumAttachment *pAttach = *it;
8957 /* Fix up the backrefs for DVD/floppy media. */
8958 if (pAttach->getType() != DeviceType_HardDisk)
8959 {
8960 Medium* pMedium = pAttach->getMedium();
8961 if (pMedium)
8962 {
8963 rc = pMedium->detachFrom(mData->mUuid);
8964 AssertComRC(rc);
8965 }
8966 }
8967
8968 (*it)->rollback();
8969
8970 pAttach = *it;
8971 /* Fix up the backrefs for DVD/floppy media. */
8972 if (pAttach->getType() != DeviceType_HardDisk)
8973 {
8974 Medium* pMedium = pAttach->getMedium();
8975 if (pMedium)
8976 {
8977 rc = pMedium->attachTo(mData->mUuid);
8978 AssertComRC(rc);
8979 }
8980 }
8981 }
8982
8983 /** @todo convert all this Machine-based voodoo to MediumAttachment
8984 * based rollback logic. */
8985 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
8986 // which gets called if Machine::registeredInit() fails...
8987 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
8988
8989 return;
8990}
8991
8992/**
8993 * Returns true if the settings file is located in the directory named exactly
8994 * as the machine. This will be true if the machine settings structure was
8995 * created by default in #openConfigLoader().
8996 *
8997 * @param aSettingsDir if not NULL, the full machine settings file directory
8998 * name will be assigned there.
8999 *
9000 * @note Doesn't lock anything.
9001 * @note Not thread safe (must be called from this object's lock).
9002 */
9003bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9004{
9005 Utf8Str settingsDir = mData->m_strConfigFileFull;
9006 settingsDir.stripFilename();
9007 char *dirName = RTPathFilename(settingsDir.c_str());
9008
9009 AssertReturn(dirName, false);
9010
9011 /* if we don't rename anything on name change, return false shorlty */
9012 if (!mUserData->mNameSync)
9013 return false;
9014
9015 if (aSettingsDir)
9016 *aSettingsDir = settingsDir;
9017
9018 return Bstr(dirName) == mUserData->mName;
9019}
9020
9021/**
9022 * Discards all changes to machine settings.
9023 *
9024 * @param aNotify Whether to notify the direct session about changes or not.
9025 *
9026 * @note Locks objects for writing!
9027 */
9028void Machine::rollback(bool aNotify)
9029{
9030 AutoCaller autoCaller(this);
9031 AssertComRCReturn(autoCaller.rc(), (void)0);
9032
9033 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9034
9035 if (!mStorageControllers.isNull())
9036 {
9037 if (mStorageControllers.isBackedUp())
9038 {
9039 /* unitialize all new devices (absent in the backed up list). */
9040 StorageControllerList::const_iterator it = mStorageControllers->begin();
9041 StorageControllerList *backedList = mStorageControllers.backedUpData();
9042 while (it != mStorageControllers->end())
9043 {
9044 if ( std::find(backedList->begin(), backedList->end(), *it)
9045 == backedList->end()
9046 )
9047 {
9048 (*it)->uninit();
9049 }
9050 ++it;
9051 }
9052
9053 /* restore the list */
9054 mStorageControllers.rollback();
9055 }
9056
9057 /* rollback any changes to devices after restoring the list */
9058 if (mData->flModifications & IsModified_Storage)
9059 {
9060 StorageControllerList::const_iterator it = mStorageControllers->begin();
9061 while (it != mStorageControllers->end())
9062 {
9063 (*it)->rollback();
9064 ++it;
9065 }
9066 }
9067 }
9068
9069 mUserData.rollback();
9070
9071 mHWData.rollback();
9072
9073 if (mData->flModifications & IsModified_Storage)
9074 rollbackMedia();
9075
9076 if (mBIOSSettings)
9077 mBIOSSettings->rollback();
9078
9079#ifdef VBOX_WITH_VRDP
9080 if (mVRDPServer && (mData->flModifications & IsModified_VRDPServer))
9081 mVRDPServer->rollback();
9082#endif
9083
9084 if (mAudioAdapter)
9085 mAudioAdapter->rollback();
9086
9087 if (mUSBController && (mData->flModifications & IsModified_USB))
9088 mUSBController->rollback();
9089
9090 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9091 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9092 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9093
9094 if (mData->flModifications & IsModified_NetworkAdapters)
9095 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9096 if ( mNetworkAdapters[slot]
9097 && mNetworkAdapters[slot]->isModified())
9098 {
9099 mNetworkAdapters[slot]->rollback();
9100 networkAdapters[slot] = mNetworkAdapters[slot];
9101 }
9102
9103 if (mData->flModifications & IsModified_SerialPorts)
9104 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9105 if ( mSerialPorts[slot]
9106 && mSerialPorts[slot]->isModified())
9107 {
9108 mSerialPorts[slot]->rollback();
9109 serialPorts[slot] = mSerialPorts[slot];
9110 }
9111
9112 if (mData->flModifications & IsModified_ParallelPorts)
9113 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9114 if ( mParallelPorts[slot]
9115 && mParallelPorts[slot]->isModified())
9116 {
9117 mParallelPorts[slot]->rollback();
9118 parallelPorts[slot] = mParallelPorts[slot];
9119 }
9120
9121 if (aNotify)
9122 {
9123 /* inform the direct session about changes */
9124
9125 ComObjPtr<Machine> that = this;
9126 uint32_t flModifications = mData->flModifications;
9127 alock.leave();
9128
9129 if (flModifications & IsModified_SharedFolders)
9130 that->onSharedFolderChange();
9131
9132 if (flModifications & IsModified_VRDPServer)
9133 that->onVRDPServerChange(/* aRestart */ TRUE);
9134 if (flModifications & IsModified_USB)
9135 that->onUSBControllerChange();
9136
9137 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9138 if (networkAdapters[slot])
9139 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9140 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9141 if (serialPorts[slot])
9142 that->onSerialPortChange(serialPorts[slot]);
9143 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9144 if (parallelPorts[slot])
9145 that->onParallelPortChange(parallelPorts[slot]);
9146
9147 if (flModifications & IsModified_Storage)
9148 that->onStorageControllerChange();
9149 }
9150}
9151
9152/**
9153 * Commits all the changes to machine settings.
9154 *
9155 * Note that this operation is supposed to never fail.
9156 *
9157 * @note Locks this object and children for writing.
9158 */
9159void Machine::commit()
9160{
9161 AutoCaller autoCaller(this);
9162 AssertComRCReturnVoid(autoCaller.rc());
9163
9164 AutoCaller peerCaller(mPeer);
9165 AssertComRCReturnVoid(peerCaller.rc());
9166
9167 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9168
9169 /*
9170 * use safe commit to ensure Snapshot machines (that share mUserData)
9171 * will still refer to a valid memory location
9172 */
9173 mUserData.commitCopy();
9174
9175 mHWData.commit();
9176
9177 if (mMediaData.isBackedUp())
9178 commitMedia();
9179
9180 mBIOSSettings->commit();
9181#ifdef VBOX_WITH_VRDP
9182 mVRDPServer->commit();
9183#endif
9184 mAudioAdapter->commit();
9185 mUSBController->commit();
9186
9187 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9188 mNetworkAdapters[slot]->commit();
9189 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9190 mSerialPorts[slot]->commit();
9191 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9192 mParallelPorts[slot]->commit();
9193
9194 bool commitStorageControllers = false;
9195
9196 if (mStorageControllers.isBackedUp())
9197 {
9198 mStorageControllers.commit();
9199
9200 if (mPeer)
9201 {
9202 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9203
9204 /* Commit all changes to new controllers (this will reshare data with
9205 * peers for thos who have peers) */
9206 StorageControllerList *newList = new StorageControllerList();
9207 StorageControllerList::const_iterator it = mStorageControllers->begin();
9208 while (it != mStorageControllers->end())
9209 {
9210 (*it)->commit();
9211
9212 /* look if this controller has a peer device */
9213 ComObjPtr<StorageController> peer = (*it)->getPeer();
9214 if (!peer)
9215 {
9216 /* no peer means the device is a newly created one;
9217 * create a peer owning data this device share it with */
9218 peer.createObject();
9219 peer->init(mPeer, *it, true /* aReshare */);
9220 }
9221 else
9222 {
9223 /* remove peer from the old list */
9224 mPeer->mStorageControllers->remove(peer);
9225 }
9226 /* and add it to the new list */
9227 newList->push_back(peer);
9228
9229 ++it;
9230 }
9231
9232 /* uninit old peer's controllers that are left */
9233 it = mPeer->mStorageControllers->begin();
9234 while (it != mPeer->mStorageControllers->end())
9235 {
9236 (*it)->uninit();
9237 ++it;
9238 }
9239
9240 /* attach new list of controllers to our peer */
9241 mPeer->mStorageControllers.attach(newList);
9242 }
9243 else
9244 {
9245 /* we have no peer (our parent is the newly created machine);
9246 * just commit changes to devices */
9247 commitStorageControllers = true;
9248 }
9249 }
9250 else
9251 {
9252 /* the list of controllers itself is not changed,
9253 * just commit changes to controllers themselves */
9254 commitStorageControllers = true;
9255 }
9256
9257 if (commitStorageControllers)
9258 {
9259 StorageControllerList::const_iterator it = mStorageControllers->begin();
9260 while (it != mStorageControllers->end())
9261 {
9262 (*it)->commit();
9263 ++it;
9264 }
9265 }
9266
9267 if (isSessionMachine())
9268 {
9269 /* attach new data to the primary machine and reshare it */
9270 mPeer->mUserData.attach(mUserData);
9271 mPeer->mHWData.attach(mHWData);
9272 /* mMediaData is reshared by fixupMedia */
9273 // mPeer->mMediaData.attach(mMediaData);
9274 Assert(mPeer->mMediaData.data() == mMediaData.data());
9275 }
9276}
9277
9278/**
9279 * Copies all the hardware data from the given machine.
9280 *
9281 * Currently, only called when the VM is being restored from a snapshot. In
9282 * particular, this implies that the VM is not running during this method's
9283 * call.
9284 *
9285 * @note This method must be called from under this object's lock.
9286 *
9287 * @note This method doesn't call #commit(), so all data remains backed up and
9288 * unsaved.
9289 */
9290void Machine::copyFrom(Machine *aThat)
9291{
9292 AssertReturnVoid(!isSnapshotMachine());
9293 AssertReturnVoid(aThat->isSnapshotMachine());
9294
9295 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9296
9297 mHWData.assignCopy(aThat->mHWData);
9298
9299 // create copies of all shared folders (mHWData after attiching a copy
9300 // contains just references to original objects)
9301 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9302 it != mHWData->mSharedFolders.end();
9303 ++it)
9304 {
9305 ComObjPtr<SharedFolder> folder;
9306 folder.createObject();
9307 HRESULT rc = folder->initCopy(getMachine(), *it);
9308 AssertComRC(rc);
9309 *it = folder;
9310 }
9311
9312 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9313#ifdef VBOX_WITH_VRDP
9314 mVRDPServer->copyFrom(aThat->mVRDPServer);
9315#endif
9316 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9317 mUSBController->copyFrom(aThat->mUSBController);
9318
9319 /* create private copies of all controllers */
9320 mStorageControllers.backup();
9321 mStorageControllers->clear();
9322 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9323 it != aThat->mStorageControllers->end();
9324 ++it)
9325 {
9326 ComObjPtr<StorageController> ctrl;
9327 ctrl.createObject();
9328 ctrl->initCopy(this, *it);
9329 mStorageControllers->push_back(ctrl);
9330 }
9331
9332 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9333 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9334 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9335 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9336 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9337 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9338}
9339
9340#ifdef VBOX_WITH_RESOURCE_USAGE_API
9341
9342void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9343{
9344 AssertReturnVoid(isWriteLockOnCurrentThread());
9345 AssertPtrReturnVoid(aCollector);
9346
9347 pm::CollectorHAL *hal = aCollector->getHAL();
9348 /* Create sub metrics */
9349 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9350 "Percentage of processor time spent in user mode by the VM process.");
9351 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9352 "Percentage of processor time spent in kernel mode by the VM process.");
9353 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9354 "Size of resident portion of VM process in memory.");
9355 /* Create and register base metrics */
9356 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9357 cpuLoadUser, cpuLoadKernel);
9358 aCollector->registerBaseMetric(cpuLoad);
9359 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9360 ramUsageUsed);
9361 aCollector->registerBaseMetric(ramUsage);
9362
9363 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9364 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9365 new pm::AggregateAvg()));
9366 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9367 new pm::AggregateMin()));
9368 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9369 new pm::AggregateMax()));
9370 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9371 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9372 new pm::AggregateAvg()));
9373 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9374 new pm::AggregateMin()));
9375 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9376 new pm::AggregateMax()));
9377
9378 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9379 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9380 new pm::AggregateAvg()));
9381 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9382 new pm::AggregateMin()));
9383 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9384 new pm::AggregateMax()));
9385
9386
9387 /* Guest metrics */
9388 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9389
9390 /* Create sub metrics */
9391 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9392 "Percentage of processor time spent in user mode as seen by the guest.");
9393 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9394 "Percentage of processor time spent in kernel mode as seen by the guest.");
9395 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9396 "Percentage of processor time spent idling as seen by the guest.");
9397
9398 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9399 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9400 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9401 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9402 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9403 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9404
9405 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9406
9407 /* Create and register base metrics */
9408 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9409 aCollector->registerBaseMetric(guestCpuLoad);
9410
9411 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9412 guestMemCache, guestPagedTotal);
9413 aCollector->registerBaseMetric(guestCpuMem);
9414
9415 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9416 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9417 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9418 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9419
9420 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9421 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9422 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9423 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9424
9425 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9426 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9427 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9428 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9429
9430 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9431 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9432 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9433 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9434
9435 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9436 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9437 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9438 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9439
9440 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9441 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9442 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9443 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9444
9445 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9446 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9447 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9448 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9449
9450 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9451 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9452 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9453 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9454
9455 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9456 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9457 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9458 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9459}
9460
9461void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9462{
9463 AssertReturnVoid(isWriteLockOnCurrentThread());
9464
9465 if (aCollector)
9466 {
9467 aCollector->unregisterMetricsFor(aMachine);
9468 aCollector->unregisterBaseMetricsFor(aMachine);
9469 }
9470
9471 if (mGuestHAL)
9472 {
9473 delete mGuestHAL;
9474 mGuestHAL = NULL;
9475 }
9476}
9477
9478#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9479
9480
9481////////////////////////////////////////////////////////////////////////////////
9482
9483DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9484
9485HRESULT SessionMachine::FinalConstruct()
9486{
9487 LogFlowThisFunc(("\n"));
9488
9489#if defined(RT_OS_WINDOWS)
9490 mIPCSem = NULL;
9491#elif defined(RT_OS_OS2)
9492 mIPCSem = NULLHANDLE;
9493#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9494 mIPCSem = -1;
9495#else
9496# error "Port me!"
9497#endif
9498
9499 return S_OK;
9500}
9501
9502void SessionMachine::FinalRelease()
9503{
9504 LogFlowThisFunc(("\n"));
9505
9506 uninit(Uninit::Unexpected);
9507}
9508
9509/**
9510 * @note Must be called only by Machine::openSession() from its own write lock.
9511 */
9512HRESULT SessionMachine::init(Machine *aMachine)
9513{
9514 LogFlowThisFuncEnter();
9515 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
9516
9517 AssertReturn(aMachine, E_INVALIDARG);
9518
9519 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9520
9521 /* Enclose the state transition NotReady->InInit->Ready */
9522 AutoInitSpan autoInitSpan(this);
9523 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9524
9525 /* create the interprocess semaphore */
9526#if defined(RT_OS_WINDOWS)
9527 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9528 for (size_t i = 0; i < mIPCSemName.length(); i++)
9529 if (mIPCSemName[i] == '\\')
9530 mIPCSemName[i] = '/';
9531 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName);
9532 ComAssertMsgRet(mIPCSem,
9533 ("Cannot create IPC mutex '%ls', err=%d",
9534 mIPCSemName.raw(), ::GetLastError()),
9535 E_FAIL);
9536#elif defined(RT_OS_OS2)
9537 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9538 aMachine->mData->mUuid.raw());
9539 mIPCSemName = ipcSem;
9540 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.raw(), &mIPCSem, 0, FALSE);
9541 ComAssertMsgRet(arc == NO_ERROR,
9542 ("Cannot create IPC mutex '%s', arc=%ld",
9543 ipcSem.raw(), arc),
9544 E_FAIL);
9545#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9546# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9547# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9548 /** @todo Check that this still works correctly. */
9549 AssertCompileSize(key_t, 8);
9550# else
9551 AssertCompileSize(key_t, 4);
9552# endif
9553 key_t key;
9554 mIPCSem = -1;
9555 mIPCKey = "0";
9556 for (uint32_t i = 0; i < 1 << 24; i++)
9557 {
9558 key = ((uint32_t)'V' << 24) | i;
9559 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9560 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9561 {
9562 mIPCSem = sem;
9563 if (sem >= 0)
9564 mIPCKey = BstrFmt("%u", key);
9565 break;
9566 }
9567 }
9568# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9569 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9570 char *pszSemName = NULL;
9571 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9572 key_t key = ::ftok(pszSemName, 'V');
9573 RTStrFree(pszSemName);
9574
9575 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9576# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9577
9578 int errnoSave = errno;
9579 if (mIPCSem < 0 && errnoSave == ENOSYS)
9580 {
9581 setError(E_FAIL,
9582 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9583 "support for SysV IPC. Check the host kernel configuration for "
9584 "CONFIG_SYSVIPC=y"));
9585 return E_FAIL;
9586 }
9587 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9588 * the IPC semaphores */
9589 if (mIPCSem < 0 && errnoSave == ENOSPC)
9590 {
9591#ifdef RT_OS_LINUX
9592 setError(E_FAIL,
9593 tr("Cannot create IPC semaphore because the system limit for the "
9594 "maximum number of semaphore sets (SEMMNI), or the system wide "
9595 "maximum number of sempahores (SEMMNS) would be exceeded. The "
9596 "current set of SysV IPC semaphores can be determined from "
9597 "the file /proc/sysvipc/sem"));
9598#else
9599 setError(E_FAIL,
9600 tr("Cannot create IPC semaphore because the system-imposed limit "
9601 "on the maximum number of allowed semaphores or semaphore "
9602 "identifiers system-wide would be exceeded"));
9603#endif
9604 return E_FAIL;
9605 }
9606 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9607 E_FAIL);
9608 /* set the initial value to 1 */
9609 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9610 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9611 E_FAIL);
9612#else
9613# error "Port me!"
9614#endif
9615
9616 /* memorize the peer Machine */
9617 unconst(mPeer) = aMachine;
9618 /* share the parent pointer */
9619 unconst(mParent) = aMachine->mParent;
9620
9621 /* take the pointers to data to share */
9622 mData.share(aMachine->mData);
9623 mSSData.share(aMachine->mSSData);
9624
9625 mUserData.share(aMachine->mUserData);
9626 mHWData.share(aMachine->mHWData);
9627 mMediaData.share(aMachine->mMediaData);
9628
9629 mStorageControllers.allocate();
9630 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9631 it != aMachine->mStorageControllers->end();
9632 ++it)
9633 {
9634 ComObjPtr<StorageController> ctl;
9635 ctl.createObject();
9636 ctl->init(this, *it);
9637 mStorageControllers->push_back(ctl);
9638 }
9639
9640 unconst(mBIOSSettings).createObject();
9641 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9642#ifdef VBOX_WITH_VRDP
9643 /* create another VRDPServer object that will be mutable */
9644 unconst(mVRDPServer).createObject();
9645 mVRDPServer->init(this, aMachine->mVRDPServer);
9646#endif
9647 /* create another audio adapter object that will be mutable */
9648 unconst(mAudioAdapter).createObject();
9649 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9650 /* create a list of serial ports that will be mutable */
9651 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9652 {
9653 unconst(mSerialPorts[slot]).createObject();
9654 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9655 }
9656 /* create a list of parallel ports that will be mutable */
9657 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9658 {
9659 unconst(mParallelPorts[slot]).createObject();
9660 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9661 }
9662 /* create another USB controller object that will be mutable */
9663 unconst(mUSBController).createObject();
9664 mUSBController->init(this, aMachine->mUSBController);
9665
9666 /* create a list of network adapters that will be mutable */
9667 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9668 {
9669 unconst(mNetworkAdapters[slot]).createObject();
9670 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9671 }
9672
9673 /* Confirm a successful initialization when it's the case */
9674 autoInitSpan.setSucceeded();
9675
9676 LogFlowThisFuncLeave();
9677 return S_OK;
9678}
9679
9680/**
9681 * Uninitializes this session object. If the reason is other than
9682 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9683 *
9684 * @param aReason uninitialization reason
9685 *
9686 * @note Locks mParent + this object for writing.
9687 */
9688void SessionMachine::uninit(Uninit::Reason aReason)
9689{
9690 LogFlowThisFuncEnter();
9691 LogFlowThisFunc(("reason=%d\n", aReason));
9692
9693 /*
9694 * Strongly reference ourselves to prevent this object deletion after
9695 * mData->mSession.mMachine.setNull() below (which can release the last
9696 * reference and call the destructor). Important: this must be done before
9697 * accessing any members (and before AutoUninitSpan that does it as well).
9698 * This self reference will be released as the very last step on return.
9699 */
9700 ComObjPtr<SessionMachine> selfRef = this;
9701
9702 /* Enclose the state transition Ready->InUninit->NotReady */
9703 AutoUninitSpan autoUninitSpan(this);
9704 if (autoUninitSpan.uninitDone())
9705 {
9706 LogFlowThisFunc(("Already uninitialized\n"));
9707 LogFlowThisFuncLeave();
9708 return;
9709 }
9710
9711 if (autoUninitSpan.initFailed())
9712 {
9713 /* We've been called by init() because it's failed. It's not really
9714 * necessary (nor it's safe) to perform the regular uninit sequense
9715 * below, the following is enough.
9716 */
9717 LogFlowThisFunc(("Initialization failed.\n"));
9718#if defined(RT_OS_WINDOWS)
9719 if (mIPCSem)
9720 ::CloseHandle(mIPCSem);
9721 mIPCSem = NULL;
9722#elif defined(RT_OS_OS2)
9723 if (mIPCSem != NULLHANDLE)
9724 ::DosCloseMutexSem(mIPCSem);
9725 mIPCSem = NULLHANDLE;
9726#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9727 if (mIPCSem >= 0)
9728 ::semctl(mIPCSem, 0, IPC_RMID);
9729 mIPCSem = -1;
9730# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9731 mIPCKey = "0";
9732# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9733#else
9734# error "Port me!"
9735#endif
9736 uninitDataAndChildObjects();
9737 mData.free();
9738 unconst(mParent) = NULL;
9739 unconst(mPeer) = NULL;
9740 LogFlowThisFuncLeave();
9741 return;
9742 }
9743
9744 MachineState_T lastState;
9745 {
9746 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9747 lastState = mData->mMachineState;
9748 }
9749 NOREF(lastState);
9750
9751#ifdef VBOX_WITH_USB
9752 // release all captured USB devices, but do this before requesting the locks below
9753 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9754 {
9755 /* Console::captureUSBDevices() is called in the VM process only after
9756 * setting the machine state to Starting or Restoring.
9757 * Console::detachAllUSBDevices() will be called upon successful
9758 * termination. So, we need to release USB devices only if there was
9759 * an abnormal termination of a running VM.
9760 *
9761 * This is identical to SessionMachine::DetachAllUSBDevices except
9762 * for the aAbnormal argument. */
9763 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9764 AssertComRC(rc);
9765 NOREF(rc);
9766
9767 USBProxyService *service = mParent->host()->usbProxyService();
9768 if (service)
9769 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9770 }
9771#endif /* VBOX_WITH_USB */
9772
9773 // we need to lock this object in uninit() because the lock is shared
9774 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
9775 // and others need mParent lock, and USB needs host lock.
9776 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
9777
9778 // Trigger async cleanup tasks, avoid doing things here which are not
9779 // vital to be done immediately and maybe need more locks. This calls
9780 // Machine::unregisterMetrics().
9781 mParent->onMachineUninit(mPeer);
9782
9783 if (aReason == Uninit::Abnormal)
9784 {
9785 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
9786 Global::IsOnlineOrTransient(lastState)));
9787
9788 /* reset the state to Aborted */
9789 if (mData->mMachineState != MachineState_Aborted)
9790 setMachineState(MachineState_Aborted);
9791 }
9792
9793 // any machine settings modified?
9794 if (mData->flModifications)
9795 {
9796 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
9797 rollback(false /* aNotify */);
9798 }
9799
9800 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
9801 if (!mSnapshotData.mStateFilePath.isEmpty())
9802 {
9803 LogWarningThisFunc(("canceling failed save state request!\n"));
9804 endSavingState(FALSE /* aSuccess */);
9805 }
9806 else if (!mSnapshotData.mSnapshot.isNull())
9807 {
9808 LogWarningThisFunc(("canceling untaken snapshot!\n"));
9809
9810 /* delete all differencing hard disks created (this will also attach
9811 * their parents back by rolling back mMediaData) */
9812 rollbackMedia();
9813 /* delete the saved state file (it might have been already created) */
9814 if (mSnapshotData.mSnapshot->stateFilePath().length())
9815 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
9816
9817 mSnapshotData.mSnapshot->uninit();
9818 }
9819
9820 if (!mData->mSession.mType.isEmpty())
9821 {
9822 /* mType is not null when this machine's process has been started by
9823 * Machine::launchVMProcess(), therefore it is our child. We
9824 * need to queue the PID to reap the process (and avoid zombies on
9825 * Linux). */
9826 Assert(mData->mSession.mPid != NIL_RTPROCESS);
9827 mParent->addProcessToReap(mData->mSession.mPid);
9828 }
9829
9830 mData->mSession.mPid = NIL_RTPROCESS;
9831
9832 if (aReason == Uninit::Unexpected)
9833 {
9834 /* Uninitialization didn't come from #checkForDeath(), so tell the
9835 * client watcher thread to update the set of machines that have open
9836 * sessions. */
9837 mParent->updateClientWatcher();
9838 }
9839
9840 /* uninitialize all remote controls */
9841 if (mData->mSession.mRemoteControls.size())
9842 {
9843 LogFlowThisFunc(("Closing remote sessions (%d):\n",
9844 mData->mSession.mRemoteControls.size()));
9845
9846 Data::Session::RemoteControlList::iterator it =
9847 mData->mSession.mRemoteControls.begin();
9848 while (it != mData->mSession.mRemoteControls.end())
9849 {
9850 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
9851 HRESULT rc = (*it)->Uninitialize();
9852 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
9853 if (FAILED(rc))
9854 LogWarningThisFunc(("Forgot to close the remote session?\n"));
9855 ++it;
9856 }
9857 mData->mSession.mRemoteControls.clear();
9858 }
9859
9860 /*
9861 * An expected uninitialization can come only from #checkForDeath().
9862 * Otherwise it means that something's got really wrong (for examlple,
9863 * the Session implementation has released the VirtualBox reference
9864 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
9865 * etc). However, it's also possible, that the client releases the IPC
9866 * semaphore correctly (i.e. before it releases the VirtualBox reference),
9867 * but the VirtualBox release event comes first to the server process.
9868 * This case is practically possible, so we should not assert on an
9869 * unexpected uninit, just log a warning.
9870 */
9871
9872 if ((aReason == Uninit::Unexpected))
9873 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
9874
9875 if (aReason != Uninit::Normal)
9876 {
9877 mData->mSession.mDirectControl.setNull();
9878 }
9879 else
9880 {
9881 /* this must be null here (see #OnSessionEnd()) */
9882 Assert(mData->mSession.mDirectControl.isNull());
9883 Assert(mData->mSession.mState == SessionState_Unlocking);
9884 Assert(!mData->mSession.mProgress.isNull());
9885 }
9886 if (mData->mSession.mProgress)
9887 {
9888 if (aReason == Uninit::Normal)
9889 mData->mSession.mProgress->notifyComplete(S_OK);
9890 else
9891 mData->mSession.mProgress->notifyComplete(E_FAIL,
9892 COM_IIDOF(ISession),
9893 getComponentName(),
9894 tr("The VM session was aborted"));
9895 mData->mSession.mProgress.setNull();
9896 }
9897
9898 /* remove the association between the peer machine and this session machine */
9899 Assert( (SessionMachine*)mData->mSession.mMachine == this
9900 || aReason == Uninit::Unexpected);
9901
9902 /* reset the rest of session data */
9903 mData->mSession.mMachine.setNull();
9904 mData->mSession.mState = SessionState_Unlocked;
9905 mData->mSession.mType.setNull();
9906
9907 /* close the interprocess semaphore before leaving the exclusive lock */
9908#if defined(RT_OS_WINDOWS)
9909 if (mIPCSem)
9910 ::CloseHandle(mIPCSem);
9911 mIPCSem = NULL;
9912#elif defined(RT_OS_OS2)
9913 if (mIPCSem != NULLHANDLE)
9914 ::DosCloseMutexSem(mIPCSem);
9915 mIPCSem = NULLHANDLE;
9916#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9917 if (mIPCSem >= 0)
9918 ::semctl(mIPCSem, 0, IPC_RMID);
9919 mIPCSem = -1;
9920# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9921 mIPCKey = "0";
9922# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9923#else
9924# error "Port me!"
9925#endif
9926
9927 /* fire an event */
9928 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
9929
9930 uninitDataAndChildObjects();
9931
9932 /* free the essential data structure last */
9933 mData.free();
9934
9935#if 1 /** @todo Please review this change! (bird) */
9936 /* drop the exclusive lock before setting the below two to NULL */
9937 multilock.release();
9938#else
9939 /* leave the exclusive lock before setting the below two to NULL */
9940 multilock.leave();
9941#endif
9942
9943 unconst(mParent) = NULL;
9944 unconst(mPeer) = NULL;
9945
9946 LogFlowThisFuncLeave();
9947}
9948
9949// util::Lockable interface
9950////////////////////////////////////////////////////////////////////////////////
9951
9952/**
9953 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
9954 * with the primary Machine instance (mPeer).
9955 */
9956RWLockHandle *SessionMachine::lockHandle() const
9957{
9958 AssertReturn(mPeer != NULL, NULL);
9959 return mPeer->lockHandle();
9960}
9961
9962// IInternalMachineControl methods
9963////////////////////////////////////////////////////////////////////////////////
9964
9965/**
9966 * @note Locks the same as #setMachineState() does.
9967 */
9968STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
9969{
9970 return setMachineState(aMachineState);
9971}
9972
9973/**
9974 * @note Locks this object for reading.
9975 */
9976STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
9977{
9978 AutoCaller autoCaller(this);
9979 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9980
9981 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9982
9983#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
9984 mIPCSemName.cloneTo(aId);
9985 return S_OK;
9986#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9987# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9988 mIPCKey.cloneTo(aId);
9989# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9990 mData->m_strConfigFileFull.cloneTo(aId);
9991# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9992 return S_OK;
9993#else
9994# error "Port me!"
9995#endif
9996}
9997
9998/**
9999 * @note Locks this object for writing.
10000 */
10001STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10002{
10003 AutoCaller autoCaller(this);
10004 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10005
10006 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10007
10008 if (mData->mSession.mState != SessionState_Locked)
10009 return VBOX_E_INVALID_OBJECT_STATE;
10010
10011 if (!mData->mSession.mProgress.isNull())
10012 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10013
10014 return S_OK;
10015}
10016
10017
10018/**
10019 * @note Locks this object for writing.
10020 */
10021STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10022{
10023 AutoCaller autoCaller(this);
10024 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10025
10026 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10027
10028 if (mData->mSession.mState != SessionState_Locked)
10029 return VBOX_E_INVALID_OBJECT_STATE;
10030
10031 /* Finalize the openRemoteSession progress object. */
10032 if (mData->mSession.mProgress)
10033 {
10034 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10035 mData->mSession.mProgress.setNull();
10036
10037 if (SUCCEEDED((HRESULT)iResult))
10038 {
10039#ifdef VBOX_WITH_RESOURCE_USAGE_API
10040 /* The VM has been powered up successfully, so it makes sense
10041 * now to offer the performance metrics for a running machine
10042 * object. Doing it earlier wouldn't be safe. */
10043 registerMetrics(mParent->performanceCollector(), mPeer,
10044 mData->mSession.mPid);
10045#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10046
10047 }
10048 }
10049 return S_OK;
10050}
10051
10052/**
10053 * Goes through the USB filters of the given machine to see if the given
10054 * device matches any filter or not.
10055 *
10056 * @note Locks the same as USBController::hasMatchingFilter() does.
10057 */
10058STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10059 BOOL *aMatched,
10060 ULONG *aMaskedIfs)
10061{
10062 LogFlowThisFunc(("\n"));
10063
10064 CheckComArgNotNull(aUSBDevice);
10065 CheckComArgOutPointerValid(aMatched);
10066
10067 AutoCaller autoCaller(this);
10068 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10069
10070#ifdef VBOX_WITH_USB
10071 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10072#else
10073 NOREF(aUSBDevice);
10074 NOREF(aMaskedIfs);
10075 *aMatched = FALSE;
10076#endif
10077
10078 return S_OK;
10079}
10080
10081/**
10082 * @note Locks the same as Host::captureUSBDevice() does.
10083 */
10084STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10085{
10086 LogFlowThisFunc(("\n"));
10087
10088 AutoCaller autoCaller(this);
10089 AssertComRCReturnRC(autoCaller.rc());
10090
10091#ifdef VBOX_WITH_USB
10092 /* if captureDeviceForVM() fails, it must have set extended error info */
10093 MultiResult rc = mParent->host()->checkUSBProxyService();
10094 if (FAILED(rc)) return rc;
10095
10096 USBProxyService *service = mParent->host()->usbProxyService();
10097 AssertReturn(service, E_FAIL);
10098 return service->captureDeviceForVM(this, Guid(aId));
10099#else
10100 NOREF(aId);
10101 return E_NOTIMPL;
10102#endif
10103}
10104
10105/**
10106 * @note Locks the same as Host::detachUSBDevice() does.
10107 */
10108STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10109{
10110 LogFlowThisFunc(("\n"));
10111
10112 AutoCaller autoCaller(this);
10113 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10114
10115#ifdef VBOX_WITH_USB
10116 USBProxyService *service = mParent->host()->usbProxyService();
10117 AssertReturn(service, E_FAIL);
10118 return service->detachDeviceFromVM(this, Guid(aId), !!aDone);
10119#else
10120 NOREF(aId);
10121 NOREF(aDone);
10122 return E_NOTIMPL;
10123#endif
10124}
10125
10126/**
10127 * Inserts all machine filters to the USB proxy service and then calls
10128 * Host::autoCaptureUSBDevices().
10129 *
10130 * Called by Console from the VM process upon VM startup.
10131 *
10132 * @note Locks what called methods lock.
10133 */
10134STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10135{
10136 LogFlowThisFunc(("\n"));
10137
10138 AutoCaller autoCaller(this);
10139 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10140
10141#ifdef VBOX_WITH_USB
10142 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10143 AssertComRC(rc);
10144 NOREF(rc);
10145
10146 USBProxyService *service = mParent->host()->usbProxyService();
10147 AssertReturn(service, E_FAIL);
10148 return service->autoCaptureDevicesForVM(this);
10149#else
10150 return S_OK;
10151#endif
10152}
10153
10154/**
10155 * Removes all machine filters from the USB proxy service and then calls
10156 * Host::detachAllUSBDevices().
10157 *
10158 * Called by Console from the VM process upon normal VM termination or by
10159 * SessionMachine::uninit() upon abnormal VM termination (from under the
10160 * Machine/SessionMachine lock).
10161 *
10162 * @note Locks what called methods lock.
10163 */
10164STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10165{
10166 LogFlowThisFunc(("\n"));
10167
10168 AutoCaller autoCaller(this);
10169 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10170
10171#ifdef VBOX_WITH_USB
10172 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10173 AssertComRC(rc);
10174 NOREF(rc);
10175
10176 USBProxyService *service = mParent->host()->usbProxyService();
10177 AssertReturn(service, E_FAIL);
10178 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10179#else
10180 NOREF(aDone);
10181 return S_OK;
10182#endif
10183}
10184
10185/**
10186 * @note Locks this object for writing.
10187 */
10188STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10189 IProgress **aProgress)
10190{
10191 LogFlowThisFuncEnter();
10192
10193 AssertReturn(aSession, E_INVALIDARG);
10194 AssertReturn(aProgress, E_INVALIDARG);
10195
10196 AutoCaller autoCaller(this);
10197
10198 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10199 /*
10200 * We don't assert below because it might happen that a non-direct session
10201 * informs us it is closed right after we've been uninitialized -- it's ok.
10202 */
10203 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10204
10205 /* get IInternalSessionControl interface */
10206 ComPtr<IInternalSessionControl> control(aSession);
10207
10208 ComAssertRet(!control.isNull(), E_INVALIDARG);
10209
10210 /* Creating a Progress object requires the VirtualBox lock, and
10211 * thus locking it here is required by the lock order rules. */
10212 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10213
10214 if (control == mData->mSession.mDirectControl)
10215 {
10216 ComAssertRet(aProgress, E_POINTER);
10217
10218 /* The direct session is being normally closed by the client process
10219 * ----------------------------------------------------------------- */
10220
10221 /* go to the closing state (essential for all open*Session() calls and
10222 * for #checkForDeath()) */
10223 Assert(mData->mSession.mState == SessionState_Locked);
10224 mData->mSession.mState = SessionState_Unlocking;
10225
10226 /* set direct control to NULL to release the remote instance */
10227 mData->mSession.mDirectControl.setNull();
10228 LogFlowThisFunc(("Direct control is set to NULL\n"));
10229
10230 if (mData->mSession.mProgress)
10231 {
10232 /* finalize the progress, someone might wait if a frontend
10233 * closes the session before powering on the VM. */
10234 mData->mSession.mProgress->notifyComplete(E_FAIL,
10235 COM_IIDOF(ISession),
10236 getComponentName(),
10237 tr("The VM session was closed before any attempt to power it on"));
10238 mData->mSession.mProgress.setNull();
10239 }
10240
10241 /* Create the progress object the client will use to wait until
10242 * #checkForDeath() is called to uninitialize this session object after
10243 * it releases the IPC semaphore.
10244 * Note! Because we're "reusing" mProgress here, this must be a proxy
10245 * object just like for openRemoteSession. */
10246 Assert(mData->mSession.mProgress.isNull());
10247 ComObjPtr<ProgressProxy> progress;
10248 progress.createObject();
10249 ComPtr<IUnknown> pPeer(mPeer);
10250 progress->init(mParent, pPeer,
10251 Bstr(tr("Closing session")),
10252 FALSE /* aCancelable */);
10253 progress.queryInterfaceTo(aProgress);
10254 mData->mSession.mProgress = progress;
10255 }
10256 else
10257 {
10258 /* the remote session is being normally closed */
10259 Data::Session::RemoteControlList::iterator it =
10260 mData->mSession.mRemoteControls.begin();
10261 while (it != mData->mSession.mRemoteControls.end())
10262 {
10263 if (control == *it)
10264 break;
10265 ++it;
10266 }
10267 BOOL found = it != mData->mSession.mRemoteControls.end();
10268 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10269 E_INVALIDARG);
10270 mData->mSession.mRemoteControls.remove(*it);
10271 }
10272
10273 LogFlowThisFuncLeave();
10274 return S_OK;
10275}
10276
10277/**
10278 * @note Locks this object for writing.
10279 */
10280STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10281{
10282 LogFlowThisFuncEnter();
10283
10284 AssertReturn(aProgress, E_INVALIDARG);
10285 AssertReturn(aStateFilePath, E_POINTER);
10286
10287 AutoCaller autoCaller(this);
10288 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10289
10290 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10291
10292 AssertReturn( mData->mMachineState == MachineState_Paused
10293 && mSnapshotData.mLastState == MachineState_Null
10294 && mSnapshotData.mProgressId.isEmpty()
10295 && mSnapshotData.mStateFilePath.isEmpty(),
10296 E_FAIL);
10297
10298 /* memorize the progress ID and add it to the global collection */
10299 Bstr progressId;
10300 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10301 AssertComRCReturn(rc, rc);
10302 rc = mParent->addProgress(aProgress);
10303 AssertComRCReturn(rc, rc);
10304
10305 Bstr stateFilePath;
10306 /* stateFilePath is null when the machine is not running */
10307 if (mData->mMachineState == MachineState_Paused)
10308 {
10309 stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
10310 mUserData->mSnapshotFolderFull.raw(),
10311 RTPATH_DELIMITER, mData->mUuid.raw());
10312 }
10313
10314 /* fill in the snapshot data */
10315 mSnapshotData.mLastState = mData->mMachineState;
10316 mSnapshotData.mProgressId = Guid(progressId);
10317 mSnapshotData.mStateFilePath = stateFilePath;
10318
10319 /* set the state to Saving (this is expected by Console::SaveState()) */
10320 setMachineState(MachineState_Saving);
10321
10322 stateFilePath.cloneTo(aStateFilePath);
10323
10324 return S_OK;
10325}
10326
10327/**
10328 * @note Locks mParent + this object for writing.
10329 */
10330STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10331{
10332 LogFlowThisFunc(("\n"));
10333
10334 AutoCaller autoCaller(this);
10335 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10336
10337 /* endSavingState() need mParent lock */
10338 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10339
10340 AssertReturn( mData->mMachineState == MachineState_Saving
10341 && mSnapshotData.mLastState != MachineState_Null
10342 && !mSnapshotData.mProgressId.isEmpty()
10343 && !mSnapshotData.mStateFilePath.isEmpty(),
10344 E_FAIL);
10345
10346 /*
10347 * on success, set the state to Saved;
10348 * on failure, set the state to the state we had when BeginSavingState() was
10349 * called (this is expected by Console::SaveState() and
10350 * Console::saveStateThread())
10351 */
10352 if (aSuccess)
10353 setMachineState(MachineState_Saved);
10354 else
10355 setMachineState(mSnapshotData.mLastState);
10356
10357 return endSavingState(aSuccess);
10358}
10359
10360/**
10361 * @note Locks this object for writing.
10362 */
10363STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10364{
10365 LogFlowThisFunc(("\n"));
10366
10367 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10368
10369 AutoCaller autoCaller(this);
10370 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10371
10372 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10373
10374 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10375 || mData->mMachineState == MachineState_Teleported
10376 || mData->mMachineState == MachineState_Aborted
10377 , E_FAIL); /** @todo setError. */
10378
10379 Utf8Str stateFilePathFull = aSavedStateFile;
10380 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10381 if (RT_FAILURE(vrc))
10382 return setError(VBOX_E_FILE_ERROR,
10383 tr("Invalid saved state file path '%ls' (%Rrc)"),
10384 aSavedStateFile,
10385 vrc);
10386
10387 mSSData->mStateFilePath = stateFilePathFull;
10388
10389 /* The below setMachineState() will detect the state transition and will
10390 * update the settings file */
10391
10392 return setMachineState(MachineState_Saved);
10393}
10394
10395STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10396 ComSafeArrayOut(BSTR, aValues),
10397 ComSafeArrayOut(ULONG64, aTimestamps),
10398 ComSafeArrayOut(BSTR, aFlags))
10399{
10400 LogFlowThisFunc(("\n"));
10401
10402#ifdef VBOX_WITH_GUEST_PROPS
10403 using namespace guestProp;
10404
10405 AutoCaller autoCaller(this);
10406 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10407
10408 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10409
10410 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10411 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10412 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10413 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10414
10415 size_t cEntries = mHWData->mGuestProperties.size();
10416 com::SafeArray<BSTR> names(cEntries);
10417 com::SafeArray<BSTR> values(cEntries);
10418 com::SafeArray<ULONG64> timestamps(cEntries);
10419 com::SafeArray<BSTR> flags(cEntries);
10420 unsigned i = 0;
10421 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10422 it != mHWData->mGuestProperties.end();
10423 ++it)
10424 {
10425 char szFlags[MAX_FLAGS_LEN + 1];
10426 it->strName.cloneTo(&names[i]);
10427 it->strValue.cloneTo(&values[i]);
10428 timestamps[i] = it->mTimestamp;
10429 /* If it is NULL, keep it NULL. */
10430 if (it->mFlags)
10431 {
10432 writeFlags(it->mFlags, szFlags);
10433 Bstr(szFlags).cloneTo(&flags[i]);
10434 }
10435 else
10436 flags[i] = NULL;
10437 ++i;
10438 }
10439 names.detachTo(ComSafeArrayOutArg(aNames));
10440 values.detachTo(ComSafeArrayOutArg(aValues));
10441 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10442 flags.detachTo(ComSafeArrayOutArg(aFlags));
10443 return S_OK;
10444#else
10445 ReturnComNotImplemented();
10446#endif
10447}
10448
10449STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10450 IN_BSTR aValue,
10451 ULONG64 aTimestamp,
10452 IN_BSTR aFlags)
10453{
10454 LogFlowThisFunc(("\n"));
10455
10456#ifdef VBOX_WITH_GUEST_PROPS
10457 using namespace guestProp;
10458
10459 CheckComArgStrNotEmptyOrNull(aName);
10460 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10461 return E_POINTER; /* aValue can be NULL to indicate deletion */
10462
10463 try
10464 {
10465 /*
10466 * Convert input up front.
10467 */
10468 Utf8Str utf8Name(aName);
10469 uint32_t fFlags = NILFLAG;
10470 if (aFlags)
10471 {
10472 Utf8Str utf8Flags(aFlags);
10473 int vrc = validateFlags(utf8Flags.raw(), &fFlags);
10474 AssertRCReturn(vrc, E_INVALIDARG);
10475 }
10476
10477 /*
10478 * Now grab the object lock, validate the state and do the update.
10479 */
10480 AutoCaller autoCaller(this);
10481 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10482
10483 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10484
10485 switch (mData->mMachineState)
10486 {
10487 case MachineState_Paused:
10488 case MachineState_Running:
10489 case MachineState_Teleporting:
10490 case MachineState_TeleportingPausedVM:
10491 case MachineState_LiveSnapshotting:
10492 case MachineState_DeletingSnapshotOnline:
10493 case MachineState_DeletingSnapshotPaused:
10494 case MachineState_Saving:
10495 break;
10496
10497 default:
10498 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10499 VBOX_E_INVALID_VM_STATE);
10500 }
10501
10502 setModified(IsModified_MachineData);
10503 mHWData.backup();
10504
10505 /** @todo r=bird: The careful memory handling doesn't work out here because
10506 * the catch block won't undo any damange we've done. So, if push_back throws
10507 * bad_alloc then you've lost the value.
10508 *
10509 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10510 * since values that changes actually bubbles to the end of the list. Using
10511 * something that has an efficient lookup and can tollerate a bit of updates
10512 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10513 * combination of RTStrCache (for sharing names and getting uniqueness into
10514 * the bargain) and hash/tree is another. */
10515 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10516 iter != mHWData->mGuestProperties.end();
10517 ++iter)
10518 if (utf8Name == iter->strName)
10519 {
10520 mHWData->mGuestProperties.erase(iter);
10521 mData->mGuestPropertiesModified = TRUE;
10522 break;
10523 }
10524 if (aValue != NULL)
10525 {
10526 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10527 mHWData->mGuestProperties.push_back(property);
10528 mData->mGuestPropertiesModified = TRUE;
10529 }
10530
10531 /*
10532 * Send a callback notification if appropriate
10533 */
10534 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10535 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(),
10536 RTSTR_MAX,
10537 utf8Name.raw(),
10538 RTSTR_MAX, NULL)
10539 )
10540 {
10541 alock.leave();
10542
10543 mParent->onGuestPropertyChange(mData->mUuid,
10544 aName,
10545 aValue,
10546 aFlags);
10547 }
10548 }
10549 catch (...)
10550 {
10551 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10552 }
10553 return S_OK;
10554#else
10555 ReturnComNotImplemented();
10556#endif
10557}
10558
10559// public methods only for internal purposes
10560/////////////////////////////////////////////////////////////////////////////
10561
10562/**
10563 * Called from the client watcher thread to check for expected or unexpected
10564 * death of the client process that has a direct session to this machine.
10565 *
10566 * On Win32 and on OS/2, this method is called only when we've got the
10567 * mutex (i.e. the client has either died or terminated normally) so it always
10568 * returns @c true (the client is terminated, the session machine is
10569 * uninitialized).
10570 *
10571 * On other platforms, the method returns @c true if the client process has
10572 * terminated normally or abnormally and the session machine was uninitialized,
10573 * and @c false if the client process is still alive.
10574 *
10575 * @note Locks this object for writing.
10576 */
10577bool SessionMachine::checkForDeath()
10578{
10579 Uninit::Reason reason;
10580 bool terminated = false;
10581
10582 /* Enclose autoCaller with a block because calling uninit() from under it
10583 * will deadlock. */
10584 {
10585 AutoCaller autoCaller(this);
10586 if (!autoCaller.isOk())
10587 {
10588 /* return true if not ready, to cause the client watcher to exclude
10589 * the corresponding session from watching */
10590 LogFlowThisFunc(("Already uninitialized!\n"));
10591 return true;
10592 }
10593
10594 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10595
10596 /* Determine the reason of death: if the session state is Closing here,
10597 * everything is fine. Otherwise it means that the client did not call
10598 * OnSessionEnd() before it released the IPC semaphore. This may happen
10599 * either because the client process has abnormally terminated, or
10600 * because it simply forgot to call ISession::Close() before exiting. We
10601 * threat the latter also as an abnormal termination (see
10602 * Session::uninit() for details). */
10603 reason = mData->mSession.mState == SessionState_Unlocking ?
10604 Uninit::Normal :
10605 Uninit::Abnormal;
10606
10607#if defined(RT_OS_WINDOWS)
10608
10609 AssertMsg(mIPCSem, ("semaphore must be created"));
10610
10611 /* release the IPC mutex */
10612 ::ReleaseMutex(mIPCSem);
10613
10614 terminated = true;
10615
10616#elif defined(RT_OS_OS2)
10617
10618 AssertMsg(mIPCSem, ("semaphore must be created"));
10619
10620 /* release the IPC mutex */
10621 ::DosReleaseMutexSem(mIPCSem);
10622
10623 terminated = true;
10624
10625#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10626
10627 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10628
10629 int val = ::semctl(mIPCSem, 0, GETVAL);
10630 if (val > 0)
10631 {
10632 /* the semaphore is signaled, meaning the session is terminated */
10633 terminated = true;
10634 }
10635
10636#else
10637# error "Port me!"
10638#endif
10639
10640 } /* AutoCaller block */
10641
10642 if (terminated)
10643 uninit(reason);
10644
10645 return terminated;
10646}
10647
10648/**
10649 * @note Locks this object for reading.
10650 */
10651HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10652{
10653 LogFlowThisFunc(("\n"));
10654
10655 AutoCaller autoCaller(this);
10656 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10657
10658 ComPtr<IInternalSessionControl> directControl;
10659 {
10660 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10661 directControl = mData->mSession.mDirectControl;
10662 }
10663
10664 /* ignore notifications sent after #OnSessionEnd() is called */
10665 if (!directControl)
10666 return S_OK;
10667
10668 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10669}
10670
10671/**
10672 * @note Locks this object for reading.
10673 */
10674HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10675{
10676 LogFlowThisFunc(("\n"));
10677
10678 AutoCaller autoCaller(this);
10679 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10680
10681 ComPtr<IInternalSessionControl> directControl;
10682 {
10683 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10684 directControl = mData->mSession.mDirectControl;
10685 }
10686
10687 /* ignore notifications sent after #OnSessionEnd() is called */
10688 if (!directControl)
10689 return S_OK;
10690
10691 return directControl->OnSerialPortChange(serialPort);
10692}
10693
10694/**
10695 * @note Locks this object for reading.
10696 */
10697HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10698{
10699 LogFlowThisFunc(("\n"));
10700
10701 AutoCaller autoCaller(this);
10702 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10703
10704 ComPtr<IInternalSessionControl> directControl;
10705 {
10706 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10707 directControl = mData->mSession.mDirectControl;
10708 }
10709
10710 /* ignore notifications sent after #OnSessionEnd() is called */
10711 if (!directControl)
10712 return S_OK;
10713
10714 return directControl->OnParallelPortChange(parallelPort);
10715}
10716
10717/**
10718 * @note Locks this object for reading.
10719 */
10720HRESULT SessionMachine::onStorageControllerChange()
10721{
10722 LogFlowThisFunc(("\n"));
10723
10724 AutoCaller autoCaller(this);
10725 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10726
10727 ComPtr<IInternalSessionControl> directControl;
10728 {
10729 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10730 directControl = mData->mSession.mDirectControl;
10731 }
10732
10733 /* ignore notifications sent after #OnSessionEnd() is called */
10734 if (!directControl)
10735 return S_OK;
10736
10737 return directControl->OnStorageControllerChange();
10738}
10739
10740/**
10741 * @note Locks this object for reading.
10742 */
10743HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10744{
10745 LogFlowThisFunc(("\n"));
10746
10747 AutoCaller autoCaller(this);
10748 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10749
10750 ComPtr<IInternalSessionControl> directControl;
10751 {
10752 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10753 directControl = mData->mSession.mDirectControl;
10754 }
10755
10756 /* ignore notifications sent after #OnSessionEnd() is called */
10757 if (!directControl)
10758 return S_OK;
10759
10760 return directControl->OnMediumChange(aAttachment, aForce);
10761}
10762
10763/**
10764 * @note Locks this object for reading.
10765 */
10766HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
10767{
10768 LogFlowThisFunc(("\n"));
10769
10770 AutoCaller autoCaller(this);
10771 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10772
10773 ComPtr<IInternalSessionControl> directControl;
10774 {
10775 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10776 directControl = mData->mSession.mDirectControl;
10777 }
10778
10779 /* ignore notifications sent after #OnSessionEnd() is called */
10780 if (!directControl)
10781 return S_OK;
10782
10783 return directControl->OnCPUChange(aCPU, aRemove);
10784}
10785
10786/**
10787 * @note Locks this object for reading.
10788 */
10789HRESULT SessionMachine::onVRDPServerChange(BOOL aRestart)
10790{
10791 LogFlowThisFunc(("\n"));
10792
10793 AutoCaller autoCaller(this);
10794 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10795
10796 ComPtr<IInternalSessionControl> directControl;
10797 {
10798 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10799 directControl = mData->mSession.mDirectControl;
10800 }
10801
10802 /* ignore notifications sent after #OnSessionEnd() is called */
10803 if (!directControl)
10804 return S_OK;
10805
10806 return directControl->OnVRDPServerChange(aRestart);
10807}
10808
10809/**
10810 * @note Locks this object for reading.
10811 */
10812HRESULT SessionMachine::onUSBControllerChange()
10813{
10814 LogFlowThisFunc(("\n"));
10815
10816 AutoCaller autoCaller(this);
10817 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10818
10819 ComPtr<IInternalSessionControl> directControl;
10820 {
10821 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10822 directControl = mData->mSession.mDirectControl;
10823 }
10824
10825 /* ignore notifications sent after #OnSessionEnd() is called */
10826 if (!directControl)
10827 return S_OK;
10828
10829 return directControl->OnUSBControllerChange();
10830}
10831
10832/**
10833 * @note Locks this object for reading.
10834 */
10835HRESULT SessionMachine::onSharedFolderChange()
10836{
10837 LogFlowThisFunc(("\n"));
10838
10839 AutoCaller autoCaller(this);
10840 AssertComRCReturnRC(autoCaller.rc());
10841
10842 ComPtr<IInternalSessionControl> directControl;
10843 {
10844 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10845 directControl = mData->mSession.mDirectControl;
10846 }
10847
10848 /* ignore notifications sent after #OnSessionEnd() is called */
10849 if (!directControl)
10850 return S_OK;
10851
10852 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
10853}
10854
10855/**
10856 * Returns @c true if this machine's USB controller reports it has a matching
10857 * filter for the given USB device and @c false otherwise.
10858 *
10859 * @note Caller must have requested machine read lock.
10860 */
10861bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
10862{
10863 AutoCaller autoCaller(this);
10864 /* silently return if not ready -- this method may be called after the
10865 * direct machine session has been called */
10866 if (!autoCaller.isOk())
10867 return false;
10868
10869
10870#ifdef VBOX_WITH_USB
10871 switch (mData->mMachineState)
10872 {
10873 case MachineState_Starting:
10874 case MachineState_Restoring:
10875 case MachineState_TeleportingIn:
10876 case MachineState_Paused:
10877 case MachineState_Running:
10878 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
10879 * elsewhere... */
10880 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
10881 default: break;
10882 }
10883#else
10884 NOREF(aDevice);
10885 NOREF(aMaskedIfs);
10886#endif
10887 return false;
10888}
10889
10890/**
10891 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10892 */
10893HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
10894 IVirtualBoxErrorInfo *aError,
10895 ULONG aMaskedIfs)
10896{
10897 LogFlowThisFunc(("\n"));
10898
10899 AutoCaller autoCaller(this);
10900
10901 /* This notification may happen after the machine object has been
10902 * uninitialized (the session was closed), so don't assert. */
10903 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10904
10905 ComPtr<IInternalSessionControl> directControl;
10906 {
10907 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10908 directControl = mData->mSession.mDirectControl;
10909 }
10910
10911 /* fail on notifications sent after #OnSessionEnd() is called, it is
10912 * expected by the caller */
10913 if (!directControl)
10914 return E_FAIL;
10915
10916 /* No locks should be held at this point. */
10917 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10918 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10919
10920 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
10921}
10922
10923/**
10924 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10925 */
10926HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
10927 IVirtualBoxErrorInfo *aError)
10928{
10929 LogFlowThisFunc(("\n"));
10930
10931 AutoCaller autoCaller(this);
10932
10933 /* This notification may happen after the machine object has been
10934 * uninitialized (the session was closed), so don't assert. */
10935 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10936
10937 ComPtr<IInternalSessionControl> directControl;
10938 {
10939 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10940 directControl = mData->mSession.mDirectControl;
10941 }
10942
10943 /* fail on notifications sent after #OnSessionEnd() is called, it is
10944 * expected by the caller */
10945 if (!directControl)
10946 return E_FAIL;
10947
10948 /* No locks should be held at this point. */
10949 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10950 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10951
10952 return directControl->OnUSBDeviceDetach(aId, aError);
10953}
10954
10955// protected methods
10956/////////////////////////////////////////////////////////////////////////////
10957
10958/**
10959 * Helper method to finalize saving the state.
10960 *
10961 * @note Must be called from under this object's lock.
10962 *
10963 * @param aSuccess TRUE if the snapshot has been taken successfully
10964 *
10965 * @note Locks mParent + this objects for writing.
10966 */
10967HRESULT SessionMachine::endSavingState(BOOL aSuccess)
10968{
10969 LogFlowThisFuncEnter();
10970
10971 AutoCaller autoCaller(this);
10972 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10973
10974 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10975
10976 HRESULT rc = S_OK;
10977
10978 if (aSuccess)
10979 {
10980 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
10981
10982 /* save all VM settings */
10983 rc = saveSettings(NULL);
10984 // no need to check whether VirtualBox.xml needs saving also since
10985 // we can't have a name change pending at this point
10986 }
10987 else
10988 {
10989 /* delete the saved state file (it might have been already created) */
10990 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
10991 }
10992
10993 /* remove the completed progress object */
10994 mParent->removeProgress(mSnapshotData.mProgressId);
10995
10996 /* clear out the temporary saved state data */
10997 mSnapshotData.mLastState = MachineState_Null;
10998 mSnapshotData.mProgressId.clear();
10999 mSnapshotData.mStateFilePath.setNull();
11000
11001 LogFlowThisFuncLeave();
11002 return rc;
11003}
11004
11005/**
11006 * Locks the attached media.
11007 *
11008 * All attached hard disks are locked for writing and DVD/floppy are locked for
11009 * reading. Parents of attached hard disks (if any) are locked for reading.
11010 *
11011 * This method also performs accessibility check of all media it locks: if some
11012 * media is inaccessible, the method will return a failure and a bunch of
11013 * extended error info objects per each inaccessible medium.
11014 *
11015 * Note that this method is atomic: if it returns a success, all media are
11016 * locked as described above; on failure no media is locked at all (all
11017 * succeeded individual locks will be undone).
11018 *
11019 * This method is intended to be called when the machine is in Starting or
11020 * Restoring state and asserts otherwise.
11021 *
11022 * The locks made by this method must be undone by calling #unlockMedia() when
11023 * no more needed.
11024 */
11025HRESULT SessionMachine::lockMedia()
11026{
11027 AutoCaller autoCaller(this);
11028 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11029
11030 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11031
11032 AssertReturn( mData->mMachineState == MachineState_Starting
11033 || mData->mMachineState == MachineState_Restoring
11034 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11035 /* bail out if trying to lock things with already set up locking */
11036 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11037
11038 MultiResult mrc(S_OK);
11039
11040 /* Collect locking information for all medium objects attached to the VM. */
11041 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11042 it != mMediaData->mAttachments.end();
11043 ++it)
11044 {
11045 MediumAttachment* pAtt = *it;
11046 DeviceType_T devType = pAtt->getType();
11047 Medium *pMedium = pAtt->getMedium();
11048
11049 MediumLockList *pMediumLockList(new MediumLockList());
11050 // There can be attachments without a medium (floppy/dvd), and thus
11051 // it's impossible to create a medium lock list. It still makes sense
11052 // to have the empty medium lock list in the map in case a medium is
11053 // attached later.
11054 if (pMedium != NULL)
11055 {
11056 MediumType_T mediumType = pMedium->getType();
11057 bool fIsReadOnlyImage = devType == DeviceType_DVD
11058 || mediumType == MediumType_Shareable;
11059 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11060
11061 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11062 !fIsReadOnlyImage /* fMediumLockWrite */,
11063 NULL,
11064 *pMediumLockList);
11065 if (FAILED(mrc))
11066 {
11067 delete pMediumLockList;
11068 mData->mSession.mLockedMedia.Clear();
11069 break;
11070 }
11071 }
11072
11073 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11074 if (FAILED(rc))
11075 {
11076 mData->mSession.mLockedMedia.Clear();
11077 mrc = setError(rc,
11078 tr("Collecting locking information for all attached media failed"));
11079 break;
11080 }
11081 }
11082
11083 if (SUCCEEDED(mrc))
11084 {
11085 /* Now lock all media. If this fails, nothing is locked. */
11086 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11087 if (FAILED(rc))
11088 {
11089 mrc = setError(rc,
11090 tr("Locking of attached media failed"));
11091 }
11092 }
11093
11094 return mrc;
11095}
11096
11097/**
11098 * Undoes the locks made by by #lockMedia().
11099 */
11100void SessionMachine::unlockMedia()
11101{
11102 AutoCaller autoCaller(this);
11103 AssertComRCReturnVoid(autoCaller.rc());
11104
11105 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11106
11107 /* we may be holding important error info on the current thread;
11108 * preserve it */
11109 ErrorInfoKeeper eik;
11110
11111 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11112 AssertComRC(rc);
11113}
11114
11115/**
11116 * Helper to change the machine state (reimplementation).
11117 *
11118 * @note Locks this object for writing.
11119 */
11120HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11121{
11122 LogFlowThisFuncEnter();
11123 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11124
11125 AutoCaller autoCaller(this);
11126 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11127
11128 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11129
11130 MachineState_T oldMachineState = mData->mMachineState;
11131
11132 AssertMsgReturn(oldMachineState != aMachineState,
11133 ("oldMachineState=%s, aMachineState=%s\n",
11134 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11135 E_FAIL);
11136
11137 HRESULT rc = S_OK;
11138
11139 int stsFlags = 0;
11140 bool deleteSavedState = false;
11141
11142 /* detect some state transitions */
11143
11144 if ( ( oldMachineState == MachineState_Saved
11145 && aMachineState == MachineState_Restoring)
11146 || ( ( oldMachineState == MachineState_PoweredOff
11147 || oldMachineState == MachineState_Teleported
11148 || oldMachineState == MachineState_Aborted
11149 )
11150 && ( aMachineState == MachineState_TeleportingIn
11151 || aMachineState == MachineState_Starting
11152 )
11153 )
11154 )
11155 {
11156 /* The EMT thread is about to start */
11157
11158 /* Nothing to do here for now... */
11159
11160 /// @todo NEWMEDIA don't let mDVDDrive and other children
11161 /// change anything when in the Starting/Restoring state
11162 }
11163 else if ( ( oldMachineState == MachineState_Running
11164 || oldMachineState == MachineState_Paused
11165 || oldMachineState == MachineState_Teleporting
11166 || oldMachineState == MachineState_LiveSnapshotting
11167 || oldMachineState == MachineState_Stuck
11168 || oldMachineState == MachineState_Starting
11169 || oldMachineState == MachineState_Stopping
11170 || oldMachineState == MachineState_Saving
11171 || oldMachineState == MachineState_Restoring
11172 || oldMachineState == MachineState_TeleportingPausedVM
11173 || oldMachineState == MachineState_TeleportingIn
11174 )
11175 && ( aMachineState == MachineState_PoweredOff
11176 || aMachineState == MachineState_Saved
11177 || aMachineState == MachineState_Teleported
11178 || aMachineState == MachineState_Aborted
11179 )
11180 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11181 * snapshot */
11182 && ( mSnapshotData.mSnapshot.isNull()
11183 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11184 )
11185 )
11186 {
11187 /* The EMT thread has just stopped, unlock attached media. Note that as
11188 * opposed to locking that is done from Console, we do unlocking here
11189 * because the VM process may have aborted before having a chance to
11190 * properly unlock all media it locked. */
11191
11192 unlockMedia();
11193 }
11194
11195 if (oldMachineState == MachineState_Restoring)
11196 {
11197 if (aMachineState != MachineState_Saved)
11198 {
11199 /*
11200 * delete the saved state file once the machine has finished
11201 * restoring from it (note that Console sets the state from
11202 * Restoring to Saved if the VM couldn't restore successfully,
11203 * to give the user an ability to fix an error and retry --
11204 * we keep the saved state file in this case)
11205 */
11206 deleteSavedState = true;
11207 }
11208 }
11209 else if ( oldMachineState == MachineState_Saved
11210 && ( aMachineState == MachineState_PoweredOff
11211 || aMachineState == MachineState_Aborted
11212 || aMachineState == MachineState_Teleported
11213 )
11214 )
11215 {
11216 /*
11217 * delete the saved state after Console::ForgetSavedState() is called
11218 * or if the VM process (owning a direct VM session) crashed while the
11219 * VM was Saved
11220 */
11221
11222 /// @todo (dmik)
11223 // Not sure that deleting the saved state file just because of the
11224 // client death before it attempted to restore the VM is a good
11225 // thing. But when it crashes we need to go to the Aborted state
11226 // which cannot have the saved state file associated... The only
11227 // way to fix this is to make the Aborted condition not a VM state
11228 // but a bool flag: i.e., when a crash occurs, set it to true and
11229 // change the state to PoweredOff or Saved depending on the
11230 // saved state presence.
11231
11232 deleteSavedState = true;
11233 mData->mCurrentStateModified = TRUE;
11234 stsFlags |= SaveSTS_CurStateModified;
11235 }
11236
11237 if ( aMachineState == MachineState_Starting
11238 || aMachineState == MachineState_Restoring
11239 || aMachineState == MachineState_TeleportingIn
11240 )
11241 {
11242 /* set the current state modified flag to indicate that the current
11243 * state is no more identical to the state in the
11244 * current snapshot */
11245 if (!mData->mCurrentSnapshot.isNull())
11246 {
11247 mData->mCurrentStateModified = TRUE;
11248 stsFlags |= SaveSTS_CurStateModified;
11249 }
11250 }
11251
11252 if (deleteSavedState)
11253 {
11254 Assert(!mSSData->mStateFilePath.isEmpty());
11255 RTFileDelete(mSSData->mStateFilePath.c_str());
11256 mSSData->mStateFilePath.setNull();
11257 stsFlags |= SaveSTS_StateFilePath;
11258 }
11259
11260 /* redirect to the underlying peer machine */
11261 mPeer->setMachineState(aMachineState);
11262
11263 if ( aMachineState == MachineState_PoweredOff
11264 || aMachineState == MachineState_Teleported
11265 || aMachineState == MachineState_Aborted
11266 || aMachineState == MachineState_Saved)
11267 {
11268 /* the machine has stopped execution
11269 * (or the saved state file was adopted) */
11270 stsFlags |= SaveSTS_StateTimeStamp;
11271 }
11272
11273 if ( ( oldMachineState == MachineState_PoweredOff
11274 || oldMachineState == MachineState_Aborted
11275 || oldMachineState == MachineState_Teleported
11276 )
11277 && aMachineState == MachineState_Saved)
11278 {
11279 /* the saved state file was adopted */
11280 Assert(!mSSData->mStateFilePath.isEmpty());
11281 stsFlags |= SaveSTS_StateFilePath;
11282 }
11283
11284 if ( aMachineState == MachineState_PoweredOff
11285 || aMachineState == MachineState_Aborted
11286 || aMachineState == MachineState_Teleported)
11287 {
11288 /* Make sure any transient guest properties get removed from the
11289 * property store on shutdown. */
11290
11291 HWData::GuestPropertyList::iterator it;
11292 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11293 if (!fNeedsSaving)
11294 for (it = mHWData->mGuestProperties.begin();
11295 it != mHWData->mGuestProperties.end(); ++it)
11296 if (it->mFlags & guestProp::TRANSIENT)
11297 {
11298 fNeedsSaving = true;
11299 break;
11300 }
11301 if (fNeedsSaving)
11302 {
11303 mData->mCurrentStateModified = TRUE;
11304 stsFlags |= SaveSTS_CurStateModified;
11305 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11306 }
11307 }
11308
11309 rc = saveStateSettings(stsFlags);
11310
11311 if ( ( oldMachineState != MachineState_PoweredOff
11312 && oldMachineState != MachineState_Aborted
11313 && oldMachineState != MachineState_Teleported
11314 )
11315 && ( aMachineState == MachineState_PoweredOff
11316 || aMachineState == MachineState_Aborted
11317 || aMachineState == MachineState_Teleported
11318 )
11319 )
11320 {
11321 /* we've been shut down for any reason */
11322 /* no special action so far */
11323 }
11324
11325 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11326 LogFlowThisFuncLeave();
11327 return rc;
11328}
11329
11330/**
11331 * Sends the current machine state value to the VM process.
11332 *
11333 * @note Locks this object for reading, then calls a client process.
11334 */
11335HRESULT SessionMachine::updateMachineStateOnClient()
11336{
11337 AutoCaller autoCaller(this);
11338 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11339
11340 ComPtr<IInternalSessionControl> directControl;
11341 {
11342 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11343 AssertReturn(!!mData, E_FAIL);
11344 directControl = mData->mSession.mDirectControl;
11345
11346 /* directControl may be already set to NULL here in #OnSessionEnd()
11347 * called too early by the direct session process while there is still
11348 * some operation (like deleting the snapshot) in progress. The client
11349 * process in this case is waiting inside Session::close() for the
11350 * "end session" process object to complete, while #uninit() called by
11351 * #checkForDeath() on the Watcher thread is waiting for the pending
11352 * operation to complete. For now, we accept this inconsitent behavior
11353 * and simply do nothing here. */
11354
11355 if (mData->mSession.mState == SessionState_Unlocking)
11356 return S_OK;
11357
11358 AssertReturn(!directControl.isNull(), E_FAIL);
11359 }
11360
11361 return directControl->UpdateMachineState(mData->mMachineState);
11362}
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