VirtualBox

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

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

Main: Make API change to query saved screenshots of any configured monitor in a snapshot. Not implemented, yet.

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