VirtualBox

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

Last change on this file since 30812 was 30812, checked in by vboxsync, 14 years ago

Main/Machine: fix file descriptor leak in ReadLog().

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

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