VirtualBox

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

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

Main: Added input validations missing in r64842.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 378.9 KB
Line 
1/* $Id: MachineImpl.cpp 31746 2010-08-18 10:08:52Z 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 if (aSize < 0)
5623 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
5624
5625 AutoCaller autoCaller(this);
5626 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5627
5628 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5629
5630 HRESULT rc = S_OK;
5631 Utf8Str log = queryLogFilename(aIdx);
5632
5633 /* do not unnecessarily hold the lock while doing something which does
5634 * not need the lock and potentially takes a long time. */
5635 alock.release();
5636
5637 /* Limit the chunk size to 32K for now, as that gives better performance
5638 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5639 * One byte expands to approx. 25 bytes of breathtaking XML. */
5640 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5641 com::SafeArray<BYTE> logData(cbData);
5642
5643 RTFILE LogFile;
5644 int vrc = RTFileOpen(&LogFile, log.c_str(),
5645 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5646 if (RT_SUCCESS(vrc))
5647 {
5648 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5649 if (RT_SUCCESS(vrc))
5650 logData.resize(cbData);
5651 else
5652 rc = setError(VBOX_E_IPRT_ERROR,
5653 tr("Could not read log file '%s' (%Rrc)"),
5654 log.c_str(), vrc);
5655 RTFileClose(LogFile);
5656 }
5657 else
5658 rc = setError(VBOX_E_IPRT_ERROR,
5659 tr("Could not open log file '%s' (%Rrc)"),
5660 log.c_str(), vrc);
5661
5662 if (FAILED(rc))
5663 logData.resize(0);
5664 logData.detachTo(ComSafeArrayOutArg(aData));
5665
5666 return rc;
5667}
5668
5669
5670// public methods for internal purposes
5671/////////////////////////////////////////////////////////////////////////////
5672
5673/**
5674 * Adds the given IsModified_* flag to the dirty flags of the machine.
5675 * This must be called either during loadSettings or under the machine write lock.
5676 * @param fl
5677 */
5678void Machine::setModified(uint32_t fl)
5679{
5680 mData->flModifications |= fl;
5681}
5682
5683/**
5684 * Saves the registry entry of this machine to the given configuration node.
5685 *
5686 * @param aEntryNode Node to save the registry entry to.
5687 *
5688 * @note locks this object for reading.
5689 */
5690HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5691{
5692 AutoLimitedCaller autoCaller(this);
5693 AssertComRCReturnRC(autoCaller.rc());
5694
5695 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5696
5697 data.uuid = mData->mUuid;
5698 data.strSettingsFile = mData->m_strConfigFile;
5699
5700 return S_OK;
5701}
5702
5703/**
5704 * Calculates the absolute path of the given path taking the directory of the
5705 * machine settings file as the current directory.
5706 *
5707 * @param aPath Path to calculate the absolute path for.
5708 * @param aResult Where to put the result (used only on success, can be the
5709 * same Utf8Str instance as passed in @a aPath).
5710 * @return IPRT result.
5711 *
5712 * @note Locks this object for reading.
5713 */
5714int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5715{
5716 AutoCaller autoCaller(this);
5717 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5718
5719 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5720
5721 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5722
5723 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5724
5725 strSettingsDir.stripFilename();
5726 char folder[RTPATH_MAX];
5727 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5728 if (RT_SUCCESS(vrc))
5729 aResult = folder;
5730
5731 return vrc;
5732}
5733
5734/**
5735 * Copies strSource to strTarget, making it relative to the machine folder
5736 * if it is a subdirectory thereof, or simply copying it otherwise.
5737 *
5738 * @param strSource Path to evalue and copy.
5739 * @param strTarget Buffer to receive target path.
5740 *
5741 * @note Locks this object for reading.
5742 */
5743void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5744 Utf8Str &strTarget)
5745{
5746 AutoCaller autoCaller(this);
5747 AssertComRCReturn(autoCaller.rc(), (void)0);
5748
5749 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5750
5751 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5752 // use strTarget as a temporary buffer to hold the machine settings dir
5753 strTarget = mData->m_strConfigFileFull;
5754 strTarget.stripFilename();
5755 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5756 // is relative: then append what's left
5757 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
5758 else
5759 // is not relative: then overwrite
5760 strTarget = strSource;
5761}
5762
5763/**
5764 * Returns the full path to the machine's log folder in the
5765 * \a aLogFolder argument.
5766 */
5767void Machine::getLogFolder(Utf8Str &aLogFolder)
5768{
5769 AutoCaller autoCaller(this);
5770 AssertComRCReturnVoid(autoCaller.rc());
5771
5772 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5773
5774 Utf8Str settingsDir;
5775 if (isInOwnDir(&settingsDir))
5776 /* Log folder is <Machines>/<VM_Name>/Logs */
5777 aLogFolder = settingsDir;
5778 else
5779 {
5780 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5781 Assert(!mUserData->m_strSnapshotFolderFull.isEmpty());
5782 aLogFolder = mUserData->m_strSnapshotFolderFull;
5783 }
5784
5785 aLogFolder.append(RTPATH_DELIMITER);
5786 aLogFolder.append("Logs");
5787}
5788
5789/**
5790 * Returns the full path to the machine's log file for an given index.
5791 */
5792Utf8Str Machine::queryLogFilename(ULONG idx)
5793{
5794 Utf8Str logFolder;
5795 getLogFolder(logFolder);
5796 Assert(logFolder.length());
5797 Utf8Str log;
5798 if (idx == 0)
5799 log = Utf8StrFmt("%s%cVBox.log",
5800 logFolder.c_str(), RTPATH_DELIMITER);
5801 else
5802 log = Utf8StrFmt("%s%cVBox.log.%d",
5803 logFolder.c_str(), RTPATH_DELIMITER, idx);
5804 return log;
5805}
5806
5807/**
5808 * @note Locks this object for writing, calls the client process
5809 * (inside the lock).
5810 */
5811HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5812 IN_BSTR aType,
5813 IN_BSTR aEnvironment,
5814 ProgressProxy *aProgress)
5815{
5816 LogFlowThisFuncEnter();
5817
5818 AssertReturn(aControl, E_FAIL);
5819 AssertReturn(aProgress, E_FAIL);
5820
5821 AutoCaller autoCaller(this);
5822 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5823
5824 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5825
5826 if (!mData->mRegistered)
5827 return setError(E_UNEXPECTED,
5828 tr("The machine '%s' is not registered"),
5829 mUserData->s.strName.c_str());
5830
5831 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5832
5833 if ( mData->mSession.mState == SessionState_Locked
5834 || mData->mSession.mState == SessionState_Spawning
5835 || mData->mSession.mState == SessionState_Unlocking)
5836 return setError(VBOX_E_INVALID_OBJECT_STATE,
5837 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
5838 mUserData->s.strName.c_str());
5839
5840 /* may not be busy */
5841 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5842
5843 /* get the path to the executable */
5844 char szPath[RTPATH_MAX];
5845 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5846 size_t sz = strlen(szPath);
5847 szPath[sz++] = RTPATH_DELIMITER;
5848 szPath[sz] = 0;
5849 char *cmd = szPath + sz;
5850 sz = RTPATH_MAX - sz;
5851
5852 int vrc = VINF_SUCCESS;
5853 RTPROCESS pid = NIL_RTPROCESS;
5854
5855 RTENV env = RTENV_DEFAULT;
5856
5857 if (aEnvironment != NULL && *aEnvironment)
5858 {
5859 char *newEnvStr = NULL;
5860
5861 do
5862 {
5863 /* clone the current environment */
5864 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5865 AssertRCBreakStmt(vrc2, vrc = vrc2);
5866
5867 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5868 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5869
5870 /* put new variables to the environment
5871 * (ignore empty variable names here since RTEnv API
5872 * intentionally doesn't do that) */
5873 char *var = newEnvStr;
5874 for (char *p = newEnvStr; *p; ++p)
5875 {
5876 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5877 {
5878 *p = '\0';
5879 if (*var)
5880 {
5881 char *val = strchr(var, '=');
5882 if (val)
5883 {
5884 *val++ = '\0';
5885 vrc2 = RTEnvSetEx(env, var, val);
5886 }
5887 else
5888 vrc2 = RTEnvUnsetEx(env, var);
5889 if (RT_FAILURE(vrc2))
5890 break;
5891 }
5892 var = p + 1;
5893 }
5894 }
5895 if (RT_SUCCESS(vrc2) && *var)
5896 vrc2 = RTEnvPutEx(env, var);
5897
5898 AssertRCBreakStmt(vrc2, vrc = vrc2);
5899 }
5900 while (0);
5901
5902 if (newEnvStr != NULL)
5903 RTStrFree(newEnvStr);
5904 }
5905
5906 Utf8Str strType(aType);
5907
5908 /* Qt is default */
5909#ifdef VBOX_WITH_QTGUI
5910 if (strType == "gui" || strType == "GUI/Qt")
5911 {
5912# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5913 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5914# else
5915 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5916# endif
5917 Assert(sz >= sizeof(VirtualBox_exe));
5918 strcpy(cmd, VirtualBox_exe);
5919
5920 Utf8Str idStr = mData->mUuid.toString();
5921 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5922 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5923 }
5924#else /* !VBOX_WITH_QTGUI */
5925 if (0)
5926 ;
5927#endif /* VBOX_WITH_QTGUI */
5928
5929 else
5930
5931#ifdef VBOX_WITH_VBOXSDL
5932 if (strType == "sdl" || strType == "GUI/SDL")
5933 {
5934 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5935 Assert(sz >= sizeof(VBoxSDL_exe));
5936 strcpy(cmd, VBoxSDL_exe);
5937
5938 Utf8Str idStr = mData->mUuid.toString();
5939 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
5940 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5941 }
5942#else /* !VBOX_WITH_VBOXSDL */
5943 if (0)
5944 ;
5945#endif /* !VBOX_WITH_VBOXSDL */
5946
5947 else
5948
5949#ifdef VBOX_WITH_HEADLESS
5950 if ( strType == "headless"
5951 || strType == "capture"
5952#ifdef VBOX_WITH_VRDP
5953 || strType == "vrdp"
5954#endif
5955 )
5956 {
5957 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
5958 Assert(sz >= sizeof(VBoxHeadless_exe));
5959 strcpy(cmd, VBoxHeadless_exe);
5960
5961 Utf8Str idStr = mData->mUuid.toString();
5962 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
5963 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
5964#ifdef VBOX_WITH_VRDP
5965 if (strType == "headless")
5966 {
5967 unsigned pos = RT_ELEMENTS(args) - 3;
5968 args[pos++] = "--vrdp";
5969 args[pos] = "off";
5970 }
5971#endif
5972 if (strType == "capture")
5973 {
5974 unsigned pos = RT_ELEMENTS(args) - 3;
5975 args[pos] = "--capture";
5976 }
5977 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5978 }
5979#else /* !VBOX_WITH_HEADLESS */
5980 if (0)
5981 ;
5982#endif /* !VBOX_WITH_HEADLESS */
5983 else
5984 {
5985 RTEnvDestroy(env);
5986 return setError(E_INVALIDARG,
5987 tr("Invalid session type: '%s'"),
5988 strType.c_str());
5989 }
5990
5991 RTEnvDestroy(env);
5992
5993 if (RT_FAILURE(vrc))
5994 return setError(VBOX_E_IPRT_ERROR,
5995 tr("Could not launch a process for the machine '%s' (%Rrc)"),
5996 mUserData->s.strName.c_str(), vrc);
5997
5998 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
5999
6000 /*
6001 * Note that we don't leave the lock here before calling the client,
6002 * because it doesn't need to call us back if called with a NULL argument.
6003 * Leaving the lock herer is dangerous because we didn't prepare the
6004 * launch data yet, but the client we've just started may happen to be
6005 * too fast and call openSession() that will fail (because of PID, etc.),
6006 * so that the Machine will never get out of the Spawning session state.
6007 */
6008
6009 /* inform the session that it will be a remote one */
6010 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6011 HRESULT rc = aControl->AssignMachine(NULL);
6012 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6013
6014 if (FAILED(rc))
6015 {
6016 /* restore the session state */
6017 mData->mSession.mState = SessionState_Unlocked;
6018 /* The failure may occur w/o any error info (from RPC), so provide one */
6019 return setError(VBOX_E_VM_ERROR,
6020 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6021 }
6022
6023 /* attach launch data to the machine */
6024 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6025 mData->mSession.mRemoteControls.push_back (aControl);
6026 mData->mSession.mProgress = aProgress;
6027 mData->mSession.mPid = pid;
6028 mData->mSession.mState = SessionState_Spawning;
6029 mData->mSession.mType = strType;
6030
6031 LogFlowThisFuncLeave();
6032 return S_OK;
6033}
6034
6035/**
6036 * Returns @c true if the given machine has an open direct session and returns
6037 * the session machine instance and additional session data (on some platforms)
6038 * if so.
6039 *
6040 * Note that when the method returns @c false, the arguments remain unchanged.
6041 *
6042 * @param aMachine Session machine object.
6043 * @param aControl Direct session control object (optional).
6044 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6045 *
6046 * @note locks this object for reading.
6047 */
6048#if defined(RT_OS_WINDOWS)
6049bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6050 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6051 HANDLE *aIPCSem /*= NULL*/,
6052 bool aAllowClosing /*= false*/)
6053#elif defined(RT_OS_OS2)
6054bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6055 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6056 HMTX *aIPCSem /*= NULL*/,
6057 bool aAllowClosing /*= false*/)
6058#else
6059bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6060 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6061 bool aAllowClosing /*= false*/)
6062#endif
6063{
6064 AutoLimitedCaller autoCaller(this);
6065 AssertComRCReturn(autoCaller.rc(), false);
6066
6067 /* just return false for inaccessible machines */
6068 if (autoCaller.state() != Ready)
6069 return false;
6070
6071 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6072
6073 if ( mData->mSession.mState == SessionState_Locked
6074 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6075 )
6076 {
6077 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6078
6079 aMachine = mData->mSession.mMachine;
6080
6081 if (aControl != NULL)
6082 *aControl = mData->mSession.mDirectControl;
6083
6084#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6085 /* Additional session data */
6086 if (aIPCSem != NULL)
6087 *aIPCSem = aMachine->mIPCSem;
6088#endif
6089 return true;
6090 }
6091
6092 return false;
6093}
6094
6095/**
6096 * Returns @c true if the given machine has an spawning direct session and
6097 * returns and additional session data (on some platforms) if so.
6098 *
6099 * Note that when the method returns @c false, the arguments remain unchanged.
6100 *
6101 * @param aPID PID of the spawned direct session process.
6102 *
6103 * @note locks this object for reading.
6104 */
6105#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6106bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6107#else
6108bool Machine::isSessionSpawning()
6109#endif
6110{
6111 AutoLimitedCaller autoCaller(this);
6112 AssertComRCReturn(autoCaller.rc(), false);
6113
6114 /* just return false for inaccessible machines */
6115 if (autoCaller.state() != Ready)
6116 return false;
6117
6118 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6119
6120 if (mData->mSession.mState == SessionState_Spawning)
6121 {
6122#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6123 /* Additional session data */
6124 if (aPID != NULL)
6125 {
6126 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6127 *aPID = mData->mSession.mPid;
6128 }
6129#endif
6130 return true;
6131 }
6132
6133 return false;
6134}
6135
6136/**
6137 * Called from the client watcher thread to check for unexpected client process
6138 * death during Session_Spawning state (e.g. before it successfully opened a
6139 * direct session).
6140 *
6141 * On Win32 and on OS/2, this method is called only when we've got the
6142 * direct client's process termination notification, so it always returns @c
6143 * true.
6144 *
6145 * On other platforms, this method returns @c true if the client process is
6146 * terminated and @c false if it's still alive.
6147 *
6148 * @note Locks this object for writing.
6149 */
6150bool Machine::checkForSpawnFailure()
6151{
6152 AutoCaller autoCaller(this);
6153 if (!autoCaller.isOk())
6154 {
6155 /* nothing to do */
6156 LogFlowThisFunc(("Already uninitialized!\n"));
6157 return true;
6158 }
6159
6160 /* VirtualBox::addProcessToReap() needs a write lock */
6161 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6162
6163 if (mData->mSession.mState != SessionState_Spawning)
6164 {
6165 /* nothing to do */
6166 LogFlowThisFunc(("Not spawning any more!\n"));
6167 return true;
6168 }
6169
6170 HRESULT rc = S_OK;
6171
6172#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6173
6174 /* the process was already unexpectedly terminated, we just need to set an
6175 * error and finalize session spawning */
6176 rc = setError(E_FAIL,
6177 tr("The virtual machine '%ls' has terminated unexpectedly during startup"),
6178 getName().c_str());
6179#else
6180
6181 /* PID not yet initialized, skip check. */
6182 if (mData->mSession.mPid == NIL_RTPROCESS)
6183 return false;
6184
6185 RTPROCSTATUS status;
6186 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6187 &status);
6188
6189 if (vrc != VERR_PROCESS_RUNNING)
6190 {
6191 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6192 rc = setError(E_FAIL,
6193 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6194 getName().c_str(), status.iStatus);
6195 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6196 rc = setError(E_FAIL,
6197 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6198 getName().c_str(), status.iStatus);
6199 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6200 rc = setError(E_FAIL,
6201 tr("The virtual machine '%s' has terminated abnormally"),
6202 getName().c_str(), status.iStatus);
6203 else
6204 rc = setError(E_FAIL,
6205 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6206 getName().c_str(), rc);
6207 }
6208
6209#endif
6210
6211 if (FAILED(rc))
6212 {
6213 /* Close the remote session, remove the remote control from the list
6214 * and reset session state to Closed (@note keep the code in sync with
6215 * the relevant part in checkForSpawnFailure()). */
6216
6217 Assert(mData->mSession.mRemoteControls.size() == 1);
6218 if (mData->mSession.mRemoteControls.size() == 1)
6219 {
6220 ErrorInfoKeeper eik;
6221 mData->mSession.mRemoteControls.front()->Uninitialize();
6222 }
6223
6224 mData->mSession.mRemoteControls.clear();
6225 mData->mSession.mState = SessionState_Unlocked;
6226
6227 /* finalize the progress after setting the state */
6228 if (!mData->mSession.mProgress.isNull())
6229 {
6230 mData->mSession.mProgress->notifyComplete(rc);
6231 mData->mSession.mProgress.setNull();
6232 }
6233
6234 mParent->addProcessToReap(mData->mSession.mPid);
6235 mData->mSession.mPid = NIL_RTPROCESS;
6236
6237 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6238 return true;
6239 }
6240
6241 return false;
6242}
6243
6244/**
6245 * Checks whether the machine can be registered. If so, commits and saves
6246 * all settings.
6247 *
6248 * @note Must be called from mParent's write lock. Locks this object and
6249 * children for writing.
6250 */
6251HRESULT Machine::prepareRegister()
6252{
6253 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6254
6255 AutoLimitedCaller autoCaller(this);
6256 AssertComRCReturnRC(autoCaller.rc());
6257
6258 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6259
6260 /* wait for state dependants to drop to zero */
6261 ensureNoStateDependencies();
6262
6263 if (!mData->mAccessible)
6264 return setError(VBOX_E_INVALID_OBJECT_STATE,
6265 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6266 mUserData->s.strName.c_str(),
6267 mData->mUuid.toString().c_str());
6268
6269 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6270
6271 if (mData->mRegistered)
6272 return setError(VBOX_E_INVALID_OBJECT_STATE,
6273 tr("The machine '%s' with UUID {%s} is already registered"),
6274 mUserData->s.strName.c_str(),
6275 mData->mUuid.toString().c_str());
6276
6277 HRESULT rc = S_OK;
6278
6279 // Ensure the settings are saved. If we are going to be registered and
6280 // no config file exists yet, create it by calling saveSettings() too.
6281 if ( (mData->flModifications)
6282 || (!mData->pMachineConfigFile->fileExists())
6283 )
6284 {
6285 rc = saveSettings(NULL);
6286 // no need to check whether VirtualBox.xml needs saving too since
6287 // we can't have a machine XML file rename pending
6288 if (FAILED(rc)) return rc;
6289 }
6290
6291 /* more config checking goes here */
6292
6293 if (SUCCEEDED(rc))
6294 {
6295 /* we may have had implicit modifications we want to fix on success */
6296 commit();
6297
6298 mData->mRegistered = true;
6299 }
6300 else
6301 {
6302 /* we may have had implicit modifications we want to cancel on failure*/
6303 rollback(false /* aNotify */);
6304 }
6305
6306 return rc;
6307}
6308
6309/**
6310 * Increases the number of objects dependent on the machine state or on the
6311 * registered state. Guarantees that these two states will not change at least
6312 * until #releaseStateDependency() is called.
6313 *
6314 * Depending on the @a aDepType value, additional state checks may be made.
6315 * These checks will set extended error info on failure. See
6316 * #checkStateDependency() for more info.
6317 *
6318 * If this method returns a failure, the dependency is not added and the caller
6319 * is not allowed to rely on any particular machine state or registration state
6320 * value and may return the failed result code to the upper level.
6321 *
6322 * @param aDepType Dependency type to add.
6323 * @param aState Current machine state (NULL if not interested).
6324 * @param aRegistered Current registered state (NULL if not interested).
6325 *
6326 * @note Locks this object for writing.
6327 */
6328HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6329 MachineState_T *aState /* = NULL */,
6330 BOOL *aRegistered /* = NULL */)
6331{
6332 AutoCaller autoCaller(this);
6333 AssertComRCReturnRC(autoCaller.rc());
6334
6335 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6336
6337 HRESULT rc = checkStateDependency(aDepType);
6338 if (FAILED(rc)) return rc;
6339
6340 {
6341 if (mData->mMachineStateChangePending != 0)
6342 {
6343 /* ensureNoStateDependencies() is waiting for state dependencies to
6344 * drop to zero so don't add more. It may make sense to wait a bit
6345 * and retry before reporting an error (since the pending state
6346 * transition should be really quick) but let's just assert for
6347 * now to see if it ever happens on practice. */
6348
6349 AssertFailed();
6350
6351 return setError(E_ACCESSDENIED,
6352 tr("Machine state change is in progress. Please retry the operation later."));
6353 }
6354
6355 ++mData->mMachineStateDeps;
6356 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6357 }
6358
6359 if (aState)
6360 *aState = mData->mMachineState;
6361 if (aRegistered)
6362 *aRegistered = mData->mRegistered;
6363
6364 return S_OK;
6365}
6366
6367/**
6368 * Decreases the number of objects dependent on the machine state.
6369 * Must always complete the #addStateDependency() call after the state
6370 * dependency is no more necessary.
6371 */
6372void Machine::releaseStateDependency()
6373{
6374 AutoCaller autoCaller(this);
6375 AssertComRCReturnVoid(autoCaller.rc());
6376
6377 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6378
6379 /* releaseStateDependency() w/o addStateDependency()? */
6380 AssertReturnVoid(mData->mMachineStateDeps != 0);
6381 -- mData->mMachineStateDeps;
6382
6383 if (mData->mMachineStateDeps == 0)
6384 {
6385 /* inform ensureNoStateDependencies() that there are no more deps */
6386 if (mData->mMachineStateChangePending != 0)
6387 {
6388 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6389 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6390 }
6391 }
6392}
6393
6394// protected methods
6395/////////////////////////////////////////////////////////////////////////////
6396
6397/**
6398 * Performs machine state checks based on the @a aDepType value. If a check
6399 * fails, this method will set extended error info, otherwise it will return
6400 * S_OK. It is supposed, that on failure, the caller will immedieately return
6401 * the return value of this method to the upper level.
6402 *
6403 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6404 *
6405 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6406 * current state of this machine object allows to change settings of the
6407 * machine (i.e. the machine is not registered, or registered but not running
6408 * and not saved). It is useful to call this method from Machine setters
6409 * before performing any change.
6410 *
6411 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6412 * as for MutableStateDep except that if the machine is saved, S_OK is also
6413 * returned. This is useful in setters which allow changing machine
6414 * properties when it is in the saved state.
6415 *
6416 * @param aDepType Dependency type to check.
6417 *
6418 * @note Non Machine based classes should use #addStateDependency() and
6419 * #releaseStateDependency() methods or the smart AutoStateDependency
6420 * template.
6421 *
6422 * @note This method must be called from under this object's read or write
6423 * lock.
6424 */
6425HRESULT Machine::checkStateDependency(StateDependency aDepType)
6426{
6427 switch (aDepType)
6428 {
6429 case AnyStateDep:
6430 {
6431 break;
6432 }
6433 case MutableStateDep:
6434 {
6435 if ( mData->mRegistered
6436 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6437 || ( mData->mMachineState != MachineState_Paused
6438 && mData->mMachineState != MachineState_Running
6439 && mData->mMachineState != MachineState_Aborted
6440 && mData->mMachineState != MachineState_Teleported
6441 && mData->mMachineState != MachineState_PoweredOff
6442 )
6443 )
6444 )
6445 return setError(VBOX_E_INVALID_VM_STATE,
6446 tr("The machine is not mutable (state is %s)"),
6447 Global::stringifyMachineState(mData->mMachineState));
6448 break;
6449 }
6450 case MutableOrSavedStateDep:
6451 {
6452 if ( mData->mRegistered
6453 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6454 || ( mData->mMachineState != MachineState_Paused
6455 && mData->mMachineState != MachineState_Running
6456 && mData->mMachineState != MachineState_Aborted
6457 && mData->mMachineState != MachineState_Teleported
6458 && mData->mMachineState != MachineState_Saved
6459 && mData->mMachineState != MachineState_PoweredOff
6460 )
6461 )
6462 )
6463 return setError(VBOX_E_INVALID_VM_STATE,
6464 tr("The machine is not mutable (state is %s)"),
6465 Global::stringifyMachineState(mData->mMachineState));
6466 break;
6467 }
6468 }
6469
6470 return S_OK;
6471}
6472
6473/**
6474 * Helper to initialize all associated child objects and allocate data
6475 * structures.
6476 *
6477 * This method must be called as a part of the object's initialization procedure
6478 * (usually done in the #init() method).
6479 *
6480 * @note Must be called only from #init() or from #registeredInit().
6481 */
6482HRESULT Machine::initDataAndChildObjects()
6483{
6484 AutoCaller autoCaller(this);
6485 AssertComRCReturnRC(autoCaller.rc());
6486 AssertComRCReturn(autoCaller.state() == InInit ||
6487 autoCaller.state() == Limited, E_FAIL);
6488
6489 AssertReturn(!mData->mAccessible, E_FAIL);
6490
6491 /* allocate data structures */
6492 mSSData.allocate();
6493 mUserData.allocate();
6494 mHWData.allocate();
6495 mMediaData.allocate();
6496 mStorageControllers.allocate();
6497
6498 /* initialize mOSTypeId */
6499 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6500
6501 /* create associated BIOS settings object */
6502 unconst(mBIOSSettings).createObject();
6503 mBIOSSettings->init(this);
6504
6505#ifdef VBOX_WITH_VRDP
6506 /* create an associated VRDPServer object (default is disabled) */
6507 unconst(mVRDPServer).createObject();
6508 mVRDPServer->init(this);
6509#endif
6510
6511 /* create associated serial port objects */
6512 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6513 {
6514 unconst(mSerialPorts[slot]).createObject();
6515 mSerialPorts[slot]->init(this, slot);
6516 }
6517
6518 /* create associated parallel port objects */
6519 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6520 {
6521 unconst(mParallelPorts[slot]).createObject();
6522 mParallelPorts[slot]->init(this, slot);
6523 }
6524
6525 /* create the audio adapter object (always present, default is disabled) */
6526 unconst(mAudioAdapter).createObject();
6527 mAudioAdapter->init(this);
6528
6529 /* create the USB controller object (always present, default is disabled) */
6530 unconst(mUSBController).createObject();
6531 mUSBController->init(this);
6532
6533 /* create associated network adapter objects */
6534 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6535 {
6536 unconst(mNetworkAdapters[slot]).createObject();
6537 mNetworkAdapters[slot]->init(this, slot);
6538 }
6539
6540 return S_OK;
6541}
6542
6543/**
6544 * Helper to uninitialize all associated child objects and to free all data
6545 * structures.
6546 *
6547 * This method must be called as a part of the object's uninitialization
6548 * procedure (usually done in the #uninit() method).
6549 *
6550 * @note Must be called only from #uninit() or from #registeredInit().
6551 */
6552void Machine::uninitDataAndChildObjects()
6553{
6554 AutoCaller autoCaller(this);
6555 AssertComRCReturnVoid(autoCaller.rc());
6556 AssertComRCReturnVoid( autoCaller.state() == InUninit
6557 || autoCaller.state() == Limited);
6558
6559 /* uninit all children using addDependentChild()/removeDependentChild()
6560 * in their init()/uninit() methods */
6561 uninitDependentChildren();
6562
6563 /* tell all our other child objects we've been uninitialized */
6564
6565 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6566 {
6567 if (mNetworkAdapters[slot])
6568 {
6569 mNetworkAdapters[slot]->uninit();
6570 unconst(mNetworkAdapters[slot]).setNull();
6571 }
6572 }
6573
6574 if (mUSBController)
6575 {
6576 mUSBController->uninit();
6577 unconst(mUSBController).setNull();
6578 }
6579
6580 if (mAudioAdapter)
6581 {
6582 mAudioAdapter->uninit();
6583 unconst(mAudioAdapter).setNull();
6584 }
6585
6586 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6587 {
6588 if (mParallelPorts[slot])
6589 {
6590 mParallelPorts[slot]->uninit();
6591 unconst(mParallelPorts[slot]).setNull();
6592 }
6593 }
6594
6595 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6596 {
6597 if (mSerialPorts[slot])
6598 {
6599 mSerialPorts[slot]->uninit();
6600 unconst(mSerialPorts[slot]).setNull();
6601 }
6602 }
6603
6604#ifdef VBOX_WITH_VRDP
6605 if (mVRDPServer)
6606 {
6607 mVRDPServer->uninit();
6608 unconst(mVRDPServer).setNull();
6609 }
6610#endif
6611
6612 if (mBIOSSettings)
6613 {
6614 mBIOSSettings->uninit();
6615 unconst(mBIOSSettings).setNull();
6616 }
6617
6618 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6619 * instance is uninitialized; SessionMachine instances refer to real
6620 * Machine hard disks). This is necessary for a clean re-initialization of
6621 * the VM after successfully re-checking the accessibility state. Note
6622 * that in case of normal Machine or SnapshotMachine uninitialization (as
6623 * a result of unregistering or deleting the snapshot), outdated hard
6624 * disk attachments will already be uninitialized and deleted, so this
6625 * code will not affect them. */
6626 if ( !!mMediaData
6627 && (!isSessionMachine())
6628 )
6629 {
6630 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6631 it != mMediaData->mAttachments.end();
6632 ++it)
6633 {
6634 ComObjPtr<Medium> hd = (*it)->getMedium();
6635 if (hd.isNull())
6636 continue;
6637 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6638 AssertComRC(rc);
6639 }
6640 }
6641
6642 if (!isSessionMachine() && !isSnapshotMachine())
6643 {
6644 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6645 if (mData->mFirstSnapshot)
6646 {
6647 // snapshots tree is protected by media write lock; strictly
6648 // this isn't necessary here since we're deleting the entire
6649 // machine, but otherwise we assert in Snapshot::uninit()
6650 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6651 mData->mFirstSnapshot->uninit();
6652 mData->mFirstSnapshot.setNull();
6653 }
6654
6655 mData->mCurrentSnapshot.setNull();
6656 }
6657
6658 /* free data structures (the essential mData structure is not freed here
6659 * since it may be still in use) */
6660 mMediaData.free();
6661 mStorageControllers.free();
6662 mHWData.free();
6663 mUserData.free();
6664 mSSData.free();
6665}
6666
6667/**
6668 * Returns a pointer to the Machine object for this machine that acts like a
6669 * parent for complex machine data objects such as shared folders, etc.
6670 *
6671 * For primary Machine objects and for SnapshotMachine objects, returns this
6672 * object's pointer itself. For SessoinMachine objects, returns the peer
6673 * (primary) machine pointer.
6674 */
6675Machine* Machine::getMachine()
6676{
6677 if (isSessionMachine())
6678 return (Machine*)mPeer;
6679 return this;
6680}
6681
6682/**
6683 * Makes sure that there are no machine state dependants. If necessary, waits
6684 * for the number of dependants to drop to zero.
6685 *
6686 * Make sure this method is called from under this object's write lock to
6687 * guarantee that no new dependants may be added when this method returns
6688 * control to the caller.
6689 *
6690 * @note Locks this object for writing. The lock will be released while waiting
6691 * (if necessary).
6692 *
6693 * @warning To be used only in methods that change the machine state!
6694 */
6695void Machine::ensureNoStateDependencies()
6696{
6697 AssertReturnVoid(isWriteLockOnCurrentThread());
6698
6699 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6700
6701 /* Wait for all state dependants if necessary */
6702 if (mData->mMachineStateDeps != 0)
6703 {
6704 /* lazy semaphore creation */
6705 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6706 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6707
6708 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6709 mData->mMachineStateDeps));
6710
6711 ++mData->mMachineStateChangePending;
6712
6713 /* reset the semaphore before waiting, the last dependant will signal
6714 * it */
6715 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6716
6717 alock.leave();
6718
6719 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6720
6721 alock.enter();
6722
6723 -- mData->mMachineStateChangePending;
6724 }
6725}
6726
6727/**
6728 * Changes the machine state and informs callbacks.
6729 *
6730 * This method is not intended to fail so it either returns S_OK or asserts (and
6731 * returns a failure).
6732 *
6733 * @note Locks this object for writing.
6734 */
6735HRESULT Machine::setMachineState(MachineState_T aMachineState)
6736{
6737 LogFlowThisFuncEnter();
6738 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6739
6740 AutoCaller autoCaller(this);
6741 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6742
6743 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6744
6745 /* wait for state dependants to drop to zero */
6746 ensureNoStateDependencies();
6747
6748 if (mData->mMachineState != aMachineState)
6749 {
6750 mData->mMachineState = aMachineState;
6751
6752 RTTimeNow(&mData->mLastStateChange);
6753
6754 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6755 }
6756
6757 LogFlowThisFuncLeave();
6758 return S_OK;
6759}
6760
6761/**
6762 * Searches for a shared folder with the given logical name
6763 * in the collection of shared folders.
6764 *
6765 * @param aName logical name of the shared folder
6766 * @param aSharedFolder where to return the found object
6767 * @param aSetError whether to set the error info if the folder is
6768 * not found
6769 * @return
6770 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6771 *
6772 * @note
6773 * must be called from under the object's lock!
6774 */
6775HRESULT Machine::findSharedFolder(CBSTR aName,
6776 ComObjPtr<SharedFolder> &aSharedFolder,
6777 bool aSetError /* = false */)
6778{
6779 bool found = false;
6780 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6781 !found && it != mHWData->mSharedFolders.end();
6782 ++it)
6783 {
6784 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6785 found = (*it)->getName() == aName;
6786 if (found)
6787 aSharedFolder = *it;
6788 }
6789
6790 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6791
6792 if (aSetError && !found)
6793 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6794
6795 return rc;
6796}
6797
6798/**
6799 * Initializes all machine instance data from the given settings structures
6800 * from XML. The exception is the machine UUID which needs special handling
6801 * depending on the caller's use case, so the caller needs to set that herself.
6802 *
6803 * @param config
6804 * @param fAllowStorage
6805 */
6806HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config)
6807{
6808 // copy name, description, OS type, teleporter, UTC etc.
6809 mUserData->s = config.machineUserData;
6810
6811 // look up the object by Id to check it is valid
6812 ComPtr<IGuestOSType> guestOSType;
6813 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType),
6814 guestOSType.asOutParam());
6815 if (FAILED(rc)) return rc;
6816
6817 // stateFile (optional)
6818 if (config.strStateFile.isEmpty())
6819 mSSData->mStateFilePath.setNull();
6820 else
6821 {
6822 Utf8Str stateFilePathFull(config.strStateFile);
6823 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6824 if (RT_FAILURE(vrc))
6825 return setError(E_FAIL,
6826 tr("Invalid saved state file path '%s' (%Rrc)"),
6827 config.strStateFile.c_str(),
6828 vrc);
6829 mSSData->mStateFilePath = stateFilePathFull;
6830 }
6831
6832 // snapshot folder needs special processing so set it again
6833 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder));
6834 if (FAILED(rc)) return rc;
6835
6836 /* currentStateModified (optional, default is true) */
6837 mData->mCurrentStateModified = config.fCurrentStateModified;
6838
6839 mData->mLastStateChange = config.timeLastStateChange;
6840
6841 /*
6842 * note: all mUserData members must be assigned prior this point because
6843 * we need to commit changes in order to let mUserData be shared by all
6844 * snapshot machine instances.
6845 */
6846 mUserData.commitCopy();
6847
6848 // machine registry, if present (must be loaded before snapshots)
6849 if (config.canHaveOwnMediaRegistry())
6850 {
6851 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
6852 config.mediaRegistry);
6853 if (FAILED(rc)) return rc;
6854 }
6855
6856 /* Snapshot node (optional) */
6857 size_t cRootSnapshots;
6858 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6859 {
6860 // there must be only one root snapshot
6861 Assert(cRootSnapshots == 1);
6862
6863 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6864
6865 rc = loadSnapshot(snap,
6866 config.uuidCurrentSnapshot,
6867 NULL); // no parent == first snapshot
6868 if (FAILED(rc)) return rc;
6869 }
6870
6871 // hardware data
6872 rc = loadHardware(config.hardwareMachine);
6873 if (FAILED(rc)) return rc;
6874
6875 // load storage controllers
6876 rc = loadStorageControllers(config.storageMachine);
6877 if (FAILED(rc)) return rc;
6878
6879 /*
6880 * NOTE: the assignment below must be the last thing to do,
6881 * otherwise it will be not possible to change the settings
6882 * somewehere in the code above because all setters will be
6883 * blocked by checkStateDependency(MutableStateDep).
6884 */
6885
6886 /* set the machine state to Aborted or Saved when appropriate */
6887 if (config.fAborted)
6888 {
6889 Assert(!mSSData->mStateFilePath.isEmpty());
6890 mSSData->mStateFilePath.setNull();
6891
6892 /* no need to use setMachineState() during init() */
6893 mData->mMachineState = MachineState_Aborted;
6894 }
6895 else if (!mSSData->mStateFilePath.isEmpty())
6896 {
6897 /* no need to use setMachineState() during init() */
6898 mData->mMachineState = MachineState_Saved;
6899 }
6900
6901 // after loading settings, we are no longer different from the XML on disk
6902 mData->flModifications = 0;
6903
6904 return S_OK;
6905}
6906
6907/**
6908 * Recursively loads all snapshots starting from the given.
6909 *
6910 * @param aNode <Snapshot> node.
6911 * @param aCurSnapshotId Current snapshot ID from the settings file.
6912 * @param aParentSnapshot Parent snapshot.
6913 */
6914HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6915 const Guid &aCurSnapshotId,
6916 Snapshot *aParentSnapshot)
6917{
6918 AssertReturn(!isSnapshotMachine(), E_FAIL);
6919 AssertReturn(!isSessionMachine(), E_FAIL);
6920
6921 HRESULT rc = S_OK;
6922
6923 Utf8Str strStateFile;
6924 if (!data.strStateFile.isEmpty())
6925 {
6926 /* optional */
6927 strStateFile = data.strStateFile;
6928 int vrc = calculateFullPath(strStateFile, strStateFile);
6929 if (RT_FAILURE(vrc))
6930 return setError(E_FAIL,
6931 tr("Invalid saved state file path '%s' (%Rrc)"),
6932 strStateFile.c_str(),
6933 vrc);
6934 }
6935
6936 /* create a snapshot machine object */
6937 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6938 pSnapshotMachine.createObject();
6939 rc = pSnapshotMachine->init(this,
6940 data.hardware,
6941 data.storage,
6942 data.uuid,
6943 strStateFile);
6944 if (FAILED(rc)) return rc;
6945
6946 /* create a snapshot object */
6947 ComObjPtr<Snapshot> pSnapshot;
6948 pSnapshot.createObject();
6949 /* initialize the snapshot */
6950 rc = pSnapshot->init(mParent, // VirtualBox object
6951 data.uuid,
6952 data.strName,
6953 data.strDescription,
6954 data.timestamp,
6955 pSnapshotMachine,
6956 aParentSnapshot);
6957 if (FAILED(rc)) return rc;
6958
6959 /* memorize the first snapshot if necessary */
6960 if (!mData->mFirstSnapshot)
6961 mData->mFirstSnapshot = pSnapshot;
6962
6963 /* memorize the current snapshot when appropriate */
6964 if ( !mData->mCurrentSnapshot
6965 && pSnapshot->getId() == aCurSnapshotId
6966 )
6967 mData->mCurrentSnapshot = pSnapshot;
6968
6969 // now create the children
6970 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
6971 it != data.llChildSnapshots.end();
6972 ++it)
6973 {
6974 const settings::Snapshot &childData = *it;
6975 // recurse
6976 rc = loadSnapshot(childData,
6977 aCurSnapshotId,
6978 pSnapshot); // parent = the one we created above
6979 if (FAILED(rc)) return rc;
6980 }
6981
6982 return rc;
6983}
6984
6985/**
6986 * @param aNode <Hardware> node.
6987 */
6988HRESULT Machine::loadHardware(const settings::Hardware &data)
6989{
6990 AssertReturn(!isSessionMachine(), E_FAIL);
6991
6992 HRESULT rc = S_OK;
6993
6994 try
6995 {
6996 /* The hardware version attribute (optional). */
6997 mHWData->mHWVersion = data.strVersion;
6998 mHWData->mHardwareUUID = data.uuid;
6999
7000 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7001 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7002 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7003 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7004 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7005 mHWData->mPAEEnabled = data.fPAE;
7006 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7007
7008 mHWData->mCPUCount = data.cCPUs;
7009 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7010 mHWData->mCpuPriority = data.ulCpuPriority;
7011
7012 // cpu
7013 if (mHWData->mCPUHotPlugEnabled)
7014 {
7015 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7016 it != data.llCpus.end();
7017 ++it)
7018 {
7019 const settings::Cpu &cpu = *it;
7020
7021 mHWData->mCPUAttached[cpu.ulId] = true;
7022 }
7023 }
7024
7025 // cpuid leafs
7026 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7027 it != data.llCpuIdLeafs.end();
7028 ++it)
7029 {
7030 const settings::CpuIdLeaf &leaf = *it;
7031
7032 switch (leaf.ulId)
7033 {
7034 case 0x0:
7035 case 0x1:
7036 case 0x2:
7037 case 0x3:
7038 case 0x4:
7039 case 0x5:
7040 case 0x6:
7041 case 0x7:
7042 case 0x8:
7043 case 0x9:
7044 case 0xA:
7045 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7046 break;
7047
7048 case 0x80000000:
7049 case 0x80000001:
7050 case 0x80000002:
7051 case 0x80000003:
7052 case 0x80000004:
7053 case 0x80000005:
7054 case 0x80000006:
7055 case 0x80000007:
7056 case 0x80000008:
7057 case 0x80000009:
7058 case 0x8000000A:
7059 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7060 break;
7061
7062 default:
7063 /* just ignore */
7064 break;
7065 }
7066 }
7067
7068 mHWData->mMemorySize = data.ulMemorySizeMB;
7069 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7070
7071 // boot order
7072 for (size_t i = 0;
7073 i < RT_ELEMENTS(mHWData->mBootOrder);
7074 i++)
7075 {
7076 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7077 if (it == data.mapBootOrder.end())
7078 mHWData->mBootOrder[i] = DeviceType_Null;
7079 else
7080 mHWData->mBootOrder[i] = it->second;
7081 }
7082
7083 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7084 mHWData->mMonitorCount = data.cMonitors;
7085 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7086 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7087 mHWData->mFirmwareType = data.firmwareType;
7088 mHWData->mPointingHidType = data.pointingHidType;
7089 mHWData->mKeyboardHidType = data.keyboardHidType;
7090 mHWData->mHpetEnabled = data.fHpetEnabled;
7091
7092#ifdef VBOX_WITH_VRDP
7093 /* RemoteDisplay */
7094 rc = mVRDPServer->loadSettings(data.vrdpSettings);
7095 if (FAILED(rc)) return rc;
7096#endif
7097
7098 /* BIOS */
7099 rc = mBIOSSettings->loadSettings(data.biosSettings);
7100 if (FAILED(rc)) return rc;
7101
7102 /* USB Controller */
7103 rc = mUSBController->loadSettings(data.usbController);
7104 if (FAILED(rc)) return rc;
7105
7106 // network adapters
7107 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7108 it != data.llNetworkAdapters.end();
7109 ++it)
7110 {
7111 const settings::NetworkAdapter &nic = *it;
7112
7113 /* slot unicity is guaranteed by XML Schema */
7114 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7115 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7116 if (FAILED(rc)) return rc;
7117 }
7118
7119 // serial ports
7120 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7121 it != data.llSerialPorts.end();
7122 ++it)
7123 {
7124 const settings::SerialPort &s = *it;
7125
7126 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7127 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7128 if (FAILED(rc)) return rc;
7129 }
7130
7131 // parallel ports (optional)
7132 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7133 it != data.llParallelPorts.end();
7134 ++it)
7135 {
7136 const settings::ParallelPort &p = *it;
7137
7138 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7139 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7140 if (FAILED(rc)) return rc;
7141 }
7142
7143 /* AudioAdapter */
7144 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7145 if (FAILED(rc)) return rc;
7146
7147 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7148 it != data.llSharedFolders.end();
7149 ++it)
7150 {
7151 const settings::SharedFolder &sf = *it;
7152 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable, sf.fAutoMount);
7153 if (FAILED(rc)) return rc;
7154 }
7155
7156 // Clipboard
7157 mHWData->mClipboardMode = data.clipboardMode;
7158
7159 // guest settings
7160 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7161
7162 // IO settings
7163 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7164 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7165
7166#ifdef VBOX_WITH_GUEST_PROPS
7167 /* Guest properties (optional) */
7168 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7169 it != data.llGuestProperties.end();
7170 ++it)
7171 {
7172 const settings::GuestProperty &prop = *it;
7173 uint32_t fFlags = guestProp::NILFLAG;
7174 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7175 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7176 mHWData->mGuestProperties.push_back(property);
7177 }
7178
7179 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7180#endif /* VBOX_WITH_GUEST_PROPS defined */
7181 }
7182 catch(std::bad_alloc &)
7183 {
7184 return E_OUTOFMEMORY;
7185 }
7186
7187 AssertComRC(rc);
7188 return rc;
7189}
7190
7191 /**
7192 * @param aNode <StorageControllers> node.
7193 */
7194HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7195 const Guid *aSnapshotId /* = NULL */)
7196{
7197 AssertReturn(!isSessionMachine(), E_FAIL);
7198
7199 HRESULT rc = S_OK;
7200
7201 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7202 it != data.llStorageControllers.end();
7203 ++it)
7204 {
7205 const settings::StorageController &ctlData = *it;
7206
7207 ComObjPtr<StorageController> pCtl;
7208 /* Try to find one with the name first. */
7209 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7210 if (SUCCEEDED(rc))
7211 return setError(VBOX_E_OBJECT_IN_USE,
7212 tr("Storage controller named '%s' already exists"),
7213 ctlData.strName.c_str());
7214
7215 pCtl.createObject();
7216 rc = pCtl->init(this,
7217 ctlData.strName,
7218 ctlData.storageBus,
7219 ctlData.ulInstance);
7220 if (FAILED(rc)) return rc;
7221
7222 mStorageControllers->push_back(pCtl);
7223
7224 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7225 if (FAILED(rc)) return rc;
7226
7227 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7228 if (FAILED(rc)) return rc;
7229
7230 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7231 if (FAILED(rc)) return rc;
7232
7233 /* Set IDE emulation settings (only for AHCI controller). */
7234 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7235 {
7236 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7237 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7238 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7239 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7240 )
7241 return rc;
7242 }
7243
7244 /* Load the attached devices now. */
7245 rc = loadStorageDevices(pCtl,
7246 ctlData,
7247 aSnapshotId);
7248 if (FAILED(rc)) return rc;
7249 }
7250
7251 return S_OK;
7252}
7253
7254/**
7255 * @param aNode <HardDiskAttachments> node.
7256 * @param fAllowStorage if false, we produce an error if the config requests media attachments
7257 * (used with importing unregistered machines which cannot have media attachments)
7258 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7259 *
7260 * @note Lock mParent for reading and hard disks for writing before calling.
7261 */
7262HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7263 const settings::StorageController &data,
7264 const Guid *aSnapshotId /*= NULL*/)
7265{
7266 HRESULT rc = S_OK;
7267
7268 /* paranoia: detect duplicate attachments */
7269 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7270 it != data.llAttachedDevices.end();
7271 ++it)
7272 {
7273 const settings::AttachedDevice &ad = *it;
7274
7275 for (settings::AttachedDevicesList::const_iterator it2 = it;
7276 it2 != data.llAttachedDevices.end();
7277 ++it2)
7278 {
7279 if (it == it2)
7280 continue;
7281
7282 const settings::AttachedDevice &ad2 = *it2;
7283
7284 if ( ad.lPort == ad2.lPort
7285 && ad.lDevice == ad2.lDevice)
7286 {
7287 return setError(E_FAIL,
7288 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7289 aStorageController->getName().c_str(),
7290 ad.lPort,
7291 ad.lDevice,
7292 mUserData->s.strName.c_str());
7293 }
7294 }
7295 }
7296
7297 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7298 it != data.llAttachedDevices.end();
7299 ++it)
7300 {
7301 const settings::AttachedDevice &dev = *it;
7302 ComObjPtr<Medium> medium;
7303
7304 switch (dev.deviceType)
7305 {
7306 case DeviceType_Floppy:
7307 case DeviceType_DVD:
7308 rc = mParent->findRemoveableMedium(dev.deviceType, dev.uuid, false /* fRefresh */, medium);
7309 if (FAILED(rc))
7310 return rc;
7311 break;
7312
7313 case DeviceType_HardDisk:
7314 {
7315 /* find a hard disk by UUID */
7316 rc = mParent->findHardDisk(&dev.uuid, Utf8Str::Empty, true /* aDoSetError */, &medium);
7317 if (FAILED(rc))
7318 {
7319 if (isSnapshotMachine())
7320 {
7321 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7322 // so the user knows that the bad disk is in a snapshot somewhere
7323 com::ErrorInfo info;
7324 return setError(E_FAIL,
7325 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7326 aSnapshotId->raw(),
7327 info.getText().raw());
7328 }
7329 else
7330 return rc;
7331 }
7332
7333 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7334
7335 if (medium->getType() == MediumType_Immutable)
7336 {
7337 if (isSnapshotMachine())
7338 return setError(E_FAIL,
7339 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7340 "of the virtual machine '%s' ('%s')"),
7341 medium->getLocationFull().c_str(),
7342 dev.uuid.raw(),
7343 aSnapshotId->raw(),
7344 mUserData->s.strName.c_str(),
7345 mData->m_strConfigFileFull.c_str());
7346
7347 return setError(E_FAIL,
7348 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7349 medium->getLocationFull().c_str(),
7350 dev.uuid.raw(),
7351 mUserData->s.strName.c_str(),
7352 mData->m_strConfigFileFull.c_str());
7353 }
7354
7355 if ( !isSnapshotMachine()
7356 && medium->getChildren().size() != 0
7357 )
7358 return setError(E_FAIL,
7359 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7360 "because it has %d differencing child hard disks"),
7361 medium->getLocationFull().c_str(),
7362 dev.uuid.raw(),
7363 mUserData->s.strName.c_str(),
7364 mData->m_strConfigFileFull.c_str(),
7365 medium->getChildren().size());
7366
7367 if (findAttachment(mMediaData->mAttachments,
7368 medium))
7369 return setError(E_FAIL,
7370 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7371 medium->getLocationFull().c_str(),
7372 dev.uuid.raw(),
7373 mUserData->s.strName.c_str(),
7374 mData->m_strConfigFileFull.c_str());
7375
7376 break;
7377 }
7378
7379 default:
7380 return setError(E_FAIL,
7381 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7382 medium->getLocationFull().c_str(),
7383 mUserData->s.strName.c_str(),
7384 mData->m_strConfigFileFull.c_str());
7385 }
7386
7387 if (FAILED(rc))
7388 break;
7389
7390 const Bstr controllerName = aStorageController->getName();
7391 ComObjPtr<MediumAttachment> pAttachment;
7392 pAttachment.createObject();
7393 rc = pAttachment->init(this,
7394 medium,
7395 controllerName,
7396 dev.lPort,
7397 dev.lDevice,
7398 dev.deviceType,
7399 dev.fPassThrough,
7400 dev.ulBandwidthLimit);
7401 if (FAILED(rc)) break;
7402
7403 /* associate the medium with this machine and snapshot */
7404 if (!medium.isNull())
7405 {
7406 if (isSnapshotMachine())
7407 rc = medium->addBackReference(mData->mUuid, *aSnapshotId);
7408 else
7409 rc = medium->addBackReference(mData->mUuid);
7410 }
7411
7412 if (FAILED(rc))
7413 break;
7414
7415 /* back up mMediaData to let registeredInit() properly rollback on failure
7416 * (= limited accessibility) */
7417 setModified(IsModified_Storage);
7418 mMediaData.backup();
7419 mMediaData->mAttachments.push_back(pAttachment);
7420 }
7421
7422 return rc;
7423}
7424
7425/**
7426 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7427 *
7428 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7429 * @param aSnapshot where to return the found snapshot
7430 * @param aSetError true to set extended error info on failure
7431 */
7432HRESULT Machine::findSnapshot(const Guid &aId,
7433 ComObjPtr<Snapshot> &aSnapshot,
7434 bool aSetError /* = false */)
7435{
7436 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7437
7438 if (!mData->mFirstSnapshot)
7439 {
7440 if (aSetError)
7441 return setError(E_FAIL,
7442 tr("This machine does not have any snapshots"));
7443 return E_FAIL;
7444 }
7445
7446 if (aId.isEmpty())
7447 aSnapshot = mData->mFirstSnapshot;
7448 else
7449 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
7450
7451 if (!aSnapshot)
7452 {
7453 if (aSetError)
7454 return setError(E_FAIL,
7455 tr("Could not find a snapshot with UUID {%s}"),
7456 aId.toString().c_str());
7457 return E_FAIL;
7458 }
7459
7460 return S_OK;
7461}
7462
7463/**
7464 * Returns the snapshot with the given name or fails of no such snapshot.
7465 *
7466 * @param aName snapshot name to find
7467 * @param aSnapshot where to return the found snapshot
7468 * @param aSetError true to set extended error info on failure
7469 */
7470HRESULT Machine::findSnapshot(IN_BSTR aName,
7471 ComObjPtr<Snapshot> &aSnapshot,
7472 bool aSetError /* = false */)
7473{
7474 AssertReturn(aName, E_INVALIDARG);
7475
7476 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7477
7478 if (!mData->mFirstSnapshot)
7479 {
7480 if (aSetError)
7481 return setError(VBOX_E_OBJECT_NOT_FOUND,
7482 tr("This machine does not have any snapshots"));
7483 return VBOX_E_OBJECT_NOT_FOUND;
7484 }
7485
7486 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aName);
7487
7488 if (!aSnapshot)
7489 {
7490 if (aSetError)
7491 return setError(VBOX_E_OBJECT_NOT_FOUND,
7492 tr("Could not find a snapshot named '%ls'"), aName);
7493 return VBOX_E_OBJECT_NOT_FOUND;
7494 }
7495
7496 return S_OK;
7497}
7498
7499/**
7500 * Returns a storage controller object with the given name.
7501 *
7502 * @param aName storage controller name to find
7503 * @param aStorageController where to return the found storage controller
7504 * @param aSetError true to set extended error info on failure
7505 */
7506HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7507 ComObjPtr<StorageController> &aStorageController,
7508 bool aSetError /* = false */)
7509{
7510 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7511
7512 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7513 it != mStorageControllers->end();
7514 ++it)
7515 {
7516 if ((*it)->getName() == aName)
7517 {
7518 aStorageController = (*it);
7519 return S_OK;
7520 }
7521 }
7522
7523 if (aSetError)
7524 return setError(VBOX_E_OBJECT_NOT_FOUND,
7525 tr("Could not find a storage controller named '%s'"),
7526 aName.c_str());
7527 return VBOX_E_OBJECT_NOT_FOUND;
7528}
7529
7530HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7531 MediaData::AttachmentList &atts)
7532{
7533 AutoCaller autoCaller(this);
7534 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7535
7536 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7537
7538 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7539 it != mMediaData->mAttachments.end();
7540 ++it)
7541 {
7542 const ComObjPtr<MediumAttachment> &pAtt = *it;
7543
7544 // should never happen, but deal with NULL pointers in the list.
7545 AssertStmt(!pAtt.isNull(), continue);
7546
7547 // getControllerName() needs caller+read lock
7548 AutoCaller autoAttCaller(pAtt);
7549 if (FAILED(autoAttCaller.rc()))
7550 {
7551 atts.clear();
7552 return autoAttCaller.rc();
7553 }
7554 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7555
7556 if (pAtt->getControllerName() == aName)
7557 atts.push_back(pAtt);
7558 }
7559
7560 return S_OK;
7561}
7562
7563/**
7564 * Helper for #saveSettings. Cares about renaming the settings directory and
7565 * file if the machine name was changed and about creating a new settings file
7566 * if this is a new machine.
7567 *
7568 * @note Must be never called directly but only from #saveSettings().
7569 */
7570HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7571{
7572 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7573
7574 HRESULT rc = S_OK;
7575
7576 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7577
7578 /* attempt to rename the settings file if machine name is changed */
7579 if ( mUserData->s.fNameSync
7580 && mUserData.isBackedUp()
7581 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7582 )
7583 {
7584 bool dirRenamed = false;
7585 bool fileRenamed = false;
7586
7587 Utf8Str configFile, newConfigFile;
7588 Utf8Str configDir, newConfigDir;
7589
7590 do
7591 {
7592 int vrc = VINF_SUCCESS;
7593
7594 Utf8Str name = mUserData.backedUpData()->s.strName;
7595 Utf8Str newName = mUserData->s.strName;
7596
7597 configFile = mData->m_strConfigFileFull;
7598
7599 /* first, rename the directory if it matches the machine name */
7600 configDir = configFile;
7601 configDir.stripFilename();
7602 newConfigDir = configDir;
7603 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7604 {
7605 newConfigDir.stripFilename();
7606 newConfigDir.append(RTPATH_DELIMITER);
7607 newConfigDir.append(newName);
7608 /* new dir and old dir cannot be equal here because of 'if'
7609 * above and because name != newName */
7610 Assert(configDir != newConfigDir);
7611 if (!fSettingsFileIsNew)
7612 {
7613 /* perform real rename only if the machine is not new */
7614 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7615 if (RT_FAILURE(vrc))
7616 {
7617 rc = setError(E_FAIL,
7618 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7619 configDir.c_str(),
7620 newConfigDir.c_str(),
7621 vrc);
7622 break;
7623 }
7624 dirRenamed = true;
7625 }
7626 }
7627
7628 newConfigFile = Utf8StrFmt("%s%c%s.xml",
7629 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7630
7631 /* then try to rename the settings file itself */
7632 if (newConfigFile != configFile)
7633 {
7634 /* get the path to old settings file in renamed directory */
7635 configFile = Utf8StrFmt("%s%c%s",
7636 newConfigDir.c_str(),
7637 RTPATH_DELIMITER,
7638 RTPathFilename(configFile.c_str()));
7639 if (!fSettingsFileIsNew)
7640 {
7641 /* perform real rename only if the machine is not new */
7642 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7643 if (RT_FAILURE(vrc))
7644 {
7645 rc = setError(E_FAIL,
7646 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7647 configFile.c_str(),
7648 newConfigFile.c_str(),
7649 vrc);
7650 break;
7651 }
7652 fileRenamed = true;
7653 }
7654 }
7655
7656 /* update m_strConfigFileFull amd mConfigFile */
7657 mData->m_strConfigFileFull = newConfigFile;
7658 // compute the relative path too
7659 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7660
7661 // store the old and new so that VirtualBox::saveSettings() can update
7662 // the media registry
7663 if ( mData->mRegistered
7664 && configDir != newConfigDir)
7665 {
7666 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7667
7668 if (pfNeedsGlobalSaveSettings)
7669 *pfNeedsGlobalSaveSettings = true;
7670 }
7671
7672 /* update the snapshot folder */
7673 if (RTPathStartsWith(mUserData->m_strSnapshotFolderFull.c_str(),
7674 configDir.c_str()))
7675 {
7676 mUserData->m_strSnapshotFolderFull = Utf8StrFmt("%s%s",
7677 newConfigDir.c_str(),
7678 mUserData->m_strSnapshotFolderFull.c_str() + configDir.length());
7679 copyPathRelativeToMachine(mUserData->m_strSnapshotFolderFull,
7680 mUserData->s.strSnapshotFolder);
7681 }
7682
7683 /* update the saved state file path */
7684 Utf8Str path = mSSData->mStateFilePath;
7685 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7686 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
7687 newConfigDir.c_str(),
7688 path.c_str() + configDir.length());
7689
7690 /* Update saved state file paths of all online snapshots.
7691 * Note that saveSettings() will recognize name change
7692 * and will save all snapshots in this case. */
7693 if (mData->mFirstSnapshot)
7694 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7695 newConfigDir.c_str());
7696 }
7697 while (0);
7698
7699 if (FAILED(rc))
7700 {
7701 /* silently try to rename everything back */
7702 if (fileRenamed)
7703 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
7704 if (dirRenamed)
7705 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
7706 }
7707
7708 if (FAILED(rc)) return rc;
7709 }
7710
7711 if (fSettingsFileIsNew)
7712 {
7713 /* create a virgin config file */
7714 int vrc = VINF_SUCCESS;
7715
7716 /* ensure the settings directory exists */
7717 Utf8Str path(mData->m_strConfigFileFull);
7718 path.stripFilename();
7719 if (!RTDirExists(path.c_str()))
7720 {
7721 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7722 if (RT_FAILURE(vrc))
7723 {
7724 return setError(E_FAIL,
7725 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7726 path.c_str(),
7727 vrc);
7728 }
7729 }
7730
7731 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7732 path = Utf8Str(mData->m_strConfigFileFull);
7733 RTFILE f = NIL_RTFILE;
7734 vrc = RTFileOpen(&f, path.c_str(),
7735 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7736 if (RT_FAILURE(vrc))
7737 return setError(E_FAIL,
7738 tr("Could not create the settings file '%s' (%Rrc)"),
7739 path.c_str(),
7740 vrc);
7741 RTFileClose(f);
7742 }
7743
7744 return rc;
7745}
7746
7747/**
7748 * Saves and commits machine data, user data and hardware data.
7749 *
7750 * Note that on failure, the data remains uncommitted.
7751 *
7752 * @a aFlags may combine the following flags:
7753 *
7754 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7755 * Used when saving settings after an operation that makes them 100%
7756 * correspond to the settings from the current snapshot.
7757 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7758 * #isReallyModified() returns false. This is necessary for cases when we
7759 * change machine data directly, not through the backup()/commit() mechanism.
7760 * - SaveS_Force: settings will be saved without doing a deep compare of the
7761 * settings structures. This is used when this is called because snapshots
7762 * have changed to avoid the overhead of the deep compare.
7763 *
7764 * @note Must be called from under this object's write lock. Locks children for
7765 * writing.
7766 *
7767 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7768 * initialized to false and that will be set to true by this function if
7769 * the caller must invoke VirtualBox::saveSettings() because the global
7770 * settings have changed. This will happen if a machine rename has been
7771 * saved and the global machine and media registries will therefore need
7772 * updating.
7773 */
7774HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7775 int aFlags /*= 0*/)
7776{
7777 LogFlowThisFuncEnter();
7778
7779 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7780
7781 /* make sure child objects are unable to modify the settings while we are
7782 * saving them */
7783 ensureNoStateDependencies();
7784
7785 AssertReturn(!isSnapshotMachine(),
7786 E_FAIL);
7787
7788 HRESULT rc = S_OK;
7789 bool fNeedsWrite = false;
7790
7791 /* First, prepare to save settings. It will care about renaming the
7792 * settings directory and file if the machine name was changed and about
7793 * creating a new settings file if this is a new machine. */
7794 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7795 if (FAILED(rc)) return rc;
7796
7797 // keep a pointer to the current settings structures
7798 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7799 settings::MachineConfigFile *pNewConfig = NULL;
7800
7801 try
7802 {
7803 // make a fresh one to have everyone write stuff into
7804 pNewConfig = new settings::MachineConfigFile(NULL);
7805 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7806
7807 // now go and copy all the settings data from COM to the settings structures
7808 // (this calles saveSettings() on all the COM objects in the machine)
7809 copyMachineDataToSettings(*pNewConfig);
7810
7811 if (aFlags & SaveS_ResetCurStateModified)
7812 {
7813 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7814 mData->mCurrentStateModified = FALSE;
7815 fNeedsWrite = true; // always, no need to compare
7816 }
7817 else if (aFlags & SaveS_Force)
7818 {
7819 fNeedsWrite = true; // always, no need to compare
7820 }
7821 else
7822 {
7823 if (!mData->mCurrentStateModified)
7824 {
7825 // do a deep compare of the settings that we just saved with the settings
7826 // previously stored in the config file; this invokes MachineConfigFile::operator==
7827 // which does a deep compare of all the settings, which is expensive but less expensive
7828 // than writing out XML in vain
7829 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7830
7831 // could still be modified if any settings changed
7832 mData->mCurrentStateModified = fAnySettingsChanged;
7833
7834 fNeedsWrite = fAnySettingsChanged;
7835 }
7836 else
7837 fNeedsWrite = true;
7838 }
7839
7840 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7841
7842 if (fNeedsWrite)
7843 // now spit it all out!
7844 pNewConfig->write(mData->m_strConfigFileFull);
7845
7846 mData->pMachineConfigFile = pNewConfig;
7847 delete pOldConfig;
7848 commit();
7849
7850 // after saving settings, we are no longer different from the XML on disk
7851 mData->flModifications = 0;
7852 }
7853 catch (HRESULT err)
7854 {
7855 // we assume that error info is set by the thrower
7856 rc = err;
7857
7858 // restore old config
7859 delete pNewConfig;
7860 mData->pMachineConfigFile = pOldConfig;
7861 }
7862 catch (...)
7863 {
7864 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7865 }
7866
7867 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7868 {
7869 /* Fire the data change event, even on failure (since we've already
7870 * committed all data). This is done only for SessionMachines because
7871 * mutable Machine instances are always not registered (i.e. private
7872 * to the client process that creates them) and thus don't need to
7873 * inform callbacks. */
7874 if (isSessionMachine())
7875 mParent->onMachineDataChange(mData->mUuid);
7876 }
7877
7878 LogFlowThisFunc(("rc=%08X\n", rc));
7879 LogFlowThisFuncLeave();
7880 return rc;
7881}
7882
7883/**
7884 * Implementation for saving the machine settings into the given
7885 * settings::MachineConfigFile instance. This copies machine extradata
7886 * from the previous machine config file in the instance data, if any.
7887 *
7888 * This gets called from two locations:
7889 *
7890 * -- Machine::saveSettings(), during the regular XML writing;
7891 *
7892 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7893 * exported to OVF and we write the VirtualBox proprietary XML
7894 * into a <vbox:Machine> tag.
7895 *
7896 * This routine fills all the fields in there, including snapshots, *except*
7897 * for the following:
7898 *
7899 * -- fCurrentStateModified. There is some special logic associated with that.
7900 *
7901 * The caller can then call MachineConfigFile::write() or do something else
7902 * with it.
7903 *
7904 * Caller must hold the machine lock!
7905 *
7906 * This throws XML errors and HRESULT, so the caller must have a catch block!
7907 */
7908void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7909{
7910 // deep copy extradata
7911 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7912
7913 config.uuid = mData->mUuid;
7914
7915 // copy name, description, OS type, teleport, UTC etc.
7916 config.machineUserData = mUserData->s;
7917
7918 if ( mData->mMachineState == MachineState_Saved
7919 || mData->mMachineState == MachineState_Restoring
7920 // when deleting a snapshot we may or may not have a saved state in the current state,
7921 // so let's not assert here please
7922 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7923 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7924 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7925 && (!mSSData->mStateFilePath.isEmpty())
7926 )
7927 )
7928 {
7929 Assert(!mSSData->mStateFilePath.isEmpty());
7930 /* try to make the file name relative to the settings file dir */
7931 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
7932 }
7933 else
7934 {
7935 Assert(mSSData->mStateFilePath.isEmpty());
7936 config.strStateFile.setNull();
7937 }
7938
7939 if (mData->mCurrentSnapshot)
7940 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7941 else
7942 config.uuidCurrentSnapshot.clear();
7943
7944 config.timeLastStateChange = mData->mLastStateChange;
7945 config.fAborted = (mData->mMachineState == MachineState_Aborted);
7946 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
7947
7948 HRESULT rc = saveHardware(config.hardwareMachine);
7949 if (FAILED(rc)) throw rc;
7950
7951 rc = saveStorageControllers(config.storageMachine);
7952 if (FAILED(rc)) throw rc;
7953
7954 // save machine's media registry if this is VirtualBox 3.3 or later
7955 if (config.canHaveOwnMediaRegistry())
7956 mParent->saveMediaRegistry(config.mediaRegistry,
7957 getId()); // only media with registry ID == machine UUID
7958 // this throws HRESULT
7959
7960 // save snapshots
7961 rc = saveAllSnapshots(config);
7962 if (FAILED(rc)) throw rc;
7963}
7964
7965/**
7966 * Saves all snapshots of the machine into the given machine config file. Called
7967 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
7968 * @param config
7969 * @return
7970 */
7971HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
7972{
7973 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7974
7975 HRESULT rc = S_OK;
7976
7977 try
7978 {
7979 config.llFirstSnapshot.clear();
7980
7981 if (mData->mFirstSnapshot)
7982 {
7983 settings::Snapshot snapNew;
7984 config.llFirstSnapshot.push_back(snapNew);
7985
7986 // get reference to the fresh copy of the snapshot on the list and
7987 // work on that copy directly to avoid excessive copying later
7988 settings::Snapshot &snap = config.llFirstSnapshot.front();
7989
7990 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
7991 if (FAILED(rc)) throw rc;
7992 }
7993
7994// if (mType == IsSessionMachine)
7995// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
7996
7997 }
7998 catch (HRESULT err)
7999 {
8000 /* we assume that error info is set by the thrower */
8001 rc = err;
8002 }
8003 catch (...)
8004 {
8005 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8006 }
8007
8008 return rc;
8009}
8010
8011/**
8012 * Saves the VM hardware configuration. It is assumed that the
8013 * given node is empty.
8014 *
8015 * @param aNode <Hardware> node to save the VM hardware confguration to.
8016 */
8017HRESULT Machine::saveHardware(settings::Hardware &data)
8018{
8019 HRESULT rc = S_OK;
8020
8021 try
8022 {
8023 /* The hardware version attribute (optional).
8024 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8025 if ( mHWData->mHWVersion == "1"
8026 && mSSData->mStateFilePath.isEmpty()
8027 )
8028 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. */
8029
8030 data.strVersion = mHWData->mHWVersion;
8031 data.uuid = mHWData->mHardwareUUID;
8032
8033 // CPU
8034 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8035 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8036 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8037 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8038 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8039 data.fPAE = !!mHWData->mPAEEnabled;
8040 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8041
8042 /* Standard and Extended CPUID leafs. */
8043 data.llCpuIdLeafs.clear();
8044 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8045 {
8046 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8047 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8048 }
8049 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8050 {
8051 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8052 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8053 }
8054
8055 data.cCPUs = mHWData->mCPUCount;
8056 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8057 data.ulCpuPriority = mHWData->mCpuPriority;
8058
8059 data.llCpus.clear();
8060 if (data.fCpuHotPlug)
8061 {
8062 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8063 {
8064 if (mHWData->mCPUAttached[idx])
8065 {
8066 settings::Cpu cpu;
8067 cpu.ulId = idx;
8068 data.llCpus.push_back(cpu);
8069 }
8070 }
8071 }
8072
8073 // memory
8074 data.ulMemorySizeMB = mHWData->mMemorySize;
8075 data.fPageFusionEnabled = mHWData->mPageFusionEnabled;
8076
8077 // firmware
8078 data.firmwareType = mHWData->mFirmwareType;
8079
8080 // HID
8081 data.pointingHidType = mHWData->mPointingHidType;
8082 data.keyboardHidType = mHWData->mKeyboardHidType;
8083
8084 // HPET
8085 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8086
8087 // boot order
8088 data.mapBootOrder.clear();
8089 for (size_t i = 0;
8090 i < RT_ELEMENTS(mHWData->mBootOrder);
8091 ++i)
8092 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8093
8094 // display
8095 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8096 data.cMonitors = mHWData->mMonitorCount;
8097 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8098 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8099
8100#ifdef VBOX_WITH_VRDP
8101 /* VRDP settings (optional) */
8102 rc = mVRDPServer->saveSettings(data.vrdpSettings);
8103 if (FAILED(rc)) throw rc;
8104#endif
8105
8106 /* BIOS (required) */
8107 rc = mBIOSSettings->saveSettings(data.biosSettings);
8108 if (FAILED(rc)) throw rc;
8109
8110 /* USB Controller (required) */
8111 rc = mUSBController->saveSettings(data.usbController);
8112 if (FAILED(rc)) throw rc;
8113
8114 /* Network adapters (required) */
8115 data.llNetworkAdapters.clear();
8116 for (ULONG slot = 0;
8117 slot < RT_ELEMENTS(mNetworkAdapters);
8118 ++slot)
8119 {
8120 settings::NetworkAdapter nic;
8121 nic.ulSlot = slot;
8122 rc = mNetworkAdapters[slot]->saveSettings(nic);
8123 if (FAILED(rc)) throw rc;
8124
8125 data.llNetworkAdapters.push_back(nic);
8126 }
8127
8128 /* Serial ports */
8129 data.llSerialPorts.clear();
8130 for (ULONG slot = 0;
8131 slot < RT_ELEMENTS(mSerialPorts);
8132 ++slot)
8133 {
8134 settings::SerialPort s;
8135 s.ulSlot = slot;
8136 rc = mSerialPorts[slot]->saveSettings(s);
8137 if (FAILED(rc)) return rc;
8138
8139 data.llSerialPorts.push_back(s);
8140 }
8141
8142 /* Parallel ports */
8143 data.llParallelPorts.clear();
8144 for (ULONG slot = 0;
8145 slot < RT_ELEMENTS(mParallelPorts);
8146 ++slot)
8147 {
8148 settings::ParallelPort p;
8149 p.ulSlot = slot;
8150 rc = mParallelPorts[slot]->saveSettings(p);
8151 if (FAILED(rc)) return rc;
8152
8153 data.llParallelPorts.push_back(p);
8154 }
8155
8156 /* Audio adapter */
8157 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8158 if (FAILED(rc)) return rc;
8159
8160 /* Shared folders */
8161 data.llSharedFolders.clear();
8162 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8163 it != mHWData->mSharedFolders.end();
8164 ++it)
8165 {
8166 ComObjPtr<SharedFolder> pFolder = *it;
8167 settings::SharedFolder sf;
8168 sf.strName = pFolder->getName();
8169 sf.strHostPath = pFolder->getHostPath();
8170 sf.fWritable = !!pFolder->isWritable();
8171 sf.fAutoMount = !!pFolder->isAutoMounted();
8172
8173 data.llSharedFolders.push_back(sf);
8174 }
8175
8176 // clipboard
8177 data.clipboardMode = mHWData->mClipboardMode;
8178
8179 /* Guest */
8180 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8181
8182 // IO settings
8183 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8184 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8185
8186 // guest properties
8187 data.llGuestProperties.clear();
8188#ifdef VBOX_WITH_GUEST_PROPS
8189 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8190 it != mHWData->mGuestProperties.end();
8191 ++it)
8192 {
8193 HWData::GuestProperty property = *it;
8194
8195 /* Remove transient guest properties at shutdown unless we
8196 * are saving state */
8197 if ( ( mData->mMachineState == MachineState_PoweredOff
8198 || mData->mMachineState == MachineState_Aborted
8199 || mData->mMachineState == MachineState_Teleported)
8200 && property.mFlags & guestProp::TRANSIENT)
8201 continue;
8202 settings::GuestProperty prop;
8203 prop.strName = property.strName;
8204 prop.strValue = property.strValue;
8205 prop.timestamp = property.mTimestamp;
8206 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8207 guestProp::writeFlags(property.mFlags, szFlags);
8208 prop.strFlags = szFlags;
8209
8210 data.llGuestProperties.push_back(prop);
8211 }
8212
8213 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8214 /* I presume this doesn't require a backup(). */
8215 mData->mGuestPropertiesModified = FALSE;
8216#endif /* VBOX_WITH_GUEST_PROPS defined */
8217 }
8218 catch(std::bad_alloc &)
8219 {
8220 return E_OUTOFMEMORY;
8221 }
8222
8223 AssertComRC(rc);
8224 return rc;
8225}
8226
8227/**
8228 * Saves the storage controller configuration.
8229 *
8230 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
8231 */
8232HRESULT Machine::saveStorageControllers(settings::Storage &data)
8233{
8234 data.llStorageControllers.clear();
8235
8236 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8237 it != mStorageControllers->end();
8238 ++it)
8239 {
8240 HRESULT rc;
8241 ComObjPtr<StorageController> pCtl = *it;
8242
8243 settings::StorageController ctl;
8244 ctl.strName = pCtl->getName();
8245 ctl.controllerType = pCtl->getControllerType();
8246 ctl.storageBus = pCtl->getStorageBus();
8247 ctl.ulInstance = pCtl->getInstance();
8248
8249 /* Save the port count. */
8250 ULONG portCount;
8251 rc = pCtl->COMGETTER(PortCount)(&portCount);
8252 ComAssertComRCRet(rc, rc);
8253 ctl.ulPortCount = portCount;
8254
8255 /* Save fUseHostIOCache */
8256 BOOL fUseHostIOCache;
8257 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8258 ComAssertComRCRet(rc, rc);
8259 ctl.fUseHostIOCache = !!fUseHostIOCache;
8260
8261 /* Save IDE emulation settings. */
8262 if (ctl.controllerType == StorageControllerType_IntelAhci)
8263 {
8264 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8265 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8266 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8267 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8268 )
8269 ComAssertComRCRet(rc, rc);
8270 }
8271
8272 /* save the devices now. */
8273 rc = saveStorageDevices(pCtl, ctl);
8274 ComAssertComRCRet(rc, rc);
8275
8276 data.llStorageControllers.push_back(ctl);
8277 }
8278
8279 return S_OK;
8280}
8281
8282/**
8283 * Saves the hard disk confguration.
8284 */
8285HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8286 settings::StorageController &data)
8287{
8288 MediaData::AttachmentList atts;
8289
8290 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()), atts);
8291 if (FAILED(rc)) return rc;
8292
8293 data.llAttachedDevices.clear();
8294 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8295 it != atts.end();
8296 ++it)
8297 {
8298 settings::AttachedDevice dev;
8299
8300 MediumAttachment *pAttach = *it;
8301 Medium *pMedium = pAttach->getMedium();
8302
8303 dev.deviceType = pAttach->getType();
8304 dev.lPort = pAttach->getPort();
8305 dev.lDevice = pAttach->getDevice();
8306 if (pMedium)
8307 {
8308 if (pMedium->isHostDrive())
8309 dev.strHostDriveSrc = pMedium->getLocation();
8310 else
8311 dev.uuid = pMedium->getId();
8312 dev.fPassThrough = pAttach->getPassthrough();
8313 }
8314
8315 data.llAttachedDevices.push_back(dev);
8316 }
8317
8318 return S_OK;
8319}
8320
8321/**
8322 * Saves machine state settings as defined by aFlags
8323 * (SaveSTS_* values).
8324 *
8325 * @param aFlags Combination of SaveSTS_* flags.
8326 *
8327 * @note Locks objects for writing.
8328 */
8329HRESULT Machine::saveStateSettings(int aFlags)
8330{
8331 if (aFlags == 0)
8332 return S_OK;
8333
8334 AutoCaller autoCaller(this);
8335 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8336
8337 /* This object's write lock is also necessary to serialize file access
8338 * (prevent concurrent reads and writes) */
8339 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8340
8341 HRESULT rc = S_OK;
8342
8343 Assert(mData->pMachineConfigFile);
8344
8345 try
8346 {
8347 if (aFlags & SaveSTS_CurStateModified)
8348 mData->pMachineConfigFile->fCurrentStateModified = true;
8349
8350 if (aFlags & SaveSTS_StateFilePath)
8351 {
8352 if (!mSSData->mStateFilePath.isEmpty())
8353 /* try to make the file name relative to the settings file dir */
8354 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8355 else
8356 mData->pMachineConfigFile->strStateFile.setNull();
8357 }
8358
8359 if (aFlags & SaveSTS_StateTimeStamp)
8360 {
8361 Assert( mData->mMachineState != MachineState_Aborted
8362 || mSSData->mStateFilePath.isEmpty());
8363
8364 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8365
8366 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8367//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8368 }
8369
8370 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8371 }
8372 catch (...)
8373 {
8374 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8375 }
8376
8377 return rc;
8378}
8379
8380/**
8381 * Creates differencing hard disks for all normal hard disks attached to this
8382 * machine and a new set of attachments to refer to created disks.
8383 *
8384 * Used when taking a snapshot or when deleting the current state. Gets called
8385 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8386 *
8387 * This method assumes that mMediaData contains the original hard disk attachments
8388 * it needs to create diffs for. On success, these attachments will be replaced
8389 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8390 * called to delete created diffs which will also rollback mMediaData and restore
8391 * whatever was backed up before calling this method.
8392 *
8393 * Attachments with non-normal hard disks are left as is.
8394 *
8395 * If @a aOnline is @c false then the original hard disks that require implicit
8396 * diffs will be locked for reading. Otherwise it is assumed that they are
8397 * already locked for writing (when the VM was started). Note that in the latter
8398 * case it is responsibility of the caller to lock the newly created diffs for
8399 * writing if this method succeeds.
8400 *
8401 * @param aProgress Progress object to run (must contain at least as
8402 * many operations left as the number of hard disks
8403 * attached).
8404 * @param aOnline Whether the VM was online prior to this operation.
8405 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8406 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8407 *
8408 * @note The progress object is not marked as completed, neither on success nor
8409 * on failure. This is a responsibility of the caller.
8410 *
8411 * @note Locks this object for writing.
8412 */
8413HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8414 ULONG aWeight,
8415 bool aOnline,
8416 bool *pfNeedsSaveSettings)
8417{
8418 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8419
8420 AutoCaller autoCaller(this);
8421 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8422
8423 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8424
8425 /* must be in a protective state because we leave the lock below */
8426 AssertReturn( mData->mMachineState == MachineState_Saving
8427 || mData->mMachineState == MachineState_LiveSnapshotting
8428 || mData->mMachineState == MachineState_RestoringSnapshot
8429 || mData->mMachineState == MachineState_DeletingSnapshot
8430 , E_FAIL);
8431
8432 HRESULT rc = S_OK;
8433
8434 MediumLockListMap lockedMediaOffline;
8435 MediumLockListMap *lockedMediaMap;
8436 if (aOnline)
8437 lockedMediaMap = &mData->mSession.mLockedMedia;
8438 else
8439 lockedMediaMap = &lockedMediaOffline;
8440
8441 try
8442 {
8443 if (!aOnline)
8444 {
8445 /* lock all attached hard disks early to detect "in use"
8446 * situations before creating actual diffs */
8447 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8448 it != mMediaData->mAttachments.end();
8449 ++it)
8450 {
8451 MediumAttachment* pAtt = *it;
8452 if (pAtt->getType() == DeviceType_HardDisk)
8453 {
8454 Medium* pMedium = pAtt->getMedium();
8455 Assert(pMedium);
8456
8457 MediumLockList *pMediumLockList(new MediumLockList());
8458 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8459 false /* fMediumLockWrite */,
8460 NULL,
8461 *pMediumLockList);
8462 if (FAILED(rc))
8463 {
8464 delete pMediumLockList;
8465 throw rc;
8466 }
8467 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8468 if (FAILED(rc))
8469 {
8470 throw setError(rc,
8471 tr("Collecting locking information for all attached media failed"));
8472 }
8473 }
8474 }
8475
8476 /* Now lock all media. If this fails, nothing is locked. */
8477 rc = lockedMediaMap->Lock();
8478 if (FAILED(rc))
8479 {
8480 throw setError(rc,
8481 tr("Locking of attached media failed"));
8482 }
8483 }
8484
8485 /* remember the current list (note that we don't use backup() since
8486 * mMediaData may be already backed up) */
8487 MediaData::AttachmentList atts = mMediaData->mAttachments;
8488
8489 /* start from scratch */
8490 mMediaData->mAttachments.clear();
8491
8492 /* go through remembered attachments and create diffs for normal hard
8493 * disks and attach them */
8494 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8495 it != atts.end();
8496 ++it)
8497 {
8498 MediumAttachment* pAtt = *it;
8499
8500 DeviceType_T devType = pAtt->getType();
8501 Medium* pMedium = pAtt->getMedium();
8502
8503 if ( devType != DeviceType_HardDisk
8504 || pMedium == NULL
8505 || pMedium->getType() != MediumType_Normal)
8506 {
8507 /* copy the attachment as is */
8508
8509 /** @todo the progress object created in Console::TakeSnaphot
8510 * only expects operations for hard disks. Later other
8511 * device types need to show up in the progress as well. */
8512 if (devType == DeviceType_HardDisk)
8513 {
8514 if (pMedium == NULL)
8515 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
8516 aWeight); // weight
8517 else
8518 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8519 pMedium->getBase()->getName().c_str()),
8520 aWeight); // weight
8521 }
8522
8523 mMediaData->mAttachments.push_back(pAtt);
8524 continue;
8525 }
8526
8527 /* need a diff */
8528 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8529 pMedium->getBase()->getName().c_str()),
8530 aWeight); // weight
8531
8532 ComObjPtr<Medium> diff;
8533 diff.createObject();
8534 rc = diff->init(mParent,
8535 pMedium->getPreferredDiffFormat(),
8536 Utf8Str(mUserData->m_strSnapshotFolderFull).append(RTPATH_SLASH_STR),
8537 pMedium->getRegistryMachineId(), // store the diff in the same registry as the parent
8538 pfNeedsSaveSettings);
8539 if (FAILED(rc)) throw rc;
8540
8541 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8542 * the push_back? Looks like we're going to leave medium with the
8543 * wrong kind of lock (general issue with if we fail anywhere at all)
8544 * and an orphaned VDI in the snapshots folder. */
8545
8546 /* update the appropriate lock list */
8547 MediumLockList *pMediumLockList;
8548 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8549 AssertComRCThrowRC(rc);
8550 if (aOnline)
8551 {
8552 rc = pMediumLockList->Update(pMedium, false);
8553 AssertComRCThrowRC(rc);
8554 }
8555
8556 /* leave the lock before the potentially lengthy operation */
8557 alock.leave();
8558 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8559 pMediumLockList,
8560 NULL /* aProgress */,
8561 true /* aWait */,
8562 pfNeedsSaveSettings);
8563 alock.enter();
8564 if (FAILED(rc)) throw rc;
8565
8566 rc = lockedMediaMap->Unlock();
8567 AssertComRCThrowRC(rc);
8568 rc = pMediumLockList->Append(diff, true);
8569 AssertComRCThrowRC(rc);
8570 rc = lockedMediaMap->Lock();
8571 AssertComRCThrowRC(rc);
8572
8573 rc = diff->addBackReference(mData->mUuid);
8574 AssertComRCThrowRC(rc);
8575
8576 /* add a new attachment */
8577 ComObjPtr<MediumAttachment> attachment;
8578 attachment.createObject();
8579 rc = attachment->init(this,
8580 diff,
8581 pAtt->getControllerName(),
8582 pAtt->getPort(),
8583 pAtt->getDevice(),
8584 DeviceType_HardDisk,
8585 true /* aImplicit */,
8586 0 /* No bandwidth limit */);
8587 if (FAILED(rc)) throw rc;
8588
8589 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8590 AssertComRCThrowRC(rc);
8591 mMediaData->mAttachments.push_back(attachment);
8592 }
8593 }
8594 catch (HRESULT aRC) { rc = aRC; }
8595
8596 /* unlock all hard disks we locked */
8597 if (!aOnline)
8598 {
8599 ErrorInfoKeeper eik;
8600
8601 rc = lockedMediaMap->Clear();
8602 AssertComRC(rc);
8603 }
8604
8605 if (FAILED(rc))
8606 {
8607 MultiResult mrc = rc;
8608
8609 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8610 }
8611
8612 return rc;
8613}
8614
8615/**
8616 * Deletes implicit differencing hard disks created either by
8617 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8618 *
8619 * Note that to delete hard disks created by #AttachMedium() this method is
8620 * called from #fixupMedia() when the changes are rolled back.
8621 *
8622 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8623 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8624 *
8625 * @note Locks this object for writing.
8626 */
8627HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8628{
8629 AutoCaller autoCaller(this);
8630 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8631
8632 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8633 LogFlowThisFuncEnter();
8634
8635 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8636
8637 HRESULT rc = S_OK;
8638
8639 MediaData::AttachmentList implicitAtts;
8640
8641 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8642
8643 /* enumerate new attachments */
8644 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8645 it != mMediaData->mAttachments.end();
8646 ++it)
8647 {
8648 ComObjPtr<Medium> hd = (*it)->getMedium();
8649 if (hd.isNull())
8650 continue;
8651
8652 if ((*it)->isImplicit())
8653 {
8654 /* deassociate and mark for deletion */
8655 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8656 rc = hd->removeBackReference(mData->mUuid);
8657 AssertComRC(rc);
8658 implicitAtts.push_back(*it);
8659 continue;
8660 }
8661
8662 /* was this hard disk attached before? */
8663 if (!findAttachment(oldAtts, hd))
8664 {
8665 /* no: de-associate */
8666 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8667 rc = hd->removeBackReference(mData->mUuid);
8668 AssertComRC(rc);
8669 continue;
8670 }
8671 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8672 }
8673
8674 /* rollback hard disk changes */
8675 mMediaData.rollback();
8676
8677 MultiResult mrc(S_OK);
8678
8679 /* delete unused implicit diffs */
8680 if (implicitAtts.size() != 0)
8681 {
8682 /* will leave the lock before the potentially lengthy
8683 * operation, so protect with the special state (unless already
8684 * protected) */
8685 MachineState_T oldState = mData->mMachineState;
8686 if ( oldState != MachineState_Saving
8687 && oldState != MachineState_LiveSnapshotting
8688 && oldState != MachineState_RestoringSnapshot
8689 && oldState != MachineState_DeletingSnapshot
8690 && oldState != MachineState_DeletingSnapshotOnline
8691 && oldState != MachineState_DeletingSnapshotPaused
8692 )
8693 setMachineState(MachineState_SettingUp);
8694
8695 alock.leave();
8696
8697 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8698 it != implicitAtts.end();
8699 ++it)
8700 {
8701 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8702 ComObjPtr<Medium> hd = (*it)->getMedium();
8703
8704 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8705 pfNeedsSaveSettings);
8706 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8707 mrc = rc;
8708 }
8709
8710 alock.enter();
8711
8712 if (mData->mMachineState == MachineState_SettingUp)
8713 {
8714 setMachineState(oldState);
8715 }
8716 }
8717
8718 return mrc;
8719}
8720
8721/**
8722 * Looks through the given list of media attachments for one with the given parameters
8723 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8724 * can be searched as well if needed.
8725 *
8726 * @param list
8727 * @param aControllerName
8728 * @param aControllerPort
8729 * @param aDevice
8730 * @return
8731 */
8732MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8733 IN_BSTR aControllerName,
8734 LONG aControllerPort,
8735 LONG aDevice)
8736{
8737 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8738 it != ll.end();
8739 ++it)
8740 {
8741 MediumAttachment *pAttach = *it;
8742 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8743 return pAttach;
8744 }
8745
8746 return NULL;
8747}
8748
8749/**
8750 * Looks through the given list of media attachments for one with the given parameters
8751 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8752 * can be searched as well if needed.
8753 *
8754 * @param list
8755 * @param aControllerName
8756 * @param aControllerPort
8757 * @param aDevice
8758 * @return
8759 */
8760MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8761 ComObjPtr<Medium> pMedium)
8762{
8763 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8764 it != ll.end();
8765 ++it)
8766 {
8767 MediumAttachment *pAttach = *it;
8768 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8769 if (pMediumThis == pMedium)
8770 return pAttach;
8771 }
8772
8773 return NULL;
8774}
8775
8776/**
8777 * Looks through the given list of media attachments for one with the given parameters
8778 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8779 * can be searched as well if needed.
8780 *
8781 * @param list
8782 * @param aControllerName
8783 * @param aControllerPort
8784 * @param aDevice
8785 * @return
8786 */
8787MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8788 Guid &id)
8789{
8790 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8791 it != ll.end();
8792 ++it)
8793 {
8794 MediumAttachment *pAttach = *it;
8795 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8796 if (pMediumThis->getId() == id)
8797 return pAttach;
8798 }
8799
8800 return NULL;
8801}
8802
8803/**
8804 * Main implementation for Machine::DetachDevice. This also gets called
8805 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8806 *
8807 * @param pAttach Medium attachment to detach.
8808 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8809 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8810 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8811 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8812 * @return
8813 */
8814HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8815 AutoWriteLock &writeLock,
8816 Snapshot *pSnapshot,
8817 bool *pfNeedsSaveSettings)
8818{
8819 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8820 DeviceType_T mediumType = pAttach->getType();
8821
8822 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8823
8824 if (pAttach->isImplicit())
8825 {
8826 /* attempt to implicitly delete the implicitly created diff */
8827
8828 /// @todo move the implicit flag from MediumAttachment to Medium
8829 /// and forbid any hard disk operation when it is implicit. Or maybe
8830 /// a special media state for it to make it even more simple.
8831
8832 Assert(mMediaData.isBackedUp());
8833
8834 /* will leave the lock before the potentially lengthy operation, so
8835 * protect with the special state */
8836 MachineState_T oldState = mData->mMachineState;
8837 setMachineState(MachineState_SettingUp);
8838
8839 writeLock.release();
8840
8841 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8842 pfNeedsSaveSettings);
8843
8844 writeLock.acquire();
8845
8846 setMachineState(oldState);
8847
8848 if (FAILED(rc)) return rc;
8849 }
8850
8851 setModified(IsModified_Storage);
8852 mMediaData.backup();
8853
8854 // we cannot use erase (it) below because backup() above will create
8855 // a copy of the list and make this copy active, but the iterator
8856 // still refers to the original and is not valid for the copy
8857 mMediaData->mAttachments.remove(pAttach);
8858
8859 if (!oldmedium.isNull())
8860 {
8861 // if this is from a snapshot, do not defer detachment to commitMedia()
8862 if (pSnapshot)
8863 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8864 // else if non-hard disk media, do not defer detachment to commitMedia() either
8865 else if (mediumType != DeviceType_HardDisk)
8866 oldmedium->removeBackReference(mData->mUuid);
8867 }
8868
8869 return S_OK;
8870}
8871
8872/**
8873 * Goes thru all medium attachments of the list and calls detachDevice() on each
8874 * of them and attaches all Medium objects found in the process to the given list,
8875 * depending on cleanupMode.
8876 *
8877 * This gets called from Machine::Unregister, both for the actual Machine and
8878 * the SnapshotMachine objects that might be found in the snapshots.
8879 *
8880 * Requires caller and locking.
8881 *
8882 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8883 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8884 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
8885 * otherwise no media get added.
8886 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
8887 * @return
8888 */
8889HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8890 Snapshot *pSnapshot,
8891 CleanupMode_T cleanupMode,
8892 MediaList &llMedia)
8893{
8894 Assert(isWriteLockOnCurrentThread());
8895
8896 HRESULT rc;
8897
8898 // make a temporary list because detachDevice invalidates iterators into
8899 // mMediaData->mAttachments
8900 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8901
8902 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8903 it != llAttachments2.end();
8904 ++it)
8905 {
8906 ComObjPtr<MediumAttachment> pAttach = *it;
8907 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8908
8909 if (!pMedium.isNull())
8910 {
8911 DeviceType_T devType = pMedium->getDeviceType();
8912 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
8913 && devType == DeviceType_HardDisk)
8914 || (cleanupMode == CleanupMode_Full)
8915 )
8916 llMedia.push_back(pMedium);
8917 }
8918
8919 // real machine: then we need to use the proper method
8920 rc = detachDevice(pAttach,
8921 writeLock,
8922 pSnapshot,
8923 NULL /* pfNeedsSaveSettings */);
8924
8925 if (FAILED(rc))
8926 return rc;
8927 }
8928
8929 return S_OK;
8930}
8931
8932/**
8933 * Perform deferred hard disk detachments.
8934 *
8935 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8936 * backed up).
8937 *
8938 * If @a aOnline is @c true then this method will also unlock the old hard disks
8939 * for which the new implicit diffs were created and will lock these new diffs for
8940 * writing.
8941 *
8942 * @param aOnline Whether the VM was online prior to this operation.
8943 *
8944 * @note Locks this object for writing!
8945 */
8946void Machine::commitMedia(bool aOnline /*= false*/)
8947{
8948 AutoCaller autoCaller(this);
8949 AssertComRCReturnVoid(autoCaller.rc());
8950
8951 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8952
8953 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
8954
8955 HRESULT rc = S_OK;
8956
8957 /* no attach/detach operations -- nothing to do */
8958 if (!mMediaData.isBackedUp())
8959 return;
8960
8961 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8962 bool fMediaNeedsLocking = false;
8963
8964 /* enumerate new attachments */
8965 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8966 it != mMediaData->mAttachments.end();
8967 ++it)
8968 {
8969 MediumAttachment *pAttach = *it;
8970
8971 pAttach->commit();
8972
8973 Medium* pMedium = pAttach->getMedium();
8974 bool fImplicit = pAttach->isImplicit();
8975
8976 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
8977 (pMedium) ? pMedium->getName().c_str() : "NULL",
8978 fImplicit));
8979
8980 /** @todo convert all this Machine-based voodoo to MediumAttachment
8981 * based commit logic. */
8982 if (fImplicit)
8983 {
8984 /* convert implicit attachment to normal */
8985 pAttach->setImplicit(false);
8986
8987 if ( aOnline
8988 && pMedium
8989 && pAttach->getType() == DeviceType_HardDisk
8990 )
8991 {
8992 ComObjPtr<Medium> parent = pMedium->getParent();
8993 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8994
8995 /* update the appropriate lock list */
8996 MediumLockList *pMediumLockList;
8997 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8998 AssertComRC(rc);
8999 if (pMediumLockList)
9000 {
9001 /* unlock if there's a need to change the locking */
9002 if (!fMediaNeedsLocking)
9003 {
9004 rc = mData->mSession.mLockedMedia.Unlock();
9005 AssertComRC(rc);
9006 fMediaNeedsLocking = true;
9007 }
9008 rc = pMediumLockList->Update(parent, false);
9009 AssertComRC(rc);
9010 rc = pMediumLockList->Append(pMedium, true);
9011 AssertComRC(rc);
9012 }
9013 }
9014
9015 continue;
9016 }
9017
9018 if (pMedium)
9019 {
9020 /* was this medium attached before? */
9021 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9022 oldIt != oldAtts.end();
9023 ++oldIt)
9024 {
9025 MediumAttachment *pOldAttach = *oldIt;
9026 if (pOldAttach->getMedium() == pMedium)
9027 {
9028 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9029
9030 /* yes: remove from old to avoid de-association */
9031 oldAtts.erase(oldIt);
9032 break;
9033 }
9034 }
9035 }
9036 }
9037
9038 /* enumerate remaining old attachments and de-associate from the
9039 * current machine state */
9040 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9041 it != oldAtts.end();
9042 ++it)
9043 {
9044 MediumAttachment *pAttach = *it;
9045 Medium* pMedium = pAttach->getMedium();
9046
9047 /* Detach only hard disks, since DVD/floppy media is detached
9048 * instantly in MountMedium. */
9049 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9050 {
9051 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9052
9053 /* now de-associate from the current machine state */
9054 rc = pMedium->removeBackReference(mData->mUuid);
9055 AssertComRC(rc);
9056
9057 if (aOnline)
9058 {
9059 /* unlock since medium is not used anymore */
9060 MediumLockList *pMediumLockList;
9061 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9062 AssertComRC(rc);
9063 if (pMediumLockList)
9064 {
9065 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9066 AssertComRC(rc);
9067 }
9068 }
9069 }
9070 }
9071
9072 /* take media locks again so that the locking state is consistent */
9073 if (fMediaNeedsLocking)
9074 {
9075 Assert(aOnline);
9076 rc = mData->mSession.mLockedMedia.Lock();
9077 AssertComRC(rc);
9078 }
9079
9080 /* commit the hard disk changes */
9081 mMediaData.commit();
9082
9083 if (isSessionMachine())
9084 {
9085 /* attach new data to the primary machine and reshare it */
9086 mPeer->mMediaData.attach(mMediaData);
9087 }
9088
9089 return;
9090}
9091
9092/**
9093 * Perform deferred deletion of implicitly created diffs.
9094 *
9095 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9096 * backed up).
9097 *
9098 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9099 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9100 *
9101 * @note Locks this object for writing!
9102 */
9103void Machine::rollbackMedia()
9104{
9105 AutoCaller autoCaller(this);
9106 AssertComRCReturnVoid (autoCaller.rc());
9107
9108 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9109
9110 LogFlowThisFunc(("Entering\n"));
9111
9112 HRESULT rc = S_OK;
9113
9114 /* no attach/detach operations -- nothing to do */
9115 if (!mMediaData.isBackedUp())
9116 return;
9117
9118 /* enumerate new attachments */
9119 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9120 it != mMediaData->mAttachments.end();
9121 ++it)
9122 {
9123 MediumAttachment *pAttach = *it;
9124 /* Fix up the backrefs for DVD/floppy media. */
9125 if (pAttach->getType() != DeviceType_HardDisk)
9126 {
9127 Medium* pMedium = pAttach->getMedium();
9128 if (pMedium)
9129 {
9130 rc = pMedium->removeBackReference(mData->mUuid);
9131 AssertComRC(rc);
9132 }
9133 }
9134
9135 (*it)->rollback();
9136
9137 pAttach = *it;
9138 /* Fix up the backrefs for DVD/floppy media. */
9139 if (pAttach->getType() != DeviceType_HardDisk)
9140 {
9141 Medium* pMedium = pAttach->getMedium();
9142 if (pMedium)
9143 {
9144 rc = pMedium->addBackReference(mData->mUuid);
9145 AssertComRC(rc);
9146 }
9147 }
9148 }
9149
9150 /** @todo convert all this Machine-based voodoo to MediumAttachment
9151 * based rollback logic. */
9152 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9153 // which gets called if Machine::registeredInit() fails...
9154 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9155
9156 return;
9157}
9158
9159/**
9160 * Returns true if the settings file is located in the directory named exactly
9161 * as the machine. This will be true if the machine settings structure was
9162 * created by default in #openConfigLoader().
9163 *
9164 * @param aSettingsDir if not NULL, the full machine settings file directory
9165 * name will be assigned there.
9166 *
9167 * @note Doesn't lock anything.
9168 * @note Not thread safe (must be called from this object's lock).
9169 */
9170bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9171{
9172 Utf8Str settingsDir = mData->m_strConfigFileFull;
9173 settingsDir.stripFilename();
9174 Utf8Str strDirName = RTPathFilename(settingsDir.c_str());
9175
9176 AssertReturn(!strDirName.isEmpty(), false);
9177
9178 /* if we don't rename anything on name change, return false shorlty */
9179 if (!mUserData->s.fNameSync)
9180 return false;
9181
9182 if (aSettingsDir)
9183 *aSettingsDir = settingsDir;
9184
9185 return strDirName == mUserData->s.strName;
9186}
9187
9188/**
9189 * Discards all changes to machine settings.
9190 *
9191 * @param aNotify Whether to notify the direct session about changes or not.
9192 *
9193 * @note Locks objects for writing!
9194 */
9195void Machine::rollback(bool aNotify)
9196{
9197 AutoCaller autoCaller(this);
9198 AssertComRCReturn(autoCaller.rc(), (void)0);
9199
9200 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9201
9202 if (!mStorageControllers.isNull())
9203 {
9204 if (mStorageControllers.isBackedUp())
9205 {
9206 /* unitialize all new devices (absent in the backed up list). */
9207 StorageControllerList::const_iterator it = mStorageControllers->begin();
9208 StorageControllerList *backedList = mStorageControllers.backedUpData();
9209 while (it != mStorageControllers->end())
9210 {
9211 if ( std::find(backedList->begin(), backedList->end(), *it)
9212 == backedList->end()
9213 )
9214 {
9215 (*it)->uninit();
9216 }
9217 ++it;
9218 }
9219
9220 /* restore the list */
9221 mStorageControllers.rollback();
9222 }
9223
9224 /* rollback any changes to devices after restoring the list */
9225 if (mData->flModifications & IsModified_Storage)
9226 {
9227 StorageControllerList::const_iterator it = mStorageControllers->begin();
9228 while (it != mStorageControllers->end())
9229 {
9230 (*it)->rollback();
9231 ++it;
9232 }
9233 }
9234 }
9235
9236 mUserData.rollback();
9237
9238 mHWData.rollback();
9239
9240 if (mData->flModifications & IsModified_Storage)
9241 rollbackMedia();
9242
9243 if (mBIOSSettings)
9244 mBIOSSettings->rollback();
9245
9246#ifdef VBOX_WITH_VRDP
9247 if (mVRDPServer && (mData->flModifications & IsModified_VRDPServer))
9248 mVRDPServer->rollback();
9249#endif
9250
9251 if (mAudioAdapter)
9252 mAudioAdapter->rollback();
9253
9254 if (mUSBController && (mData->flModifications & IsModified_USB))
9255 mUSBController->rollback();
9256
9257 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9258 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9259 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9260
9261 if (mData->flModifications & IsModified_NetworkAdapters)
9262 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9263 if ( mNetworkAdapters[slot]
9264 && mNetworkAdapters[slot]->isModified())
9265 {
9266 mNetworkAdapters[slot]->rollback();
9267 networkAdapters[slot] = mNetworkAdapters[slot];
9268 }
9269
9270 if (mData->flModifications & IsModified_SerialPorts)
9271 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9272 if ( mSerialPorts[slot]
9273 && mSerialPorts[slot]->isModified())
9274 {
9275 mSerialPorts[slot]->rollback();
9276 serialPorts[slot] = mSerialPorts[slot];
9277 }
9278
9279 if (mData->flModifications & IsModified_ParallelPorts)
9280 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9281 if ( mParallelPorts[slot]
9282 && mParallelPorts[slot]->isModified())
9283 {
9284 mParallelPorts[slot]->rollback();
9285 parallelPorts[slot] = mParallelPorts[slot];
9286 }
9287
9288 if (aNotify)
9289 {
9290 /* inform the direct session about changes */
9291
9292 ComObjPtr<Machine> that = this;
9293 uint32_t flModifications = mData->flModifications;
9294 alock.leave();
9295
9296 if (flModifications & IsModified_SharedFolders)
9297 that->onSharedFolderChange();
9298
9299 if (flModifications & IsModified_VRDPServer)
9300 that->onVRDPServerChange(/* aRestart */ TRUE);
9301 if (flModifications & IsModified_USB)
9302 that->onUSBControllerChange();
9303
9304 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9305 if (networkAdapters[slot])
9306 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9307 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9308 if (serialPorts[slot])
9309 that->onSerialPortChange(serialPorts[slot]);
9310 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9311 if (parallelPorts[slot])
9312 that->onParallelPortChange(parallelPorts[slot]);
9313
9314 if (flModifications & IsModified_Storage)
9315 that->onStorageControllerChange();
9316 }
9317}
9318
9319/**
9320 * Commits all the changes to machine settings.
9321 *
9322 * Note that this operation is supposed to never fail.
9323 *
9324 * @note Locks this object and children for writing.
9325 */
9326void Machine::commit()
9327{
9328 AutoCaller autoCaller(this);
9329 AssertComRCReturnVoid(autoCaller.rc());
9330
9331 AutoCaller peerCaller(mPeer);
9332 AssertComRCReturnVoid(peerCaller.rc());
9333
9334 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9335
9336 /*
9337 * use safe commit to ensure Snapshot machines (that share mUserData)
9338 * will still refer to a valid memory location
9339 */
9340 mUserData.commitCopy();
9341
9342 mHWData.commit();
9343
9344 if (mMediaData.isBackedUp())
9345 commitMedia();
9346
9347 mBIOSSettings->commit();
9348#ifdef VBOX_WITH_VRDP
9349 mVRDPServer->commit();
9350#endif
9351 mAudioAdapter->commit();
9352 mUSBController->commit();
9353
9354 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9355 mNetworkAdapters[slot]->commit();
9356 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9357 mSerialPorts[slot]->commit();
9358 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9359 mParallelPorts[slot]->commit();
9360
9361 bool commitStorageControllers = false;
9362
9363 if (mStorageControllers.isBackedUp())
9364 {
9365 mStorageControllers.commit();
9366
9367 if (mPeer)
9368 {
9369 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9370
9371 /* Commit all changes to new controllers (this will reshare data with
9372 * peers for thos who have peers) */
9373 StorageControllerList *newList = new StorageControllerList();
9374 StorageControllerList::const_iterator it = mStorageControllers->begin();
9375 while (it != mStorageControllers->end())
9376 {
9377 (*it)->commit();
9378
9379 /* look if this controller has a peer device */
9380 ComObjPtr<StorageController> peer = (*it)->getPeer();
9381 if (!peer)
9382 {
9383 /* no peer means the device is a newly created one;
9384 * create a peer owning data this device share it with */
9385 peer.createObject();
9386 peer->init(mPeer, *it, true /* aReshare */);
9387 }
9388 else
9389 {
9390 /* remove peer from the old list */
9391 mPeer->mStorageControllers->remove(peer);
9392 }
9393 /* and add it to the new list */
9394 newList->push_back(peer);
9395
9396 ++it;
9397 }
9398
9399 /* uninit old peer's controllers that are left */
9400 it = mPeer->mStorageControllers->begin();
9401 while (it != mPeer->mStorageControllers->end())
9402 {
9403 (*it)->uninit();
9404 ++it;
9405 }
9406
9407 /* attach new list of controllers to our peer */
9408 mPeer->mStorageControllers.attach(newList);
9409 }
9410 else
9411 {
9412 /* we have no peer (our parent is the newly created machine);
9413 * just commit changes to devices */
9414 commitStorageControllers = true;
9415 }
9416 }
9417 else
9418 {
9419 /* the list of controllers itself is not changed,
9420 * just commit changes to controllers themselves */
9421 commitStorageControllers = true;
9422 }
9423
9424 if (commitStorageControllers)
9425 {
9426 StorageControllerList::const_iterator it = mStorageControllers->begin();
9427 while (it != mStorageControllers->end())
9428 {
9429 (*it)->commit();
9430 ++it;
9431 }
9432 }
9433
9434 if (isSessionMachine())
9435 {
9436 /* attach new data to the primary machine and reshare it */
9437 mPeer->mUserData.attach(mUserData);
9438 mPeer->mHWData.attach(mHWData);
9439 /* mMediaData is reshared by fixupMedia */
9440 // mPeer->mMediaData.attach(mMediaData);
9441 Assert(mPeer->mMediaData.data() == mMediaData.data());
9442 }
9443}
9444
9445/**
9446 * Copies all the hardware data from the given machine.
9447 *
9448 * Currently, only called when the VM is being restored from a snapshot. In
9449 * particular, this implies that the VM is not running during this method's
9450 * call.
9451 *
9452 * @note This method must be called from under this object's lock.
9453 *
9454 * @note This method doesn't call #commit(), so all data remains backed up and
9455 * unsaved.
9456 */
9457void Machine::copyFrom(Machine *aThat)
9458{
9459 AssertReturnVoid(!isSnapshotMachine());
9460 AssertReturnVoid(aThat->isSnapshotMachine());
9461
9462 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9463
9464 mHWData.assignCopy(aThat->mHWData);
9465
9466 // create copies of all shared folders (mHWData after attiching a copy
9467 // contains just references to original objects)
9468 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9469 it != mHWData->mSharedFolders.end();
9470 ++it)
9471 {
9472 ComObjPtr<SharedFolder> folder;
9473 folder.createObject();
9474 HRESULT rc = folder->initCopy(getMachine(), *it);
9475 AssertComRC(rc);
9476 *it = folder;
9477 }
9478
9479 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9480#ifdef VBOX_WITH_VRDP
9481 mVRDPServer->copyFrom(aThat->mVRDPServer);
9482#endif
9483 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9484 mUSBController->copyFrom(aThat->mUSBController);
9485
9486 /* create private copies of all controllers */
9487 mStorageControllers.backup();
9488 mStorageControllers->clear();
9489 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9490 it != aThat->mStorageControllers->end();
9491 ++it)
9492 {
9493 ComObjPtr<StorageController> ctrl;
9494 ctrl.createObject();
9495 ctrl->initCopy(this, *it);
9496 mStorageControllers->push_back(ctrl);
9497 }
9498
9499 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9500 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9501 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9502 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9503 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9504 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9505}
9506
9507#ifdef VBOX_WITH_RESOURCE_USAGE_API
9508
9509void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9510{
9511 AssertReturnVoid(isWriteLockOnCurrentThread());
9512 AssertPtrReturnVoid(aCollector);
9513
9514 pm::CollectorHAL *hal = aCollector->getHAL();
9515 /* Create sub metrics */
9516 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9517 "Percentage of processor time spent in user mode by the VM process.");
9518 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9519 "Percentage of processor time spent in kernel mode by the VM process.");
9520 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9521 "Size of resident portion of VM process in memory.");
9522 /* Create and register base metrics */
9523 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9524 cpuLoadUser, cpuLoadKernel);
9525 aCollector->registerBaseMetric(cpuLoad);
9526 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9527 ramUsageUsed);
9528 aCollector->registerBaseMetric(ramUsage);
9529
9530 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9531 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9532 new pm::AggregateAvg()));
9533 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9534 new pm::AggregateMin()));
9535 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9536 new pm::AggregateMax()));
9537 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9538 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9539 new pm::AggregateAvg()));
9540 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9541 new pm::AggregateMin()));
9542 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9543 new pm::AggregateMax()));
9544
9545 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9546 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9547 new pm::AggregateAvg()));
9548 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9549 new pm::AggregateMin()));
9550 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9551 new pm::AggregateMax()));
9552
9553
9554 /* Guest metrics */
9555 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9556
9557 /* Create sub metrics */
9558 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9559 "Percentage of processor time spent in user mode as seen by the guest.");
9560 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9561 "Percentage of processor time spent in kernel mode as seen by the guest.");
9562 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9563 "Percentage of processor time spent idling as seen by the guest.");
9564
9565 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9566 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9567 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9568 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9569 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9570 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9571
9572 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9573
9574 /* Create and register base metrics */
9575 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9576 aCollector->registerBaseMetric(guestCpuLoad);
9577
9578 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9579 guestMemCache, guestPagedTotal);
9580 aCollector->registerBaseMetric(guestCpuMem);
9581
9582 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9583 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9584 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9585 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9586
9587 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9588 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9589 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9590 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9591
9592 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9593 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9594 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9595 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9596
9597 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9598 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9599 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9600 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9601
9602 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9603 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9604 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9605 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9606
9607 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9608 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9609 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9610 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9611
9612 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9613 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9614 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9615 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9616
9617 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9618 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9619 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9620 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9621
9622 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9623 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9624 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9625 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9626}
9627
9628void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9629{
9630 AssertReturnVoid(isWriteLockOnCurrentThread());
9631
9632 if (aCollector)
9633 {
9634 aCollector->unregisterMetricsFor(aMachine);
9635 aCollector->unregisterBaseMetricsFor(aMachine);
9636 }
9637
9638 if (mGuestHAL)
9639 {
9640 delete mGuestHAL;
9641 mGuestHAL = NULL;
9642 }
9643}
9644
9645#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9646
9647
9648////////////////////////////////////////////////////////////////////////////////
9649
9650DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9651
9652HRESULT SessionMachine::FinalConstruct()
9653{
9654 LogFlowThisFunc(("\n"));
9655
9656#if defined(RT_OS_WINDOWS)
9657 mIPCSem = NULL;
9658#elif defined(RT_OS_OS2)
9659 mIPCSem = NULLHANDLE;
9660#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9661 mIPCSem = -1;
9662#else
9663# error "Port me!"
9664#endif
9665
9666 return S_OK;
9667}
9668
9669void SessionMachine::FinalRelease()
9670{
9671 LogFlowThisFunc(("\n"));
9672
9673 uninit(Uninit::Unexpected);
9674}
9675
9676/**
9677 * @note Must be called only by Machine::openSession() from its own write lock.
9678 */
9679HRESULT SessionMachine::init(Machine *aMachine)
9680{
9681 LogFlowThisFuncEnter();
9682 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9683
9684 AssertReturn(aMachine, E_INVALIDARG);
9685
9686 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9687
9688 /* Enclose the state transition NotReady->InInit->Ready */
9689 AutoInitSpan autoInitSpan(this);
9690 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9691
9692 /* create the interprocess semaphore */
9693#if defined(RT_OS_WINDOWS)
9694 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9695 for (size_t i = 0; i < mIPCSemName.length(); i++)
9696 if (mIPCSemName[i] == '\\')
9697 mIPCSemName[i] = '/';
9698 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName);
9699 ComAssertMsgRet(mIPCSem,
9700 ("Cannot create IPC mutex '%ls', err=%d",
9701 mIPCSemName.raw(), ::GetLastError()),
9702 E_FAIL);
9703#elif defined(RT_OS_OS2)
9704 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9705 aMachine->mData->mUuid.raw());
9706 mIPCSemName = ipcSem;
9707 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.raw(), &mIPCSem, 0, FALSE);
9708 ComAssertMsgRet(arc == NO_ERROR,
9709 ("Cannot create IPC mutex '%s', arc=%ld",
9710 ipcSem.raw(), arc),
9711 E_FAIL);
9712#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9713# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9714# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9715 /** @todo Check that this still works correctly. */
9716 AssertCompileSize(key_t, 8);
9717# else
9718 AssertCompileSize(key_t, 4);
9719# endif
9720 key_t key;
9721 mIPCSem = -1;
9722 mIPCKey = "0";
9723 for (uint32_t i = 0; i < 1 << 24; i++)
9724 {
9725 key = ((uint32_t)'V' << 24) | i;
9726 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9727 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9728 {
9729 mIPCSem = sem;
9730 if (sem >= 0)
9731 mIPCKey = BstrFmt("%u", key);
9732 break;
9733 }
9734 }
9735# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9736 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9737 char *pszSemName = NULL;
9738 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9739 key_t key = ::ftok(pszSemName, 'V');
9740 RTStrFree(pszSemName);
9741
9742 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9743# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9744
9745 int errnoSave = errno;
9746 if (mIPCSem < 0 && errnoSave == ENOSYS)
9747 {
9748 setError(E_FAIL,
9749 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9750 "support for SysV IPC. Check the host kernel configuration for "
9751 "CONFIG_SYSVIPC=y"));
9752 return E_FAIL;
9753 }
9754 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9755 * the IPC semaphores */
9756 if (mIPCSem < 0 && errnoSave == ENOSPC)
9757 {
9758#ifdef RT_OS_LINUX
9759 setError(E_FAIL,
9760 tr("Cannot create IPC semaphore because the system limit for the "
9761 "maximum number of semaphore sets (SEMMNI), or the system wide "
9762 "maximum number of sempahores (SEMMNS) would be exceeded. The "
9763 "current set of SysV IPC semaphores can be determined from "
9764 "the file /proc/sysvipc/sem"));
9765#else
9766 setError(E_FAIL,
9767 tr("Cannot create IPC semaphore because the system-imposed limit "
9768 "on the maximum number of allowed semaphores or semaphore "
9769 "identifiers system-wide would be exceeded"));
9770#endif
9771 return E_FAIL;
9772 }
9773 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9774 E_FAIL);
9775 /* set the initial value to 1 */
9776 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9777 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9778 E_FAIL);
9779#else
9780# error "Port me!"
9781#endif
9782
9783 /* memorize the peer Machine */
9784 unconst(mPeer) = aMachine;
9785 /* share the parent pointer */
9786 unconst(mParent) = aMachine->mParent;
9787
9788 /* take the pointers to data to share */
9789 mData.share(aMachine->mData);
9790 mSSData.share(aMachine->mSSData);
9791
9792 mUserData.share(aMachine->mUserData);
9793 mHWData.share(aMachine->mHWData);
9794 mMediaData.share(aMachine->mMediaData);
9795
9796 mStorageControllers.allocate();
9797 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9798 it != aMachine->mStorageControllers->end();
9799 ++it)
9800 {
9801 ComObjPtr<StorageController> ctl;
9802 ctl.createObject();
9803 ctl->init(this, *it);
9804 mStorageControllers->push_back(ctl);
9805 }
9806
9807 unconst(mBIOSSettings).createObject();
9808 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9809#ifdef VBOX_WITH_VRDP
9810 /* create another VRDPServer object that will be mutable */
9811 unconst(mVRDPServer).createObject();
9812 mVRDPServer->init(this, aMachine->mVRDPServer);
9813#endif
9814 /* create another audio adapter object that will be mutable */
9815 unconst(mAudioAdapter).createObject();
9816 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9817 /* create a list of serial ports that will be mutable */
9818 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9819 {
9820 unconst(mSerialPorts[slot]).createObject();
9821 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9822 }
9823 /* create a list of parallel ports that will be mutable */
9824 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9825 {
9826 unconst(mParallelPorts[slot]).createObject();
9827 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9828 }
9829 /* create another USB controller object that will be mutable */
9830 unconst(mUSBController).createObject();
9831 mUSBController->init(this, aMachine->mUSBController);
9832
9833 /* create a list of network adapters that will be mutable */
9834 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9835 {
9836 unconst(mNetworkAdapters[slot]).createObject();
9837 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9838 }
9839
9840 /* default is to delete saved state on Saved -> PoweredOff transition */
9841 mRemoveSavedState = true;
9842
9843 /* Confirm a successful initialization when it's the case */
9844 autoInitSpan.setSucceeded();
9845
9846 LogFlowThisFuncLeave();
9847 return S_OK;
9848}
9849
9850/**
9851 * Uninitializes this session object. If the reason is other than
9852 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9853 *
9854 * @param aReason uninitialization reason
9855 *
9856 * @note Locks mParent + this object for writing.
9857 */
9858void SessionMachine::uninit(Uninit::Reason aReason)
9859{
9860 LogFlowThisFuncEnter();
9861 LogFlowThisFunc(("reason=%d\n", aReason));
9862
9863 /*
9864 * Strongly reference ourselves to prevent this object deletion after
9865 * mData->mSession.mMachine.setNull() below (which can release the last
9866 * reference and call the destructor). Important: this must be done before
9867 * accessing any members (and before AutoUninitSpan that does it as well).
9868 * This self reference will be released as the very last step on return.
9869 */
9870 ComObjPtr<SessionMachine> selfRef = this;
9871
9872 /* Enclose the state transition Ready->InUninit->NotReady */
9873 AutoUninitSpan autoUninitSpan(this);
9874 if (autoUninitSpan.uninitDone())
9875 {
9876 LogFlowThisFunc(("Already uninitialized\n"));
9877 LogFlowThisFuncLeave();
9878 return;
9879 }
9880
9881 if (autoUninitSpan.initFailed())
9882 {
9883 /* We've been called by init() because it's failed. It's not really
9884 * necessary (nor it's safe) to perform the regular uninit sequense
9885 * below, the following is enough.
9886 */
9887 LogFlowThisFunc(("Initialization failed.\n"));
9888#if defined(RT_OS_WINDOWS)
9889 if (mIPCSem)
9890 ::CloseHandle(mIPCSem);
9891 mIPCSem = NULL;
9892#elif defined(RT_OS_OS2)
9893 if (mIPCSem != NULLHANDLE)
9894 ::DosCloseMutexSem(mIPCSem);
9895 mIPCSem = NULLHANDLE;
9896#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9897 if (mIPCSem >= 0)
9898 ::semctl(mIPCSem, 0, IPC_RMID);
9899 mIPCSem = -1;
9900# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9901 mIPCKey = "0";
9902# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9903#else
9904# error "Port me!"
9905#endif
9906 uninitDataAndChildObjects();
9907 mData.free();
9908 unconst(mParent) = NULL;
9909 unconst(mPeer) = NULL;
9910 LogFlowThisFuncLeave();
9911 return;
9912 }
9913
9914 MachineState_T lastState;
9915 {
9916 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9917 lastState = mData->mMachineState;
9918 }
9919 NOREF(lastState);
9920
9921#ifdef VBOX_WITH_USB
9922 // release all captured USB devices, but do this before requesting the locks below
9923 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9924 {
9925 /* Console::captureUSBDevices() is called in the VM process only after
9926 * setting the machine state to Starting or Restoring.
9927 * Console::detachAllUSBDevices() will be called upon successful
9928 * termination. So, we need to release USB devices only if there was
9929 * an abnormal termination of a running VM.
9930 *
9931 * This is identical to SessionMachine::DetachAllUSBDevices except
9932 * for the aAbnormal argument. */
9933 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9934 AssertComRC(rc);
9935 NOREF(rc);
9936
9937 USBProxyService *service = mParent->host()->usbProxyService();
9938 if (service)
9939 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9940 }
9941#endif /* VBOX_WITH_USB */
9942
9943 // we need to lock this object in uninit() because the lock is shared
9944 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
9945 // and others need mParent lock, and USB needs host lock.
9946 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
9947
9948 // Trigger async cleanup tasks, avoid doing things here which are not
9949 // vital to be done immediately and maybe need more locks. This calls
9950 // Machine::unregisterMetrics().
9951 mParent->onMachineUninit(mPeer);
9952
9953 if (aReason == Uninit::Abnormal)
9954 {
9955 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
9956 Global::IsOnlineOrTransient(lastState)));
9957
9958 /* reset the state to Aborted */
9959 if (mData->mMachineState != MachineState_Aborted)
9960 setMachineState(MachineState_Aborted);
9961 }
9962
9963 // any machine settings modified?
9964 if (mData->flModifications)
9965 {
9966 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
9967 rollback(false /* aNotify */);
9968 }
9969
9970 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
9971 if (!mSnapshotData.mStateFilePath.isEmpty())
9972 {
9973 LogWarningThisFunc(("canceling failed save state request!\n"));
9974 endSavingState(FALSE /* aSuccess */);
9975 }
9976 else if (!mSnapshotData.mSnapshot.isNull())
9977 {
9978 LogWarningThisFunc(("canceling untaken snapshot!\n"));
9979
9980 /* delete all differencing hard disks created (this will also attach
9981 * their parents back by rolling back mMediaData) */
9982 rollbackMedia();
9983 /* delete the saved state file (it might have been already created) */
9984 if (mSnapshotData.mSnapshot->stateFilePath().length())
9985 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
9986
9987 mSnapshotData.mSnapshot->uninit();
9988 }
9989
9990 if (!mData->mSession.mType.isEmpty())
9991 {
9992 /* mType is not null when this machine's process has been started by
9993 * Machine::launchVMProcess(), therefore it is our child. We
9994 * need to queue the PID to reap the process (and avoid zombies on
9995 * Linux). */
9996 Assert(mData->mSession.mPid != NIL_RTPROCESS);
9997 mParent->addProcessToReap(mData->mSession.mPid);
9998 }
9999
10000 mData->mSession.mPid = NIL_RTPROCESS;
10001
10002 if (aReason == Uninit::Unexpected)
10003 {
10004 /* Uninitialization didn't come from #checkForDeath(), so tell the
10005 * client watcher thread to update the set of machines that have open
10006 * sessions. */
10007 mParent->updateClientWatcher();
10008 }
10009
10010 /* uninitialize all remote controls */
10011 if (mData->mSession.mRemoteControls.size())
10012 {
10013 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10014 mData->mSession.mRemoteControls.size()));
10015
10016 Data::Session::RemoteControlList::iterator it =
10017 mData->mSession.mRemoteControls.begin();
10018 while (it != mData->mSession.mRemoteControls.end())
10019 {
10020 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10021 HRESULT rc = (*it)->Uninitialize();
10022 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10023 if (FAILED(rc))
10024 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10025 ++it;
10026 }
10027 mData->mSession.mRemoteControls.clear();
10028 }
10029
10030 /*
10031 * An expected uninitialization can come only from #checkForDeath().
10032 * Otherwise it means that something's got really wrong (for examlple,
10033 * the Session implementation has released the VirtualBox reference
10034 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10035 * etc). However, it's also possible, that the client releases the IPC
10036 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10037 * but the VirtualBox release event comes first to the server process.
10038 * This case is practically possible, so we should not assert on an
10039 * unexpected uninit, just log a warning.
10040 */
10041
10042 if ((aReason == Uninit::Unexpected))
10043 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10044
10045 if (aReason != Uninit::Normal)
10046 {
10047 mData->mSession.mDirectControl.setNull();
10048 }
10049 else
10050 {
10051 /* this must be null here (see #OnSessionEnd()) */
10052 Assert(mData->mSession.mDirectControl.isNull());
10053 Assert(mData->mSession.mState == SessionState_Unlocking);
10054 Assert(!mData->mSession.mProgress.isNull());
10055 }
10056 if (mData->mSession.mProgress)
10057 {
10058 if (aReason == Uninit::Normal)
10059 mData->mSession.mProgress->notifyComplete(S_OK);
10060 else
10061 mData->mSession.mProgress->notifyComplete(E_FAIL,
10062 COM_IIDOF(ISession),
10063 getComponentName(),
10064 tr("The VM session was aborted"));
10065 mData->mSession.mProgress.setNull();
10066 }
10067
10068 /* remove the association between the peer machine and this session machine */
10069 Assert( (SessionMachine*)mData->mSession.mMachine == this
10070 || aReason == Uninit::Unexpected);
10071
10072 /* reset the rest of session data */
10073 mData->mSession.mMachine.setNull();
10074 mData->mSession.mState = SessionState_Unlocked;
10075 mData->mSession.mType.setNull();
10076
10077 /* close the interprocess semaphore before leaving the exclusive lock */
10078#if defined(RT_OS_WINDOWS)
10079 if (mIPCSem)
10080 ::CloseHandle(mIPCSem);
10081 mIPCSem = NULL;
10082#elif defined(RT_OS_OS2)
10083 if (mIPCSem != NULLHANDLE)
10084 ::DosCloseMutexSem(mIPCSem);
10085 mIPCSem = NULLHANDLE;
10086#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10087 if (mIPCSem >= 0)
10088 ::semctl(mIPCSem, 0, IPC_RMID);
10089 mIPCSem = -1;
10090# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10091 mIPCKey = "0";
10092# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10093#else
10094# error "Port me!"
10095#endif
10096
10097 /* fire an event */
10098 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10099
10100 uninitDataAndChildObjects();
10101
10102 /* free the essential data structure last */
10103 mData.free();
10104
10105#if 1 /** @todo Please review this change! (bird) */
10106 /* drop the exclusive lock before setting the below two to NULL */
10107 multilock.release();
10108#else
10109 /* leave the exclusive lock before setting the below two to NULL */
10110 multilock.leave();
10111#endif
10112
10113 unconst(mParent) = NULL;
10114 unconst(mPeer) = NULL;
10115
10116 LogFlowThisFuncLeave();
10117}
10118
10119// util::Lockable interface
10120////////////////////////////////////////////////////////////////////////////////
10121
10122/**
10123 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10124 * with the primary Machine instance (mPeer).
10125 */
10126RWLockHandle *SessionMachine::lockHandle() const
10127{
10128 AssertReturn(mPeer != NULL, NULL);
10129 return mPeer->lockHandle();
10130}
10131
10132// IInternalMachineControl methods
10133////////////////////////////////////////////////////////////////////////////////
10134
10135/**
10136 * @note Locks this object for writing.
10137 */
10138STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10139{
10140 AutoCaller autoCaller(this);
10141 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10142
10143 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10144
10145 mRemoveSavedState = aRemove;
10146
10147 return S_OK;
10148}
10149
10150/**
10151 * @note Locks the same as #setMachineState() does.
10152 */
10153STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10154{
10155 return setMachineState(aMachineState);
10156}
10157
10158/**
10159 * @note Locks this object for reading.
10160 */
10161STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10162{
10163 AutoCaller autoCaller(this);
10164 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10165
10166 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10167
10168#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10169 mIPCSemName.cloneTo(aId);
10170 return S_OK;
10171#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10172# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10173 mIPCKey.cloneTo(aId);
10174# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10175 mData->m_strConfigFileFull.cloneTo(aId);
10176# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10177 return S_OK;
10178#else
10179# error "Port me!"
10180#endif
10181}
10182
10183/**
10184 * @note Locks this object for writing.
10185 */
10186STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10187{
10188 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10189 AutoCaller autoCaller(this);
10190 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10191
10192 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10193
10194 if (mData->mSession.mState != SessionState_Locked)
10195 return VBOX_E_INVALID_OBJECT_STATE;
10196
10197 if (!mData->mSession.mProgress.isNull())
10198 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10199
10200 LogFlowThisFunc(("returns S_OK.\n"));
10201 return S_OK;
10202}
10203
10204
10205/**
10206 * @note Locks this object for writing.
10207 */
10208STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10209{
10210 AutoCaller autoCaller(this);
10211 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10212
10213 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10214
10215 if (mData->mSession.mState != SessionState_Locked)
10216 return VBOX_E_INVALID_OBJECT_STATE;
10217
10218 /* Finalize the openRemoteSession progress object. */
10219 if (mData->mSession.mProgress)
10220 {
10221 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10222 mData->mSession.mProgress.setNull();
10223
10224 if (SUCCEEDED((HRESULT)iResult))
10225 {
10226#ifdef VBOX_WITH_RESOURCE_USAGE_API
10227 /* The VM has been powered up successfully, so it makes sense
10228 * now to offer the performance metrics for a running machine
10229 * object. Doing it earlier wouldn't be safe. */
10230 registerMetrics(mParent->performanceCollector(), mPeer,
10231 mData->mSession.mPid);
10232#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10233
10234 }
10235 }
10236 return S_OK;
10237}
10238
10239/**
10240 * Goes through the USB filters of the given machine to see if the given
10241 * device matches any filter or not.
10242 *
10243 * @note Locks the same as USBController::hasMatchingFilter() does.
10244 */
10245STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10246 BOOL *aMatched,
10247 ULONG *aMaskedIfs)
10248{
10249 LogFlowThisFunc(("\n"));
10250
10251 CheckComArgNotNull(aUSBDevice);
10252 CheckComArgOutPointerValid(aMatched);
10253
10254 AutoCaller autoCaller(this);
10255 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10256
10257#ifdef VBOX_WITH_USB
10258 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10259#else
10260 NOREF(aUSBDevice);
10261 NOREF(aMaskedIfs);
10262 *aMatched = FALSE;
10263#endif
10264
10265 return S_OK;
10266}
10267
10268/**
10269 * @note Locks the same as Host::captureUSBDevice() does.
10270 */
10271STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10272{
10273 LogFlowThisFunc(("\n"));
10274
10275 AutoCaller autoCaller(this);
10276 AssertComRCReturnRC(autoCaller.rc());
10277
10278#ifdef VBOX_WITH_USB
10279 /* if captureDeviceForVM() fails, it must have set extended error info */
10280 MultiResult rc = mParent->host()->checkUSBProxyService();
10281 if (FAILED(rc)) return rc;
10282
10283 USBProxyService *service = mParent->host()->usbProxyService();
10284 AssertReturn(service, E_FAIL);
10285 return service->captureDeviceForVM(this, Guid(aId));
10286#else
10287 NOREF(aId);
10288 return E_NOTIMPL;
10289#endif
10290}
10291
10292/**
10293 * @note Locks the same as Host::detachUSBDevice() does.
10294 */
10295STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10296{
10297 LogFlowThisFunc(("\n"));
10298
10299 AutoCaller autoCaller(this);
10300 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10301
10302#ifdef VBOX_WITH_USB
10303 USBProxyService *service = mParent->host()->usbProxyService();
10304 AssertReturn(service, E_FAIL);
10305 return service->detachDeviceFromVM(this, Guid(aId), !!aDone);
10306#else
10307 NOREF(aId);
10308 NOREF(aDone);
10309 return E_NOTIMPL;
10310#endif
10311}
10312
10313/**
10314 * Inserts all machine filters to the USB proxy service and then calls
10315 * Host::autoCaptureUSBDevices().
10316 *
10317 * Called by Console from the VM process upon VM startup.
10318 *
10319 * @note Locks what called methods lock.
10320 */
10321STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10322{
10323 LogFlowThisFunc(("\n"));
10324
10325 AutoCaller autoCaller(this);
10326 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10327
10328#ifdef VBOX_WITH_USB
10329 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10330 AssertComRC(rc);
10331 NOREF(rc);
10332
10333 USBProxyService *service = mParent->host()->usbProxyService();
10334 AssertReturn(service, E_FAIL);
10335 return service->autoCaptureDevicesForVM(this);
10336#else
10337 return S_OK;
10338#endif
10339}
10340
10341/**
10342 * Removes all machine filters from the USB proxy service and then calls
10343 * Host::detachAllUSBDevices().
10344 *
10345 * Called by Console from the VM process upon normal VM termination or by
10346 * SessionMachine::uninit() upon abnormal VM termination (from under the
10347 * Machine/SessionMachine lock).
10348 *
10349 * @note Locks what called methods lock.
10350 */
10351STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10352{
10353 LogFlowThisFunc(("\n"));
10354
10355 AutoCaller autoCaller(this);
10356 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10357
10358#ifdef VBOX_WITH_USB
10359 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10360 AssertComRC(rc);
10361 NOREF(rc);
10362
10363 USBProxyService *service = mParent->host()->usbProxyService();
10364 AssertReturn(service, E_FAIL);
10365 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10366#else
10367 NOREF(aDone);
10368 return S_OK;
10369#endif
10370}
10371
10372/**
10373 * @note Locks this object for writing.
10374 */
10375STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10376 IProgress **aProgress)
10377{
10378 LogFlowThisFuncEnter();
10379
10380 AssertReturn(aSession, E_INVALIDARG);
10381 AssertReturn(aProgress, E_INVALIDARG);
10382
10383 AutoCaller autoCaller(this);
10384
10385 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10386 /*
10387 * We don't assert below because it might happen that a non-direct session
10388 * informs us it is closed right after we've been uninitialized -- it's ok.
10389 */
10390 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10391
10392 /* get IInternalSessionControl interface */
10393 ComPtr<IInternalSessionControl> control(aSession);
10394
10395 ComAssertRet(!control.isNull(), E_INVALIDARG);
10396
10397 /* Creating a Progress object requires the VirtualBox lock, and
10398 * thus locking it here is required by the lock order rules. */
10399 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10400
10401 if (control == mData->mSession.mDirectControl)
10402 {
10403 ComAssertRet(aProgress, E_POINTER);
10404
10405 /* The direct session is being normally closed by the client process
10406 * ----------------------------------------------------------------- */
10407
10408 /* go to the closing state (essential for all open*Session() calls and
10409 * for #checkForDeath()) */
10410 Assert(mData->mSession.mState == SessionState_Locked);
10411 mData->mSession.mState = SessionState_Unlocking;
10412
10413 /* set direct control to NULL to release the remote instance */
10414 mData->mSession.mDirectControl.setNull();
10415 LogFlowThisFunc(("Direct control is set to NULL\n"));
10416
10417 if (mData->mSession.mProgress)
10418 {
10419 /* finalize the progress, someone might wait if a frontend
10420 * closes the session before powering on the VM. */
10421 mData->mSession.mProgress->notifyComplete(E_FAIL,
10422 COM_IIDOF(ISession),
10423 getComponentName(),
10424 tr("The VM session was closed before any attempt to power it on"));
10425 mData->mSession.mProgress.setNull();
10426 }
10427
10428 /* Create the progress object the client will use to wait until
10429 * #checkForDeath() is called to uninitialize this session object after
10430 * it releases the IPC semaphore.
10431 * Note! Because we're "reusing" mProgress here, this must be a proxy
10432 * object just like for openRemoteSession. */
10433 Assert(mData->mSession.mProgress.isNull());
10434 ComObjPtr<ProgressProxy> progress;
10435 progress.createObject();
10436 ComPtr<IUnknown> pPeer(mPeer);
10437 progress->init(mParent, pPeer,
10438 Bstr(tr("Closing session")),
10439 FALSE /* aCancelable */);
10440 progress.queryInterfaceTo(aProgress);
10441 mData->mSession.mProgress = progress;
10442 }
10443 else
10444 {
10445 /* the remote session is being normally closed */
10446 Data::Session::RemoteControlList::iterator it =
10447 mData->mSession.mRemoteControls.begin();
10448 while (it != mData->mSession.mRemoteControls.end())
10449 {
10450 if (control == *it)
10451 break;
10452 ++it;
10453 }
10454 BOOL found = it != mData->mSession.mRemoteControls.end();
10455 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10456 E_INVALIDARG);
10457 mData->mSession.mRemoteControls.remove(*it);
10458 }
10459
10460 LogFlowThisFuncLeave();
10461 return S_OK;
10462}
10463
10464/**
10465 * @note Locks this object for writing.
10466 */
10467STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10468{
10469 LogFlowThisFuncEnter();
10470
10471 AssertReturn(aProgress, E_INVALIDARG);
10472 AssertReturn(aStateFilePath, E_POINTER);
10473
10474 AutoCaller autoCaller(this);
10475 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10476
10477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10478
10479 AssertReturn( mData->mMachineState == MachineState_Paused
10480 && mSnapshotData.mLastState == MachineState_Null
10481 && mSnapshotData.mProgressId.isEmpty()
10482 && mSnapshotData.mStateFilePath.isEmpty(),
10483 E_FAIL);
10484
10485 /* memorize the progress ID and add it to the global collection */
10486 Bstr progressId;
10487 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10488 AssertComRCReturn(rc, rc);
10489 rc = mParent->addProgress(aProgress);
10490 AssertComRCReturn(rc, rc);
10491
10492 Bstr stateFilePath;
10493 /* stateFilePath is null when the machine is not running */
10494 if (mData->mMachineState == MachineState_Paused)
10495 {
10496 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10497 mUserData->m_strSnapshotFolderFull.c_str(),
10498 RTPATH_DELIMITER, mData->mUuid.raw());
10499 }
10500
10501 /* fill in the snapshot data */
10502 mSnapshotData.mLastState = mData->mMachineState;
10503 mSnapshotData.mProgressId = Guid(progressId);
10504 mSnapshotData.mStateFilePath = stateFilePath;
10505
10506 /* set the state to Saving (this is expected by Console::SaveState()) */
10507 setMachineState(MachineState_Saving);
10508
10509 stateFilePath.cloneTo(aStateFilePath);
10510
10511 return S_OK;
10512}
10513
10514/**
10515 * @note Locks mParent + this object for writing.
10516 */
10517STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10518{
10519 LogFlowThisFunc(("\n"));
10520
10521 AutoCaller autoCaller(this);
10522 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10523
10524 /* endSavingState() need mParent lock */
10525 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10526
10527 AssertReturn( mData->mMachineState == MachineState_Saving
10528 && mSnapshotData.mLastState != MachineState_Null
10529 && !mSnapshotData.mProgressId.isEmpty()
10530 && !mSnapshotData.mStateFilePath.isEmpty(),
10531 E_FAIL);
10532
10533 /*
10534 * on success, set the state to Saved;
10535 * on failure, set the state to the state we had when BeginSavingState() was
10536 * called (this is expected by Console::SaveState() and
10537 * Console::saveStateThread())
10538 */
10539 if (aSuccess)
10540 setMachineState(MachineState_Saved);
10541 else
10542 setMachineState(mSnapshotData.mLastState);
10543
10544 return endSavingState(aSuccess);
10545}
10546
10547/**
10548 * @note Locks this object for writing.
10549 */
10550STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10551{
10552 LogFlowThisFunc(("\n"));
10553
10554 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10555
10556 AutoCaller autoCaller(this);
10557 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10558
10559 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10560
10561 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10562 || mData->mMachineState == MachineState_Teleported
10563 || mData->mMachineState == MachineState_Aborted
10564 , E_FAIL); /** @todo setError. */
10565
10566 Utf8Str stateFilePathFull = aSavedStateFile;
10567 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10568 if (RT_FAILURE(vrc))
10569 return setError(VBOX_E_FILE_ERROR,
10570 tr("Invalid saved state file path '%ls' (%Rrc)"),
10571 aSavedStateFile,
10572 vrc);
10573
10574 mSSData->mStateFilePath = stateFilePathFull;
10575
10576 /* The below setMachineState() will detect the state transition and will
10577 * update the settings file */
10578
10579 return setMachineState(MachineState_Saved);
10580}
10581
10582STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10583 ComSafeArrayOut(BSTR, aValues),
10584 ComSafeArrayOut(LONG64, aTimestamps),
10585 ComSafeArrayOut(BSTR, aFlags))
10586{
10587 LogFlowThisFunc(("\n"));
10588
10589#ifdef VBOX_WITH_GUEST_PROPS
10590 using namespace guestProp;
10591
10592 AutoCaller autoCaller(this);
10593 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10594
10595 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10596
10597 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10598 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10599 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10600 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10601
10602 size_t cEntries = mHWData->mGuestProperties.size();
10603 com::SafeArray<BSTR> names(cEntries);
10604 com::SafeArray<BSTR> values(cEntries);
10605 com::SafeArray<LONG64> timestamps(cEntries);
10606 com::SafeArray<BSTR> flags(cEntries);
10607 unsigned i = 0;
10608 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10609 it != mHWData->mGuestProperties.end();
10610 ++it)
10611 {
10612 char szFlags[MAX_FLAGS_LEN + 1];
10613 it->strName.cloneTo(&names[i]);
10614 it->strValue.cloneTo(&values[i]);
10615 timestamps[i] = it->mTimestamp;
10616 /* If it is NULL, keep it NULL. */
10617 if (it->mFlags)
10618 {
10619 writeFlags(it->mFlags, szFlags);
10620 Bstr(szFlags).cloneTo(&flags[i]);
10621 }
10622 else
10623 flags[i] = NULL;
10624 ++i;
10625 }
10626 names.detachTo(ComSafeArrayOutArg(aNames));
10627 values.detachTo(ComSafeArrayOutArg(aValues));
10628 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10629 flags.detachTo(ComSafeArrayOutArg(aFlags));
10630 return S_OK;
10631#else
10632 ReturnComNotImplemented();
10633#endif
10634}
10635
10636STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10637 IN_BSTR aValue,
10638 LONG64 aTimestamp,
10639 IN_BSTR aFlags)
10640{
10641 LogFlowThisFunc(("\n"));
10642
10643#ifdef VBOX_WITH_GUEST_PROPS
10644 using namespace guestProp;
10645
10646 CheckComArgStrNotEmptyOrNull(aName);
10647 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10648 return E_POINTER; /* aValue can be NULL to indicate deletion */
10649
10650 try
10651 {
10652 /*
10653 * Convert input up front.
10654 */
10655 Utf8Str utf8Name(aName);
10656 uint32_t fFlags = NILFLAG;
10657 if (aFlags)
10658 {
10659 Utf8Str utf8Flags(aFlags);
10660 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
10661 AssertRCReturn(vrc, E_INVALIDARG);
10662 }
10663
10664 /*
10665 * Now grab the object lock, validate the state and do the update.
10666 */
10667 AutoCaller autoCaller(this);
10668 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10669
10670 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10671
10672 switch (mData->mMachineState)
10673 {
10674 case MachineState_Paused:
10675 case MachineState_Running:
10676 case MachineState_Teleporting:
10677 case MachineState_TeleportingPausedVM:
10678 case MachineState_LiveSnapshotting:
10679 case MachineState_DeletingSnapshotOnline:
10680 case MachineState_DeletingSnapshotPaused:
10681 case MachineState_Saving:
10682 break;
10683
10684 default:
10685 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10686 VBOX_E_INVALID_VM_STATE);
10687 }
10688
10689 setModified(IsModified_MachineData);
10690 mHWData.backup();
10691
10692 /** @todo r=bird: The careful memory handling doesn't work out here because
10693 * the catch block won't undo any damange we've done. So, if push_back throws
10694 * bad_alloc then you've lost the value.
10695 *
10696 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10697 * since values that changes actually bubbles to the end of the list. Using
10698 * something that has an efficient lookup and can tollerate a bit of updates
10699 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10700 * combination of RTStrCache (for sharing names and getting uniqueness into
10701 * the bargain) and hash/tree is another. */
10702 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10703 iter != mHWData->mGuestProperties.end();
10704 ++iter)
10705 if (utf8Name == iter->strName)
10706 {
10707 mHWData->mGuestProperties.erase(iter);
10708 mData->mGuestPropertiesModified = TRUE;
10709 break;
10710 }
10711 if (aValue != NULL)
10712 {
10713 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10714 mHWData->mGuestProperties.push_back(property);
10715 mData->mGuestPropertiesModified = TRUE;
10716 }
10717
10718 /*
10719 * Send a callback notification if appropriate
10720 */
10721 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10722 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
10723 RTSTR_MAX,
10724 utf8Name.c_str(),
10725 RTSTR_MAX, NULL)
10726 )
10727 {
10728 alock.leave();
10729
10730 mParent->onGuestPropertyChange(mData->mUuid,
10731 aName,
10732 aValue,
10733 aFlags);
10734 }
10735 }
10736 catch (...)
10737 {
10738 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10739 }
10740 return S_OK;
10741#else
10742 ReturnComNotImplemented();
10743#endif
10744}
10745
10746// public methods only for internal purposes
10747/////////////////////////////////////////////////////////////////////////////
10748
10749/**
10750 * Called from the client watcher thread to check for expected or unexpected
10751 * death of the client process that has a direct session to this machine.
10752 *
10753 * On Win32 and on OS/2, this method is called only when we've got the
10754 * mutex (i.e. the client has either died or terminated normally) so it always
10755 * returns @c true (the client is terminated, the session machine is
10756 * uninitialized).
10757 *
10758 * On other platforms, the method returns @c true if the client process has
10759 * terminated normally or abnormally and the session machine was uninitialized,
10760 * and @c false if the client process is still alive.
10761 *
10762 * @note Locks this object for writing.
10763 */
10764bool SessionMachine::checkForDeath()
10765{
10766 Uninit::Reason reason;
10767 bool terminated = false;
10768
10769 /* Enclose autoCaller with a block because calling uninit() from under it
10770 * will deadlock. */
10771 {
10772 AutoCaller autoCaller(this);
10773 if (!autoCaller.isOk())
10774 {
10775 /* return true if not ready, to cause the client watcher to exclude
10776 * the corresponding session from watching */
10777 LogFlowThisFunc(("Already uninitialized!\n"));
10778 return true;
10779 }
10780
10781 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10782
10783 /* Determine the reason of death: if the session state is Closing here,
10784 * everything is fine. Otherwise it means that the client did not call
10785 * OnSessionEnd() before it released the IPC semaphore. This may happen
10786 * either because the client process has abnormally terminated, or
10787 * because it simply forgot to call ISession::Close() before exiting. We
10788 * threat the latter also as an abnormal termination (see
10789 * Session::uninit() for details). */
10790 reason = mData->mSession.mState == SessionState_Unlocking ?
10791 Uninit::Normal :
10792 Uninit::Abnormal;
10793
10794#if defined(RT_OS_WINDOWS)
10795
10796 AssertMsg(mIPCSem, ("semaphore must be created"));
10797
10798 /* release the IPC mutex */
10799 ::ReleaseMutex(mIPCSem);
10800
10801 terminated = true;
10802
10803#elif defined(RT_OS_OS2)
10804
10805 AssertMsg(mIPCSem, ("semaphore must be created"));
10806
10807 /* release the IPC mutex */
10808 ::DosReleaseMutexSem(mIPCSem);
10809
10810 terminated = true;
10811
10812#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10813
10814 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10815
10816 int val = ::semctl(mIPCSem, 0, GETVAL);
10817 if (val > 0)
10818 {
10819 /* the semaphore is signaled, meaning the session is terminated */
10820 terminated = true;
10821 }
10822
10823#else
10824# error "Port me!"
10825#endif
10826
10827 } /* AutoCaller block */
10828
10829 if (terminated)
10830 uninit(reason);
10831
10832 return terminated;
10833}
10834
10835/**
10836 * @note Locks this object for reading.
10837 */
10838HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10839{
10840 LogFlowThisFunc(("\n"));
10841
10842 AutoCaller autoCaller(this);
10843 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10844
10845 ComPtr<IInternalSessionControl> directControl;
10846 {
10847 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10848 directControl = mData->mSession.mDirectControl;
10849 }
10850
10851 /* ignore notifications sent after #OnSessionEnd() is called */
10852 if (!directControl)
10853 return S_OK;
10854
10855 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10856}
10857
10858/**
10859 * @note Locks this object for reading.
10860 */
10861HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10862{
10863 LogFlowThisFunc(("\n"));
10864
10865 AutoCaller autoCaller(this);
10866 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10867
10868 ComPtr<IInternalSessionControl> directControl;
10869 {
10870 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10871 directControl = mData->mSession.mDirectControl;
10872 }
10873
10874 /* ignore notifications sent after #OnSessionEnd() is called */
10875 if (!directControl)
10876 return S_OK;
10877
10878 return directControl->OnSerialPortChange(serialPort);
10879}
10880
10881/**
10882 * @note Locks this object for reading.
10883 */
10884HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10885{
10886 LogFlowThisFunc(("\n"));
10887
10888 AutoCaller autoCaller(this);
10889 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10890
10891 ComPtr<IInternalSessionControl> directControl;
10892 {
10893 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10894 directControl = mData->mSession.mDirectControl;
10895 }
10896
10897 /* ignore notifications sent after #OnSessionEnd() is called */
10898 if (!directControl)
10899 return S_OK;
10900
10901 return directControl->OnParallelPortChange(parallelPort);
10902}
10903
10904/**
10905 * @note Locks this object for reading.
10906 */
10907HRESULT SessionMachine::onStorageControllerChange()
10908{
10909 LogFlowThisFunc(("\n"));
10910
10911 AutoCaller autoCaller(this);
10912 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10913
10914 ComPtr<IInternalSessionControl> directControl;
10915 {
10916 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10917 directControl = mData->mSession.mDirectControl;
10918 }
10919
10920 /* ignore notifications sent after #OnSessionEnd() is called */
10921 if (!directControl)
10922 return S_OK;
10923
10924 return directControl->OnStorageControllerChange();
10925}
10926
10927/**
10928 * @note Locks this object for reading.
10929 */
10930HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10931{
10932 LogFlowThisFunc(("\n"));
10933
10934 AutoCaller autoCaller(this);
10935 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10936
10937 ComPtr<IInternalSessionControl> directControl;
10938 {
10939 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10940 directControl = mData->mSession.mDirectControl;
10941 }
10942
10943 /* ignore notifications sent after #OnSessionEnd() is called */
10944 if (!directControl)
10945 return S_OK;
10946
10947 return directControl->OnMediumChange(aAttachment, aForce);
10948}
10949
10950/**
10951 * @note Locks this object for reading.
10952 */
10953HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
10954{
10955 LogFlowThisFunc(("\n"));
10956
10957 AutoCaller autoCaller(this);
10958 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10959
10960 ComPtr<IInternalSessionControl> directControl;
10961 {
10962 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10963 directControl = mData->mSession.mDirectControl;
10964 }
10965
10966 /* ignore notifications sent after #OnSessionEnd() is called */
10967 if (!directControl)
10968 return S_OK;
10969
10970 return directControl->OnCPUChange(aCPU, aRemove);
10971}
10972
10973HRESULT SessionMachine::onCPUPriorityChange(ULONG aCpuPriority)
10974{
10975 LogFlowThisFunc(("\n"));
10976
10977 AutoCaller autoCaller(this);
10978 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10979
10980 ComPtr<IInternalSessionControl> directControl;
10981 {
10982 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10983 directControl = mData->mSession.mDirectControl;
10984 }
10985
10986 /* ignore notifications sent after #OnSessionEnd() is called */
10987 if (!directControl)
10988 return S_OK;
10989
10990 return directControl->OnCPUPriorityChange(aCpuPriority);
10991}
10992
10993/**
10994 * @note Locks this object for reading.
10995 */
10996HRESULT SessionMachine::onVRDPServerChange(BOOL aRestart)
10997{
10998 LogFlowThisFunc(("\n"));
10999
11000 AutoCaller autoCaller(this);
11001 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11002
11003 ComPtr<IInternalSessionControl> directControl;
11004 {
11005 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11006 directControl = mData->mSession.mDirectControl;
11007 }
11008
11009 /* ignore notifications sent after #OnSessionEnd() is called */
11010 if (!directControl)
11011 return S_OK;
11012
11013 return directControl->OnVRDPServerChange(aRestart);
11014}
11015
11016/**
11017 * @note Locks this object for reading.
11018 */
11019HRESULT SessionMachine::onUSBControllerChange()
11020{
11021 LogFlowThisFunc(("\n"));
11022
11023 AutoCaller autoCaller(this);
11024 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11025
11026 ComPtr<IInternalSessionControl> directControl;
11027 {
11028 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11029 directControl = mData->mSession.mDirectControl;
11030 }
11031
11032 /* ignore notifications sent after #OnSessionEnd() is called */
11033 if (!directControl)
11034 return S_OK;
11035
11036 return directControl->OnUSBControllerChange();
11037}
11038
11039/**
11040 * @note Locks this object for reading.
11041 */
11042HRESULT SessionMachine::onSharedFolderChange()
11043{
11044 LogFlowThisFunc(("\n"));
11045
11046 AutoCaller autoCaller(this);
11047 AssertComRCReturnRC(autoCaller.rc());
11048
11049 ComPtr<IInternalSessionControl> directControl;
11050 {
11051 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11052 directControl = mData->mSession.mDirectControl;
11053 }
11054
11055 /* ignore notifications sent after #OnSessionEnd() is called */
11056 if (!directControl)
11057 return S_OK;
11058
11059 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11060}
11061
11062/**
11063 * Returns @c true if this machine's USB controller reports it has a matching
11064 * filter for the given USB device and @c false otherwise.
11065 *
11066 * @note Caller must have requested machine read lock.
11067 */
11068bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11069{
11070 AutoCaller autoCaller(this);
11071 /* silently return if not ready -- this method may be called after the
11072 * direct machine session has been called */
11073 if (!autoCaller.isOk())
11074 return false;
11075
11076
11077#ifdef VBOX_WITH_USB
11078 switch (mData->mMachineState)
11079 {
11080 case MachineState_Starting:
11081 case MachineState_Restoring:
11082 case MachineState_TeleportingIn:
11083 case MachineState_Paused:
11084 case MachineState_Running:
11085 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11086 * elsewhere... */
11087 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11088 default: break;
11089 }
11090#else
11091 NOREF(aDevice);
11092 NOREF(aMaskedIfs);
11093#endif
11094 return false;
11095}
11096
11097/**
11098 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11099 */
11100HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11101 IVirtualBoxErrorInfo *aError,
11102 ULONG aMaskedIfs)
11103{
11104 LogFlowThisFunc(("\n"));
11105
11106 AutoCaller autoCaller(this);
11107
11108 /* This notification may happen after the machine object has been
11109 * uninitialized (the session was closed), so don't assert. */
11110 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11111
11112 ComPtr<IInternalSessionControl> directControl;
11113 {
11114 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11115 directControl = mData->mSession.mDirectControl;
11116 }
11117
11118 /* fail on notifications sent after #OnSessionEnd() is called, it is
11119 * expected by the caller */
11120 if (!directControl)
11121 return E_FAIL;
11122
11123 /* No locks should be held at this point. */
11124 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11125 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11126
11127 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11128}
11129
11130/**
11131 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11132 */
11133HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11134 IVirtualBoxErrorInfo *aError)
11135{
11136 LogFlowThisFunc(("\n"));
11137
11138 AutoCaller autoCaller(this);
11139
11140 /* This notification may happen after the machine object has been
11141 * uninitialized (the session was closed), so don't assert. */
11142 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11143
11144 ComPtr<IInternalSessionControl> directControl;
11145 {
11146 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11147 directControl = mData->mSession.mDirectControl;
11148 }
11149
11150 /* fail on notifications sent after #OnSessionEnd() is called, it is
11151 * expected by the caller */
11152 if (!directControl)
11153 return E_FAIL;
11154
11155 /* No locks should be held at this point. */
11156 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11157 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11158
11159 return directControl->OnUSBDeviceDetach(aId, aError);
11160}
11161
11162// protected methods
11163/////////////////////////////////////////////////////////////////////////////
11164
11165/**
11166 * Helper method to finalize saving the state.
11167 *
11168 * @note Must be called from under this object's lock.
11169 *
11170 * @param aSuccess TRUE if the snapshot has been taken successfully
11171 *
11172 * @note Locks mParent + this objects for writing.
11173 */
11174HRESULT SessionMachine::endSavingState(BOOL aSuccess)
11175{
11176 LogFlowThisFuncEnter();
11177
11178 AutoCaller autoCaller(this);
11179 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11180
11181 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11182
11183 HRESULT rc = S_OK;
11184
11185 if (aSuccess)
11186 {
11187 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11188
11189 /* save all VM settings */
11190 rc = saveSettings(NULL);
11191 // no need to check whether VirtualBox.xml needs saving also since
11192 // we can't have a name change pending at this point
11193 }
11194 else
11195 {
11196 /* delete the saved state file (it might have been already created) */
11197 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11198 }
11199
11200 /* remove the completed progress object */
11201 mParent->removeProgress(mSnapshotData.mProgressId);
11202
11203 /* clear out the temporary saved state data */
11204 mSnapshotData.mLastState = MachineState_Null;
11205 mSnapshotData.mProgressId.clear();
11206 mSnapshotData.mStateFilePath.setNull();
11207
11208 LogFlowThisFuncLeave();
11209 return rc;
11210}
11211
11212/**
11213 * Locks the attached media.
11214 *
11215 * All attached hard disks are locked for writing and DVD/floppy are locked for
11216 * reading. Parents of attached hard disks (if any) are locked for reading.
11217 *
11218 * This method also performs accessibility check of all media it locks: if some
11219 * media is inaccessible, the method will return a failure and a bunch of
11220 * extended error info objects per each inaccessible medium.
11221 *
11222 * Note that this method is atomic: if it returns a success, all media are
11223 * locked as described above; on failure no media is locked at all (all
11224 * succeeded individual locks will be undone).
11225 *
11226 * This method is intended to be called when the machine is in Starting or
11227 * Restoring state and asserts otherwise.
11228 *
11229 * The locks made by this method must be undone by calling #unlockMedia() when
11230 * no more needed.
11231 */
11232HRESULT SessionMachine::lockMedia()
11233{
11234 AutoCaller autoCaller(this);
11235 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11236
11237 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11238
11239 AssertReturn( mData->mMachineState == MachineState_Starting
11240 || mData->mMachineState == MachineState_Restoring
11241 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11242 /* bail out if trying to lock things with already set up locking */
11243 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11244
11245 MultiResult mrc(S_OK);
11246
11247 /* Collect locking information for all medium objects attached to the VM. */
11248 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11249 it != mMediaData->mAttachments.end();
11250 ++it)
11251 {
11252 MediumAttachment* pAtt = *it;
11253 DeviceType_T devType = pAtt->getType();
11254 Medium *pMedium = pAtt->getMedium();
11255
11256 MediumLockList *pMediumLockList(new MediumLockList());
11257 // There can be attachments without a medium (floppy/dvd), and thus
11258 // it's impossible to create a medium lock list. It still makes sense
11259 // to have the empty medium lock list in the map in case a medium is
11260 // attached later.
11261 if (pMedium != NULL)
11262 {
11263 MediumType_T mediumType = pMedium->getType();
11264 bool fIsReadOnlyImage = devType == DeviceType_DVD
11265 || mediumType == MediumType_Shareable;
11266 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11267
11268 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11269 !fIsReadOnlyImage /* fMediumLockWrite */,
11270 NULL,
11271 *pMediumLockList);
11272 if (FAILED(mrc))
11273 {
11274 delete pMediumLockList;
11275 mData->mSession.mLockedMedia.Clear();
11276 break;
11277 }
11278 }
11279
11280 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11281 if (FAILED(rc))
11282 {
11283 mData->mSession.mLockedMedia.Clear();
11284 mrc = setError(rc,
11285 tr("Collecting locking information for all attached media failed"));
11286 break;
11287 }
11288 }
11289
11290 if (SUCCEEDED(mrc))
11291 {
11292 /* Now lock all media. If this fails, nothing is locked. */
11293 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11294 if (FAILED(rc))
11295 {
11296 mrc = setError(rc,
11297 tr("Locking of attached media failed"));
11298 }
11299 }
11300
11301 return mrc;
11302}
11303
11304/**
11305 * Undoes the locks made by by #lockMedia().
11306 */
11307void SessionMachine::unlockMedia()
11308{
11309 AutoCaller autoCaller(this);
11310 AssertComRCReturnVoid(autoCaller.rc());
11311
11312 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11313
11314 /* we may be holding important error info on the current thread;
11315 * preserve it */
11316 ErrorInfoKeeper eik;
11317
11318 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11319 AssertComRC(rc);
11320}
11321
11322/**
11323 * Helper to change the machine state (reimplementation).
11324 *
11325 * @note Locks this object for writing.
11326 */
11327HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11328{
11329 LogFlowThisFuncEnter();
11330 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11331
11332 AutoCaller autoCaller(this);
11333 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11334
11335 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11336
11337 MachineState_T oldMachineState = mData->mMachineState;
11338
11339 AssertMsgReturn(oldMachineState != aMachineState,
11340 ("oldMachineState=%s, aMachineState=%s\n",
11341 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11342 E_FAIL);
11343
11344 HRESULT rc = S_OK;
11345
11346 int stsFlags = 0;
11347 bool deleteSavedState = false;
11348
11349 /* detect some state transitions */
11350
11351 if ( ( oldMachineState == MachineState_Saved
11352 && aMachineState == MachineState_Restoring)
11353 || ( ( oldMachineState == MachineState_PoweredOff
11354 || oldMachineState == MachineState_Teleported
11355 || oldMachineState == MachineState_Aborted
11356 )
11357 && ( aMachineState == MachineState_TeleportingIn
11358 || aMachineState == MachineState_Starting
11359 )
11360 )
11361 )
11362 {
11363 /* The EMT thread is about to start */
11364
11365 /* Nothing to do here for now... */
11366
11367 /// @todo NEWMEDIA don't let mDVDDrive and other children
11368 /// change anything when in the Starting/Restoring state
11369 }
11370 else if ( ( oldMachineState == MachineState_Running
11371 || oldMachineState == MachineState_Paused
11372 || oldMachineState == MachineState_Teleporting
11373 || oldMachineState == MachineState_LiveSnapshotting
11374 || oldMachineState == MachineState_Stuck
11375 || oldMachineState == MachineState_Starting
11376 || oldMachineState == MachineState_Stopping
11377 || oldMachineState == MachineState_Saving
11378 || oldMachineState == MachineState_Restoring
11379 || oldMachineState == MachineState_TeleportingPausedVM
11380 || oldMachineState == MachineState_TeleportingIn
11381 )
11382 && ( aMachineState == MachineState_PoweredOff
11383 || aMachineState == MachineState_Saved
11384 || aMachineState == MachineState_Teleported
11385 || aMachineState == MachineState_Aborted
11386 )
11387 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11388 * snapshot */
11389 && ( mSnapshotData.mSnapshot.isNull()
11390 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11391 )
11392 )
11393 {
11394 /* The EMT thread has just stopped, unlock attached media. Note that as
11395 * opposed to locking that is done from Console, we do unlocking here
11396 * because the VM process may have aborted before having a chance to
11397 * properly unlock all media it locked. */
11398
11399 unlockMedia();
11400 }
11401
11402 if (oldMachineState == MachineState_Restoring)
11403 {
11404 if (aMachineState != MachineState_Saved)
11405 {
11406 /*
11407 * delete the saved state file once the machine has finished
11408 * restoring from it (note that Console sets the state from
11409 * Restoring to Saved if the VM couldn't restore successfully,
11410 * to give the user an ability to fix an error and retry --
11411 * we keep the saved state file in this case)
11412 */
11413 deleteSavedState = true;
11414 }
11415 }
11416 else if ( oldMachineState == MachineState_Saved
11417 && ( aMachineState == MachineState_PoweredOff
11418 || aMachineState == MachineState_Aborted
11419 || aMachineState == MachineState_Teleported
11420 )
11421 )
11422 {
11423 /*
11424 * delete the saved state after Console::ForgetSavedState() is called
11425 * or if the VM process (owning a direct VM session) crashed while the
11426 * VM was Saved
11427 */
11428
11429 /// @todo (dmik)
11430 // Not sure that deleting the saved state file just because of the
11431 // client death before it attempted to restore the VM is a good
11432 // thing. But when it crashes we need to go to the Aborted state
11433 // which cannot have the saved state file associated... The only
11434 // way to fix this is to make the Aborted condition not a VM state
11435 // but a bool flag: i.e., when a crash occurs, set it to true and
11436 // change the state to PoweredOff or Saved depending on the
11437 // saved state presence.
11438
11439 deleteSavedState = true;
11440 mData->mCurrentStateModified = TRUE;
11441 stsFlags |= SaveSTS_CurStateModified;
11442 }
11443
11444 if ( aMachineState == MachineState_Starting
11445 || aMachineState == MachineState_Restoring
11446 || aMachineState == MachineState_TeleportingIn
11447 )
11448 {
11449 /* set the current state modified flag to indicate that the current
11450 * state is no more identical to the state in the
11451 * current snapshot */
11452 if (!mData->mCurrentSnapshot.isNull())
11453 {
11454 mData->mCurrentStateModified = TRUE;
11455 stsFlags |= SaveSTS_CurStateModified;
11456 }
11457 }
11458
11459 if (deleteSavedState)
11460 {
11461 if (mRemoveSavedState)
11462 {
11463 Assert(!mSSData->mStateFilePath.isEmpty());
11464 RTFileDelete(mSSData->mStateFilePath.c_str());
11465 }
11466 mSSData->mStateFilePath.setNull();
11467 stsFlags |= SaveSTS_StateFilePath;
11468 }
11469
11470 /* redirect to the underlying peer machine */
11471 mPeer->setMachineState(aMachineState);
11472
11473 if ( aMachineState == MachineState_PoweredOff
11474 || aMachineState == MachineState_Teleported
11475 || aMachineState == MachineState_Aborted
11476 || aMachineState == MachineState_Saved)
11477 {
11478 /* the machine has stopped execution
11479 * (or the saved state file was adopted) */
11480 stsFlags |= SaveSTS_StateTimeStamp;
11481 }
11482
11483 if ( ( oldMachineState == MachineState_PoweredOff
11484 || oldMachineState == MachineState_Aborted
11485 || oldMachineState == MachineState_Teleported
11486 )
11487 && aMachineState == MachineState_Saved)
11488 {
11489 /* the saved state file was adopted */
11490 Assert(!mSSData->mStateFilePath.isEmpty());
11491 stsFlags |= SaveSTS_StateFilePath;
11492 }
11493
11494 if ( aMachineState == MachineState_PoweredOff
11495 || aMachineState == MachineState_Aborted
11496 || aMachineState == MachineState_Teleported)
11497 {
11498 /* Make sure any transient guest properties get removed from the
11499 * property store on shutdown. */
11500
11501 HWData::GuestPropertyList::iterator it;
11502 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11503 if (!fNeedsSaving)
11504 for (it = mHWData->mGuestProperties.begin();
11505 it != mHWData->mGuestProperties.end(); ++it)
11506 if (it->mFlags & guestProp::TRANSIENT)
11507 {
11508 fNeedsSaving = true;
11509 break;
11510 }
11511 if (fNeedsSaving)
11512 {
11513 mData->mCurrentStateModified = TRUE;
11514 stsFlags |= SaveSTS_CurStateModified;
11515 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11516 }
11517 }
11518
11519 rc = saveStateSettings(stsFlags);
11520
11521 if ( ( oldMachineState != MachineState_PoweredOff
11522 && oldMachineState != MachineState_Aborted
11523 && oldMachineState != MachineState_Teleported
11524 )
11525 && ( aMachineState == MachineState_PoweredOff
11526 || aMachineState == MachineState_Aborted
11527 || aMachineState == MachineState_Teleported
11528 )
11529 )
11530 {
11531 /* we've been shut down for any reason */
11532 /* no special action so far */
11533 }
11534
11535 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11536 LogFlowThisFuncLeave();
11537 return rc;
11538}
11539
11540/**
11541 * Sends the current machine state value to the VM process.
11542 *
11543 * @note Locks this object for reading, then calls a client process.
11544 */
11545HRESULT SessionMachine::updateMachineStateOnClient()
11546{
11547 AutoCaller autoCaller(this);
11548 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11549
11550 ComPtr<IInternalSessionControl> directControl;
11551 {
11552 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11553 AssertReturn(!!mData, E_FAIL);
11554 directControl = mData->mSession.mDirectControl;
11555
11556 /* directControl may be already set to NULL here in #OnSessionEnd()
11557 * called too early by the direct session process while there is still
11558 * some operation (like deleting the snapshot) in progress. The client
11559 * process in this case is waiting inside Session::close() for the
11560 * "end session" process object to complete, while #uninit() called by
11561 * #checkForDeath() on the Watcher thread is waiting for the pending
11562 * operation to complete. For now, we accept this inconsitent behavior
11563 * and simply do nothing here. */
11564
11565 if (mData->mSession.mState == SessionState_Unlocking)
11566 return S_OK;
11567
11568 AssertReturn(!directControl.isNull(), E_FAIL);
11569 }
11570
11571 return directControl->UpdateMachineState(mData->mMachineState);
11572}
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