VirtualBox

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

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

Main: fix medium detachment quirks during machine register

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

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