VirtualBox

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

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

Main: free some bytes in destructors

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