VirtualBox

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

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

Machine::DeleteSettings: Delete the XML backup (VM.xml-prev) as well as any XML files we've failed to commit (VM.xml-tmp).

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