VirtualBox

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

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

Main: reorganize session APIs

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

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