VirtualBox

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

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

Main/Machine: RTProcCreate on Windows can finally handle spaces, remove the old workaround

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