VirtualBox

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

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

FT password

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