VirtualBox

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

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

Main/Machine+Snapshot+Medium: Big medium locking cleanup and straightened up the responsibilities between Snapshot and Medium. Rewritten task handling and cleaned up task implementation for medium operations. Implemented IMedium::mergeTo (no way to call it via any frontend yet), making the method parameters similar to IMedium::cloneto. Plus lots of other minor cleanups.

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

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