VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MachineImpl.cpp@ 68071

Last change on this file since 68071 was 68024, checked in by vboxsync, 7 years ago

IUnattended,IMachine: Changed IUnattended to a pure action object with a factory method instead of an attribute. Added more attributes: scriptTemplatePath, validationKitIsoPath, installTestExecService, and (readonly) machine. Only the first and also of those actually do anything at the moment.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 518.7 KB
Line 
1/* $Id: MachineImpl.cpp 68024 2017-07-18 13:54:10Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2004-2017 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#include "Logging.h"
27#include "VirtualBoxImpl.h"
28#include "MachineImpl.h"
29#include "ClientToken.h"
30#include "ProgressImpl.h"
31#include "ProgressProxyImpl.h"
32#include "MediumAttachmentImpl.h"
33#include "MediumImpl.h"
34#include "MediumLock.h"
35#include "USBControllerImpl.h"
36#include "USBDeviceFiltersImpl.h"
37#include "HostImpl.h"
38#include "SharedFolderImpl.h"
39#include "GuestOSTypeImpl.h"
40#include "VirtualBoxErrorInfoImpl.h"
41#include "StorageControllerImpl.h"
42#include "DisplayImpl.h"
43#include "DisplayUtils.h"
44#include "MachineImplCloneVM.h"
45#include "AutostartDb.h"
46#ifdef VBOX_WITH_UNATTENDED
47# include "UnattendedImpl.h"
48#endif
49#include "SystemPropertiesImpl.h"
50
51// generated header
52#include "VBoxEvents.h"
53
54#ifdef VBOX_WITH_USB
55# include "USBProxyService.h"
56#endif
57
58#include "AutoCaller.h"
59#include "HashedPw.h"
60#include "Performance.h"
61
62#include <iprt/asm.h>
63#include <iprt/path.h>
64#include <iprt/dir.h>
65#include <iprt/env.h>
66#include <iprt/lockvalidator.h>
67#include <iprt/process.h>
68#include <iprt/cpp/utils.h>
69#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
70#include <iprt/sha.h>
71#include <iprt/string.h>
72
73#include <VBox/com/array.h>
74#include <VBox/com/list.h>
75
76#include <VBox/err.h>
77#include <VBox/param.h>
78#include <VBox/settings.h>
79#include <VBox/vmm/ssm.h>
80
81#ifdef VBOX_WITH_GUEST_PROPS
82# include <VBox/HostServices/GuestPropertySvc.h>
83# include <VBox/com/array.h>
84#endif
85
86#include "VBox/com/MultiResult.h"
87
88#include <algorithm>
89
90#ifdef VBOX_WITH_DTRACE_R3_MAIN
91# include "dtrace/VBoxAPI.h"
92#endif
93
94#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
95# define HOSTSUFF_EXE ".exe"
96#else /* !RT_OS_WINDOWS */
97# define HOSTSUFF_EXE ""
98#endif /* !RT_OS_WINDOWS */
99
100// defines / prototypes
101/////////////////////////////////////////////////////////////////////////////
102
103/////////////////////////////////////////////////////////////////////////////
104// Machine::Data structure
105/////////////////////////////////////////////////////////////////////////////
106
107Machine::Data::Data()
108{
109 mRegistered = FALSE;
110 pMachineConfigFile = NULL;
111 /* Contains hints on what has changed when the user is using the VM (config
112 * changes, running the VM, ...). This is used to decide if a config needs
113 * to be written to disk. */
114 flModifications = 0;
115 /* VM modification usually also trigger setting the current state to
116 * "Modified". Although this is not always the case. An e.g. is the VM
117 * initialization phase or when snapshot related data is changed. The
118 * actually behavior is controlled by the following flag. */
119 m_fAllowStateModification = false;
120 mAccessible = FALSE;
121 /* mUuid is initialized in Machine::init() */
122
123 mMachineState = MachineState_PoweredOff;
124 RTTimeNow(&mLastStateChange);
125
126 mMachineStateDeps = 0;
127 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
128 mMachineStateChangePending = 0;
129
130 mCurrentStateModified = TRUE;
131 mGuestPropertiesModified = FALSE;
132
133 mSession.mPID = NIL_RTPROCESS;
134 mSession.mLockType = LockType_Null;
135 mSession.mState = SessionState_Unlocked;
136}
137
138Machine::Data::~Data()
139{
140 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
141 {
142 RTSemEventMultiDestroy(mMachineStateDepsSem);
143 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
144 }
145 if (pMachineConfigFile)
146 {
147 delete pMachineConfigFile;
148 pMachineConfigFile = NULL;
149 }
150}
151
152/////////////////////////////////////////////////////////////////////////////
153// Machine::HWData structure
154/////////////////////////////////////////////////////////////////////////////
155
156Machine::HWData::HWData()
157{
158 /* default values for a newly created machine */
159 mHWVersion = Utf8StrFmt("%d", SchemaDefs::DefaultHardwareVersion);
160 mMemorySize = 128;
161 mCPUCount = 1;
162 mCPUHotPlugEnabled = false;
163 mMemoryBalloonSize = 0;
164 mPageFusionEnabled = false;
165 mGraphicsControllerType = GraphicsControllerType_VBoxVGA;
166 mVRAMSize = 8;
167 mAccelerate3DEnabled = false;
168 mAccelerate2DVideoEnabled = false;
169 mMonitorCount = 1;
170 mVideoCaptureWidth = 1024;
171 mVideoCaptureHeight = 768;
172 mVideoCaptureRate = 512;
173 mVideoCaptureFPS = 25;
174 mVideoCaptureMaxTime = 0;
175 mVideoCaptureMaxFileSize = 0;
176 mVideoCaptureEnabled = false;
177 for (unsigned i = 0; i < RT_ELEMENTS(maVideoCaptureScreens); ++i)
178 maVideoCaptureScreens[i] = true;
179
180 mHWVirtExEnabled = true;
181 mHWVirtExNestedPagingEnabled = true;
182#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
183 mHWVirtExLargePagesEnabled = true;
184#else
185 /* Not supported on 32 bits hosts. */
186 mHWVirtExLargePagesEnabled = false;
187#endif
188 mHWVirtExVPIDEnabled = true;
189 mHWVirtExUXEnabled = true;
190 mHWVirtExForceEnabled = false;
191#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
192 mPAEEnabled = true;
193#else
194 mPAEEnabled = false;
195#endif
196 mLongMode = HC_ARCH_BITS == 64 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
197 mTripleFaultReset = false;
198 mAPIC = true;
199 mX2APIC = false;
200 mHPETEnabled = false;
201 mCpuExecutionCap = 100; /* Maximum CPU execution cap by default. */
202 mCpuIdPortabilityLevel = 0;
203 mCpuProfile = "host";
204
205 /* default boot order: floppy - DVD - HDD */
206 mBootOrder[0] = DeviceType_Floppy;
207 mBootOrder[1] = DeviceType_DVD;
208 mBootOrder[2] = DeviceType_HardDisk;
209 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
210 mBootOrder[i] = DeviceType_Null;
211
212 mClipboardMode = ClipboardMode_Disabled;
213 mDnDMode = DnDMode_Disabled;
214
215 mFirmwareType = FirmwareType_BIOS;
216 mKeyboardHIDType = KeyboardHIDType_PS2Keyboard;
217 mPointingHIDType = PointingHIDType_PS2Mouse;
218 mChipsetType = ChipsetType_PIIX3;
219 mParavirtProvider = ParavirtProvider_Default;
220 mEmulatedUSBCardReaderEnabled = FALSE;
221
222 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); ++i)
223 mCPUAttached[i] = false;
224
225 mIOCacheEnabled = true;
226 mIOCacheSize = 5; /* 5MB */
227}
228
229Machine::HWData::~HWData()
230{
231}
232
233/////////////////////////////////////////////////////////////////////////////
234// Machine class
235/////////////////////////////////////////////////////////////////////////////
236
237// constructor / destructor
238/////////////////////////////////////////////////////////////////////////////
239
240Machine::Machine() :
241#ifdef VBOX_WITH_RESOURCE_USAGE_API
242 mCollectorGuest(NULL),
243#endif
244 mPeer(NULL),
245 mParent(NULL),
246 mSerialPorts(),
247 mParallelPorts(),
248 uRegistryNeedsSaving(0)
249{}
250
251Machine::~Machine()
252{}
253
254HRESULT Machine::FinalConstruct()
255{
256 LogFlowThisFunc(("\n"));
257 return BaseFinalConstruct();
258}
259
260void Machine::FinalRelease()
261{
262 LogFlowThisFunc(("\n"));
263 uninit();
264 BaseFinalRelease();
265}
266
267/**
268 * Initializes a new machine instance; this init() variant creates a new, empty machine.
269 * This gets called from VirtualBox::CreateMachine().
270 *
271 * @param aParent Associated parent object
272 * @param strConfigFile Local file system path to the VM settings file (can
273 * be relative to the VirtualBox config directory).
274 * @param strName name for the machine
275 * @param llGroups list of groups for the machine
276 * @param aOsType OS Type of this machine or NULL.
277 * @param aId UUID for the new machine.
278 * @param fForceOverwrite Whether to overwrite an existing machine settings file.
279 * @param fDirectoryIncludesUUID Whether the use a special VM directory naming
280 * scheme (includes the UUID).
281 *
282 * @return Success indicator. if not S_OK, the machine object is invalid
283 */
284HRESULT Machine::init(VirtualBox *aParent,
285 const Utf8Str &strConfigFile,
286 const Utf8Str &strName,
287 const StringsList &llGroups,
288 GuestOSType *aOsType,
289 const Guid &aId,
290 bool fForceOverwrite,
291 bool fDirectoryIncludesUUID)
292{
293 LogFlowThisFuncEnter();
294 LogFlowThisFunc(("(Init_New) aConfigFile='%s'\n", strConfigFile.c_str()));
295
296 /* Enclose the state transition NotReady->InInit->Ready */
297 AutoInitSpan autoInitSpan(this);
298 AssertReturn(autoInitSpan.isOk(), E_FAIL);
299
300 HRESULT rc = initImpl(aParent, strConfigFile);
301 if (FAILED(rc)) return rc;
302
303 rc = i_tryCreateMachineConfigFile(fForceOverwrite);
304 if (FAILED(rc)) return rc;
305
306 if (SUCCEEDED(rc))
307 {
308 // create an empty machine config
309 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
310
311 rc = initDataAndChildObjects();
312 }
313
314 if (SUCCEEDED(rc))
315 {
316 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
317 mData->mAccessible = TRUE;
318
319 unconst(mData->mUuid) = aId;
320
321 mUserData->s.strName = strName;
322
323 mUserData->s.llGroups = llGroups;
324
325 mUserData->s.fDirectoryIncludesUUID = fDirectoryIncludesUUID;
326 // the "name sync" flag determines whether the machine directory gets renamed along
327 // with the machine file; say so if the settings file name is the same as the
328 // settings file parent directory (machine directory)
329 mUserData->s.fNameSync = i_isInOwnDir();
330
331 // initialize the default snapshots folder
332 rc = COMSETTER(SnapshotFolder)(NULL);
333 AssertComRC(rc);
334
335 if (aOsType)
336 {
337 /* Store OS type */
338 mUserData->s.strOsType = aOsType->i_id();
339
340 /* Apply BIOS defaults */
341 mBIOSSettings->i_applyDefaults(aOsType);
342
343 /* Let the OS type select 64-bit ness. */
344 mHWData->mLongMode = aOsType->i_is64Bit()
345 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
346
347 /* Let the OS type enable the X2APIC */
348 mHWData->mX2APIC = aOsType->i_recommendedX2APIC();
349 }
350
351 /* Apply network adapters defaults */
352 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
353 mNetworkAdapters[slot]->i_applyDefaults(aOsType);
354
355 /* Apply serial port defaults */
356 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
357 mSerialPorts[slot]->i_applyDefaults(aOsType);
358
359 /* Apply parallel port defaults */
360 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
361 mParallelPorts[slot]->i_applyDefaults();
362
363 /* At this point the changing of the current state modification
364 * flag is allowed. */
365 i_allowStateModification();
366
367 /* commit all changes made during the initialization */
368 i_commit();
369 }
370
371 /* Confirm a successful initialization when it's the case */
372 if (SUCCEEDED(rc))
373 {
374 if (mData->mAccessible)
375 autoInitSpan.setSucceeded();
376 else
377 autoInitSpan.setLimited();
378 }
379
380 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool, rc=%08X\n",
381 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
382 mData->mRegistered,
383 mData->mAccessible,
384 rc));
385
386 LogFlowThisFuncLeave();
387
388 return rc;
389}
390
391/**
392 * Initializes a new instance with data from machine XML (formerly Init_Registered).
393 * Gets called in two modes:
394 *
395 * -- from VirtualBox::initMachines() during VirtualBox startup; in that case, the
396 * UUID is specified and we mark the machine as "registered";
397 *
398 * -- from the public VirtualBox::OpenMachine() API, in which case the UUID is NULL
399 * and the machine remains unregistered until RegisterMachine() is called.
400 *
401 * @param aParent Associated parent object
402 * @param strConfigFile Local file system path to the VM settings file (can
403 * be relative to the VirtualBox config directory).
404 * @param aId UUID of the machine or NULL (see above).
405 *
406 * @return Success indicator. if not S_OK, the machine object is invalid
407 */
408HRESULT Machine::initFromSettings(VirtualBox *aParent,
409 const Utf8Str &strConfigFile,
410 const Guid *aId)
411{
412 LogFlowThisFuncEnter();
413 LogFlowThisFunc(("(Init_Registered) aConfigFile='%s\n", strConfigFile.c_str()));
414
415 /* Enclose the state transition NotReady->InInit->Ready */
416 AutoInitSpan autoInitSpan(this);
417 AssertReturn(autoInitSpan.isOk(), E_FAIL);
418
419 HRESULT rc = initImpl(aParent, strConfigFile);
420 if (FAILED(rc)) return rc;
421
422 if (aId)
423 {
424 // loading a registered VM:
425 unconst(mData->mUuid) = *aId;
426 mData->mRegistered = TRUE;
427 // now load the settings from XML:
428 rc = i_registeredInit();
429 // this calls initDataAndChildObjects() and loadSettings()
430 }
431 else
432 {
433 // opening an unregistered VM (VirtualBox::OpenMachine()):
434 rc = initDataAndChildObjects();
435
436 if (SUCCEEDED(rc))
437 {
438 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
439 mData->mAccessible = TRUE;
440
441 try
442 {
443 // load and parse machine XML; this will throw on XML or logic errors
444 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
445
446 // reject VM UUID duplicates, they can happen if someone
447 // tries to register an already known VM config again
448 if (aParent->i_findMachine(mData->pMachineConfigFile->uuid,
449 true /* fPermitInaccessible */,
450 false /* aDoSetError */,
451 NULL) != VBOX_E_OBJECT_NOT_FOUND)
452 {
453 throw setError(E_FAIL,
454 tr("Trying to open a VM config '%s' which has the same UUID as an existing virtual machine"),
455 mData->m_strConfigFile.c_str());
456 }
457
458 // use UUID from machine config
459 unconst(mData->mUuid) = mData->pMachineConfigFile->uuid;
460
461 rc = i_loadMachineDataFromSettings(*mData->pMachineConfigFile,
462 NULL /* puuidRegistry */);
463 if (FAILED(rc)) throw rc;
464
465 /* At this point the changing of the current state modification
466 * flag is allowed. */
467 i_allowStateModification();
468
469 i_commit();
470 }
471 catch (HRESULT err)
472 {
473 /* we assume that error info is set by the thrower */
474 rc = err;
475 }
476 catch (...)
477 {
478 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
479 }
480 }
481 }
482
483 /* Confirm a successful initialization when it's the case */
484 if (SUCCEEDED(rc))
485 {
486 if (mData->mAccessible)
487 autoInitSpan.setSucceeded();
488 else
489 {
490 autoInitSpan.setLimited();
491
492 // uninit media from this machine's media registry, or else
493 // reloading the settings will fail
494 mParent->i_unregisterMachineMedia(i_getId());
495 }
496 }
497
498 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
499 "rc=%08X\n",
500 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
501 mData->mRegistered, mData->mAccessible, rc));
502
503 LogFlowThisFuncLeave();
504
505 return rc;
506}
507
508/**
509 * Initializes a new instance from a machine config that is already in memory
510 * (import OVF case). Since we are importing, the UUID in the machine
511 * config is ignored and we always generate a fresh one.
512 *
513 * @param aParent Associated parent object.
514 * @param strName Name for the new machine; this overrides what is specified in config and is used
515 * for the settings file as well.
516 * @param config Machine configuration loaded and parsed from XML.
517 *
518 * @return Success indicator. if not S_OK, the machine object is invalid
519 */
520HRESULT Machine::init(VirtualBox *aParent,
521 const Utf8Str &strName,
522 const settings::MachineConfigFile &config)
523{
524 LogFlowThisFuncEnter();
525
526 /* Enclose the state transition NotReady->InInit->Ready */
527 AutoInitSpan autoInitSpan(this);
528 AssertReturn(autoInitSpan.isOk(), E_FAIL);
529
530 Utf8Str strConfigFile;
531 aParent->i_getDefaultMachineFolder(strConfigFile);
532 strConfigFile.append(RTPATH_DELIMITER);
533 strConfigFile.append(strName);
534 strConfigFile.append(RTPATH_DELIMITER);
535 strConfigFile.append(strName);
536 strConfigFile.append(".vbox");
537
538 HRESULT rc = initImpl(aParent, strConfigFile);
539 if (FAILED(rc)) return rc;
540
541 rc = i_tryCreateMachineConfigFile(false /* fForceOverwrite */);
542 if (FAILED(rc)) return rc;
543
544 rc = initDataAndChildObjects();
545
546 if (SUCCEEDED(rc))
547 {
548 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
549 mData->mAccessible = TRUE;
550
551 // create empty machine config for instance data
552 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
553
554 // generate fresh UUID, ignore machine config
555 unconst(mData->mUuid).create();
556
557 rc = i_loadMachineDataFromSettings(config,
558 &mData->mUuid); // puuidRegistry: initialize media with this registry ID
559
560 // override VM name as well, it may be different
561 mUserData->s.strName = strName;
562
563 if (SUCCEEDED(rc))
564 {
565 /* At this point the changing of the current state modification
566 * flag is allowed. */
567 i_allowStateModification();
568
569 /* commit all changes made during the initialization */
570 i_commit();
571 }
572 }
573
574 /* Confirm a successful initialization when it's the case */
575 if (SUCCEEDED(rc))
576 {
577 if (mData->mAccessible)
578 autoInitSpan.setSucceeded();
579 else
580 {
581 /* Ignore all errors from unregistering, they would destroy
582- * the more interesting error information we already have,
583- * pinpointing the issue with the VM config. */
584 ErrorInfoKeeper eik;
585
586 autoInitSpan.setLimited();
587
588 // uninit media from this machine's media registry, or else
589 // reloading the settings will fail
590 mParent->i_unregisterMachineMedia(i_getId());
591 }
592 }
593
594 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
595 "rc=%08X\n",
596 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
597 mData->mRegistered, mData->mAccessible, rc));
598
599 LogFlowThisFuncLeave();
600
601 return rc;
602}
603
604/**
605 * Shared code between the various init() implementations.
606 * @param aParent The VirtualBox object.
607 * @param strConfigFile Settings file.
608 * @return
609 */
610HRESULT Machine::initImpl(VirtualBox *aParent,
611 const Utf8Str &strConfigFile)
612{
613 LogFlowThisFuncEnter();
614
615 AssertReturn(aParent, E_INVALIDARG);
616 AssertReturn(!strConfigFile.isEmpty(), E_INVALIDARG);
617
618 HRESULT rc = S_OK;
619
620 /* share the parent weakly */
621 unconst(mParent) = aParent;
622
623 /* allocate the essential machine data structure (the rest will be
624 * allocated later by initDataAndChildObjects() */
625 mData.allocate();
626
627 /* memorize the config file name (as provided) */
628 mData->m_strConfigFile = strConfigFile;
629
630 /* get the full file name */
631 int vrc1 = mParent->i_calculateFullPath(strConfigFile, mData->m_strConfigFileFull);
632 if (RT_FAILURE(vrc1))
633 return setError(VBOX_E_FILE_ERROR,
634 tr("Invalid machine settings file name '%s' (%Rrc)"),
635 strConfigFile.c_str(),
636 vrc1);
637
638 LogFlowThisFuncLeave();
639
640 return rc;
641}
642
643/**
644 * Tries to create a machine settings file in the path stored in the machine
645 * instance data. Used when a new machine is created to fail gracefully if
646 * the settings file could not be written (e.g. because machine dir is read-only).
647 * @return
648 */
649HRESULT Machine::i_tryCreateMachineConfigFile(bool fForceOverwrite)
650{
651 HRESULT rc = S_OK;
652
653 // when we create a new machine, we must be able to create the settings file
654 RTFILE f = NIL_RTFILE;
655 int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
656 if ( RT_SUCCESS(vrc)
657 || vrc == VERR_SHARING_VIOLATION
658 )
659 {
660 if (RT_SUCCESS(vrc))
661 RTFileClose(f);
662 if (!fForceOverwrite)
663 rc = setError(VBOX_E_FILE_ERROR,
664 tr("Machine settings file '%s' already exists"),
665 mData->m_strConfigFileFull.c_str());
666 else
667 {
668 /* try to delete the config file, as otherwise the creation
669 * of a new settings file will fail. */
670 int vrc2 = RTFileDelete(mData->m_strConfigFileFull.c_str());
671 if (RT_FAILURE(vrc2))
672 rc = setError(VBOX_E_FILE_ERROR,
673 tr("Could not delete the existing settings file '%s' (%Rrc)"),
674 mData->m_strConfigFileFull.c_str(), vrc2);
675 }
676 }
677 else if ( vrc != VERR_FILE_NOT_FOUND
678 && vrc != VERR_PATH_NOT_FOUND
679 )
680 rc = setError(VBOX_E_FILE_ERROR,
681 tr("Invalid machine settings file name '%s' (%Rrc)"),
682 mData->m_strConfigFileFull.c_str(),
683 vrc);
684 return rc;
685}
686
687/**
688 * Initializes the registered machine by loading the settings file.
689 * This method is separated from #init() in order to make it possible to
690 * retry the operation after VirtualBox startup instead of refusing to
691 * startup the whole VirtualBox server in case if the settings file of some
692 * registered VM is invalid or inaccessible.
693 *
694 * @note Must be always called from this object's write lock
695 * (unless called from #init() that doesn't need any locking).
696 * @note Locks the mUSBController method for writing.
697 * @note Subclasses must not call this method.
698 */
699HRESULT Machine::i_registeredInit()
700{
701 AssertReturn(!i_isSessionMachine(), E_FAIL);
702 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
703 AssertReturn(mData->mUuid.isValid(), E_FAIL);
704 AssertReturn(!mData->mAccessible, E_FAIL);
705
706 HRESULT rc = initDataAndChildObjects();
707
708 if (SUCCEEDED(rc))
709 {
710 /* Temporarily reset the registered flag in order to let setters
711 * potentially called from loadSettings() succeed (isMutable() used in
712 * all setters will return FALSE for a Machine instance if mRegistered
713 * is TRUE). */
714 mData->mRegistered = FALSE;
715
716 try
717 {
718 // load and parse machine XML; this will throw on XML or logic errors
719 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
720
721 if (mData->mUuid != mData->pMachineConfigFile->uuid)
722 throw setError(E_FAIL,
723 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
724 mData->pMachineConfigFile->uuid.raw(),
725 mData->m_strConfigFileFull.c_str(),
726 mData->mUuid.toString().c_str(),
727 mParent->i_settingsFilePath().c_str());
728
729 rc = i_loadMachineDataFromSettings(*mData->pMachineConfigFile,
730 NULL /* const Guid *puuidRegistry */);
731 if (FAILED(rc)) throw rc;
732 }
733 catch (HRESULT err)
734 {
735 /* we assume that error info is set by the thrower */
736 rc = err;
737 }
738 catch (...)
739 {
740 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
741 }
742
743 /* Restore the registered flag (even on failure) */
744 mData->mRegistered = TRUE;
745 }
746
747 if (SUCCEEDED(rc))
748 {
749 /* Set mAccessible to TRUE only if we successfully locked and loaded
750 * the settings file */
751 mData->mAccessible = TRUE;
752
753 /* commit all changes made during loading the settings file */
754 i_commit(); /// @todo r=dj why do we need a commit during init?!? this is very expensive
755 /// @todo r=klaus for some reason the settings loading logic backs up
756 // the settings, and therefore a commit is needed. Should probably be changed.
757 }
758 else
759 {
760 /* If the machine is registered, then, instead of returning a
761 * failure, we mark it as inaccessible and set the result to
762 * success to give it a try later */
763
764 /* fetch the current error info */
765 mData->mAccessError = com::ErrorInfo();
766 Log1Warning(("Machine {%RTuuid} is inaccessible! [%ls]\n", mData->mUuid.raw(), mData->mAccessError.getText().raw()));
767
768 /* rollback all changes */
769 i_rollback(false /* aNotify */);
770
771 // uninit media from this machine's media registry, or else
772 // reloading the settings will fail
773 mParent->i_unregisterMachineMedia(i_getId());
774
775 /* uninitialize the common part to make sure all data is reset to
776 * default (null) values */
777 uninitDataAndChildObjects();
778
779 rc = S_OK;
780 }
781
782 return rc;
783}
784
785/**
786 * Uninitializes the instance.
787 * Called either from FinalRelease() or by the parent when it gets destroyed.
788 *
789 * @note The caller of this method must make sure that this object
790 * a) doesn't have active callers on the current thread and b) is not locked
791 * by the current thread; otherwise uninit() will hang either a) due to
792 * AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
793 * a dead-lock caused by this thread waiting for all callers on the other
794 * threads are done but preventing them from doing so by holding a lock.
795 */
796void Machine::uninit()
797{
798 LogFlowThisFuncEnter();
799
800 Assert(!isWriteLockOnCurrentThread());
801
802 Assert(!uRegistryNeedsSaving);
803 if (uRegistryNeedsSaving)
804 {
805 AutoCaller autoCaller(this);
806 if (SUCCEEDED(autoCaller.rc()))
807 {
808 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
809 i_saveSettings(NULL, Machine::SaveS_Force);
810 }
811 }
812
813 /* Enclose the state transition Ready->InUninit->NotReady */
814 AutoUninitSpan autoUninitSpan(this);
815 if (autoUninitSpan.uninitDone())
816 return;
817
818 Assert(!i_isSnapshotMachine());
819 Assert(!i_isSessionMachine());
820 Assert(!!mData);
821
822 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
823 LogFlowThisFunc(("mRegistered=%d\n", mData->mRegistered));
824
825 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
826
827 if (!mData->mSession.mMachine.isNull())
828 {
829 /* Theoretically, this can only happen if the VirtualBox server has been
830 * terminated while there were clients running that owned open direct
831 * sessions. Since in this case we are definitely called by
832 * VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
833 * won't happen on the client watcher thread (because it has a
834 * VirtualBox caller for the duration of the
835 * SessionMachine::i_checkForDeath() call, so that VirtualBox::uninit()
836 * cannot happen until the VirtualBox caller is released). This is
837 * important, because SessionMachine::uninit() cannot correctly operate
838 * after we return from this method (it expects the Machine instance is
839 * still valid). We'll call it ourselves below.
840 */
841 Log1WarningThisFunc(("Session machine is not NULL (%p), the direct session is still open!\n",
842 (SessionMachine*)mData->mSession.mMachine));
843
844 if (Global::IsOnlineOrTransient(mData->mMachineState))
845 {
846 Log1WarningThisFunc(("Setting state to Aborted!\n"));
847 /* set machine state using SessionMachine reimplementation */
848 static_cast<Machine*>(mData->mSession.mMachine)->i_setMachineState(MachineState_Aborted);
849 }
850
851 /*
852 * Uninitialize SessionMachine using public uninit() to indicate
853 * an unexpected uninitialization.
854 */
855 mData->mSession.mMachine->uninit();
856 /* SessionMachine::uninit() must set mSession.mMachine to null */
857 Assert(mData->mSession.mMachine.isNull());
858 }
859
860 // uninit media from this machine's media registry, if they're still there
861 Guid uuidMachine(i_getId());
862
863 /* the lock is no more necessary (SessionMachine is uninitialized) */
864 alock.release();
865
866 /* XXX This will fail with
867 * "cannot be closed because it is still attached to 1 virtual machines"
868 * because at this point we did not call uninitDataAndChildObjects() yet
869 * and therefore also removeBackReference() for all these mediums was not called! */
870
871 if (uuidMachine.isValid() && !uuidMachine.isZero()) // can be empty if we're called from a failure of Machine::init
872 mParent->i_unregisterMachineMedia(uuidMachine);
873
874 // has machine been modified?
875 if (mData->flModifications)
876 {
877 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
878 i_rollback(false /* aNotify */);
879 }
880
881 if (mData->mAccessible)
882 uninitDataAndChildObjects();
883
884 /* free the essential data structure last */
885 mData.free();
886
887 LogFlowThisFuncLeave();
888}
889
890// Wrapped IMachine properties
891/////////////////////////////////////////////////////////////////////////////
892HRESULT Machine::getParent(ComPtr<IVirtualBox> &aParent)
893{
894 /* mParent is constant during life time, no need to lock */
895 ComObjPtr<VirtualBox> pVirtualBox(mParent);
896 aParent = pVirtualBox;
897
898 return S_OK;
899}
900
901
902HRESULT Machine::getAccessible(BOOL *aAccessible)
903{
904 /* In some cases (medium registry related), it is necessary to be able to
905 * go through the list of all machines. Happens when an inaccessible VM
906 * has a sensible medium registry. */
907 AutoReadLock mllock(mParent->i_getMachinesListLockHandle() COMMA_LOCKVAL_SRC_POS);
908 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
909
910 HRESULT rc = S_OK;
911
912 if (!mData->mAccessible)
913 {
914 /* try to initialize the VM once more if not accessible */
915
916 AutoReinitSpan autoReinitSpan(this);
917 AssertReturn(autoReinitSpan.isOk(), E_FAIL);
918
919#ifdef DEBUG
920 LogFlowThisFunc(("Dumping media backreferences\n"));
921 mParent->i_dumpAllBackRefs();
922#endif
923
924 if (mData->pMachineConfigFile)
925 {
926 // reset the XML file to force loadSettings() (called from i_registeredInit())
927 // to parse it again; the file might have changed
928 delete mData->pMachineConfigFile;
929 mData->pMachineConfigFile = NULL;
930 }
931
932 rc = i_registeredInit();
933
934 if (SUCCEEDED(rc) && mData->mAccessible)
935 {
936 autoReinitSpan.setSucceeded();
937
938 /* make sure interesting parties will notice the accessibility
939 * state change */
940 mParent->i_onMachineStateChange(mData->mUuid, mData->mMachineState);
941 mParent->i_onMachineDataChange(mData->mUuid);
942 }
943 }
944
945 if (SUCCEEDED(rc))
946 *aAccessible = mData->mAccessible;
947
948 LogFlowThisFuncLeave();
949
950 return rc;
951}
952
953HRESULT Machine::getAccessError(ComPtr<IVirtualBoxErrorInfo> &aAccessError)
954{
955 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
956
957 if (mData->mAccessible || !mData->mAccessError.isBasicAvailable())
958 {
959 /* return shortly */
960 aAccessError = NULL;
961 return S_OK;
962 }
963
964 HRESULT rc = S_OK;
965
966 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
967 rc = errorInfo.createObject();
968 if (SUCCEEDED(rc))
969 {
970 errorInfo->init(mData->mAccessError.getResultCode(),
971 mData->mAccessError.getInterfaceID().ref(),
972 Utf8Str(mData->mAccessError.getComponent()).c_str(),
973 Utf8Str(mData->mAccessError.getText()));
974 aAccessError = errorInfo;
975 }
976
977 return rc;
978}
979
980HRESULT Machine::getName(com::Utf8Str &aName)
981{
982 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
983
984 aName = mUserData->s.strName;
985
986 return S_OK;
987}
988
989HRESULT Machine::setName(const com::Utf8Str &aName)
990{
991 // prohibit setting a UUID only as the machine name, or else it can
992 // never be found by findMachine()
993 Guid test(aName);
994
995 if (test.isValid())
996 return setError(E_INVALIDARG, tr("A machine cannot have a UUID as its name"));
997
998 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
999
1000 HRESULT rc = i_checkStateDependency(MutableStateDep);
1001 if (FAILED(rc)) return rc;
1002
1003 i_setModified(IsModified_MachineData);
1004 mUserData.backup();
1005 mUserData->s.strName = aName;
1006
1007 return S_OK;
1008}
1009
1010HRESULT Machine::getDescription(com::Utf8Str &aDescription)
1011{
1012 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1013
1014 aDescription = mUserData->s.strDescription;
1015
1016 return S_OK;
1017}
1018
1019HRESULT Machine::setDescription(const com::Utf8Str &aDescription)
1020{
1021 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1022
1023 // this can be done in principle in any state as it doesn't affect the VM
1024 // significantly, but play safe by not messing around while complex
1025 // activities are going on
1026 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
1027 if (FAILED(rc)) return rc;
1028
1029 i_setModified(IsModified_MachineData);
1030 mUserData.backup();
1031 mUserData->s.strDescription = aDescription;
1032
1033 return S_OK;
1034}
1035
1036HRESULT Machine::getId(com::Guid &aId)
1037{
1038 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1039
1040 aId = mData->mUuid;
1041
1042 return S_OK;
1043}
1044
1045HRESULT Machine::getGroups(std::vector<com::Utf8Str> &aGroups)
1046{
1047 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1048 aGroups.resize(mUserData->s.llGroups.size());
1049 size_t i = 0;
1050 for (StringsList::const_iterator
1051 it = mUserData->s.llGroups.begin();
1052 it != mUserData->s.llGroups.end();
1053 ++it, ++i)
1054 aGroups[i] = (*it);
1055
1056 return S_OK;
1057}
1058
1059HRESULT Machine::setGroups(const std::vector<com::Utf8Str> &aGroups)
1060{
1061 StringsList llGroups;
1062 HRESULT rc = mParent->i_convertMachineGroups(aGroups, &llGroups);
1063 if (FAILED(rc))
1064 return rc;
1065
1066 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1067
1068 rc = i_checkStateDependency(MutableOrSavedStateDep);
1069 if (FAILED(rc)) return rc;
1070
1071 i_setModified(IsModified_MachineData);
1072 mUserData.backup();
1073 mUserData->s.llGroups = llGroups;
1074
1075 return S_OK;
1076}
1077
1078HRESULT Machine::getOSTypeId(com::Utf8Str &aOSTypeId)
1079{
1080 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1081
1082 aOSTypeId = mUserData->s.strOsType;
1083
1084 return S_OK;
1085}
1086
1087HRESULT Machine::setOSTypeId(const com::Utf8Str &aOSTypeId)
1088{
1089 /* look up the object by Id to check it is valid */
1090 ComObjPtr<GuestOSType> pGuestOSType;
1091 HRESULT rc = mParent->i_findGuestOSType(aOSTypeId,
1092 pGuestOSType);
1093 if (FAILED(rc)) return rc;
1094
1095 /* when setting, always use the "etalon" value for consistency -- lookup
1096 * by ID is case-insensitive and the input value may have different case */
1097 Utf8Str osTypeId = pGuestOSType->i_id();
1098
1099 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1100
1101 rc = i_checkStateDependency(MutableStateDep);
1102 if (FAILED(rc)) return rc;
1103
1104 i_setModified(IsModified_MachineData);
1105 mUserData.backup();
1106 mUserData->s.strOsType = osTypeId;
1107
1108 return S_OK;
1109}
1110
1111HRESULT Machine::getFirmwareType(FirmwareType_T *aFirmwareType)
1112{
1113 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1114
1115 *aFirmwareType = mHWData->mFirmwareType;
1116
1117 return S_OK;
1118}
1119
1120HRESULT Machine::setFirmwareType(FirmwareType_T aFirmwareType)
1121{
1122 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1123
1124 HRESULT rc = i_checkStateDependency(MutableStateDep);
1125 if (FAILED(rc)) return rc;
1126
1127 i_setModified(IsModified_MachineData);
1128 mHWData.backup();
1129 mHWData->mFirmwareType = aFirmwareType;
1130
1131 return S_OK;
1132}
1133
1134HRESULT Machine::getKeyboardHIDType(KeyboardHIDType_T *aKeyboardHIDType)
1135{
1136 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1137
1138 *aKeyboardHIDType = mHWData->mKeyboardHIDType;
1139
1140 return S_OK;
1141}
1142
1143HRESULT Machine::setKeyboardHIDType(KeyboardHIDType_T aKeyboardHIDType)
1144{
1145 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1146
1147 HRESULT rc = i_checkStateDependency(MutableStateDep);
1148 if (FAILED(rc)) return rc;
1149
1150 i_setModified(IsModified_MachineData);
1151 mHWData.backup();
1152 mHWData->mKeyboardHIDType = aKeyboardHIDType;
1153
1154 return S_OK;
1155}
1156
1157HRESULT Machine::getPointingHIDType(PointingHIDType_T *aPointingHIDType)
1158{
1159 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1160
1161 *aPointingHIDType = mHWData->mPointingHIDType;
1162
1163 return S_OK;
1164}
1165
1166HRESULT Machine::setPointingHIDType(PointingHIDType_T aPointingHIDType)
1167{
1168 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1169
1170 HRESULT rc = i_checkStateDependency(MutableStateDep);
1171 if (FAILED(rc)) return rc;
1172
1173 i_setModified(IsModified_MachineData);
1174 mHWData.backup();
1175 mHWData->mPointingHIDType = aPointingHIDType;
1176
1177 return S_OK;
1178}
1179
1180HRESULT Machine::getChipsetType(ChipsetType_T *aChipsetType)
1181{
1182 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1183
1184 *aChipsetType = mHWData->mChipsetType;
1185
1186 return S_OK;
1187}
1188
1189HRESULT Machine::setChipsetType(ChipsetType_T aChipsetType)
1190{
1191 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1192
1193 HRESULT rc = i_checkStateDependency(MutableStateDep);
1194 if (FAILED(rc)) return rc;
1195
1196 if (aChipsetType != mHWData->mChipsetType)
1197 {
1198 i_setModified(IsModified_MachineData);
1199 mHWData.backup();
1200 mHWData->mChipsetType = aChipsetType;
1201
1202 // Resize network adapter array, to be finalized on commit/rollback.
1203 // We must not throw away entries yet, otherwise settings are lost
1204 // without a way to roll back.
1205 size_t newCount = Global::getMaxNetworkAdapters(aChipsetType);
1206 size_t oldCount = mNetworkAdapters.size();
1207 if (newCount > oldCount)
1208 {
1209 mNetworkAdapters.resize(newCount);
1210 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); slot++)
1211 {
1212 unconst(mNetworkAdapters[slot]).createObject();
1213 mNetworkAdapters[slot]->init(this, (ULONG)slot);
1214 }
1215 }
1216 }
1217
1218 return S_OK;
1219}
1220
1221HRESULT Machine::getParavirtDebug(com::Utf8Str &aParavirtDebug)
1222{
1223 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1224
1225 aParavirtDebug = mHWData->mParavirtDebug;
1226 return S_OK;
1227}
1228
1229HRESULT Machine::setParavirtDebug(const com::Utf8Str &aParavirtDebug)
1230{
1231 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1232
1233 HRESULT rc = i_checkStateDependency(MutableStateDep);
1234 if (FAILED(rc)) return rc;
1235
1236 /** @todo Parse/validate options? */
1237 if (aParavirtDebug != mHWData->mParavirtDebug)
1238 {
1239 i_setModified(IsModified_MachineData);
1240 mHWData.backup();
1241 mHWData->mParavirtDebug = aParavirtDebug;
1242 }
1243
1244 return S_OK;
1245}
1246
1247HRESULT Machine::getParavirtProvider(ParavirtProvider_T *aParavirtProvider)
1248{
1249 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1250
1251 *aParavirtProvider = mHWData->mParavirtProvider;
1252
1253 return S_OK;
1254}
1255
1256HRESULT Machine::setParavirtProvider(ParavirtProvider_T aParavirtProvider)
1257{
1258 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1259
1260 HRESULT rc = i_checkStateDependency(MutableStateDep);
1261 if (FAILED(rc)) return rc;
1262
1263 if (aParavirtProvider != mHWData->mParavirtProvider)
1264 {
1265 i_setModified(IsModified_MachineData);
1266 mHWData.backup();
1267 mHWData->mParavirtProvider = aParavirtProvider;
1268 }
1269
1270 return S_OK;
1271}
1272
1273HRESULT Machine::getEffectiveParavirtProvider(ParavirtProvider_T *aParavirtProvider)
1274{
1275 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1276
1277 *aParavirtProvider = mHWData->mParavirtProvider;
1278 switch (mHWData->mParavirtProvider)
1279 {
1280 case ParavirtProvider_None:
1281 case ParavirtProvider_HyperV:
1282 case ParavirtProvider_KVM:
1283 case ParavirtProvider_Minimal:
1284 break;
1285
1286 /* Resolve dynamic provider types to the effective types. */
1287 default:
1288 {
1289 ComObjPtr<GuestOSType> pGuestOSType;
1290 HRESULT hrc2 = mParent->i_findGuestOSType(mUserData->s.strOsType,
1291 pGuestOSType);
1292 AssertMsgReturn(SUCCEEDED(hrc2), ("Failed to get guest OS type. hrc2=%Rhrc\n", hrc2), hrc2);
1293
1294 Utf8Str guestTypeFamilyId = pGuestOSType->i_familyId();
1295 bool fOsXGuest = guestTypeFamilyId == "MacOS";
1296
1297 switch (mHWData->mParavirtProvider)
1298 {
1299 case ParavirtProvider_Legacy:
1300 {
1301 if (fOsXGuest)
1302 *aParavirtProvider = ParavirtProvider_Minimal;
1303 else
1304 *aParavirtProvider = ParavirtProvider_None;
1305 break;
1306 }
1307
1308 case ParavirtProvider_Default:
1309 {
1310 if (fOsXGuest)
1311 *aParavirtProvider = ParavirtProvider_Minimal;
1312 else if ( mUserData->s.strOsType == "Windows10"
1313 || mUserData->s.strOsType == "Windows10_64"
1314 || mUserData->s.strOsType == "Windows81"
1315 || mUserData->s.strOsType == "Windows81_64"
1316 || mUserData->s.strOsType == "Windows8"
1317 || mUserData->s.strOsType == "Windows8_64"
1318 || mUserData->s.strOsType == "Windows7"
1319 || mUserData->s.strOsType == "Windows7_64"
1320 || mUserData->s.strOsType == "WindowsVista"
1321 || mUserData->s.strOsType == "WindowsVista_64"
1322 || mUserData->s.strOsType == "Windows2012"
1323 || mUserData->s.strOsType == "Windows2012_64"
1324 || mUserData->s.strOsType == "Windows2008"
1325 || mUserData->s.strOsType == "Windows2008_64")
1326 {
1327 *aParavirtProvider = ParavirtProvider_HyperV;
1328 }
1329 else if ( mUserData->s.strOsType == "Linux26" // Linux22 and Linux24 omitted as they're too old
1330 || mUserData->s.strOsType == "Linux26_64" // for having any KVM paravirtualization support.
1331 || mUserData->s.strOsType == "Linux"
1332 || mUserData->s.strOsType == "Linux_64"
1333 || mUserData->s.strOsType == "ArchLinux"
1334 || mUserData->s.strOsType == "ArchLinux_64"
1335 || mUserData->s.strOsType == "Debian"
1336 || mUserData->s.strOsType == "Debian_64"
1337 || mUserData->s.strOsType == "Fedora"
1338 || mUserData->s.strOsType == "Fedora_64"
1339 || mUserData->s.strOsType == "Gentoo"
1340 || mUserData->s.strOsType == "Gentoo_64"
1341 || mUserData->s.strOsType == "Mandriva"
1342 || mUserData->s.strOsType == "Mandriva_64"
1343 || mUserData->s.strOsType == "OpenSUSE"
1344 || mUserData->s.strOsType == "OpenSUSE_64"
1345 || mUserData->s.strOsType == "Oracle"
1346 || mUserData->s.strOsType == "Oracle_64"
1347 || mUserData->s.strOsType == "RedHat"
1348 || mUserData->s.strOsType == "RedHat_64"
1349 || mUserData->s.strOsType == "Turbolinux"
1350 || mUserData->s.strOsType == "Turbolinux_64"
1351 || mUserData->s.strOsType == "Ubuntu"
1352 || mUserData->s.strOsType == "Ubuntu_64"
1353 || mUserData->s.strOsType == "Xandros"
1354 || mUserData->s.strOsType == "Xandros_64")
1355 {
1356 *aParavirtProvider = ParavirtProvider_KVM;
1357 }
1358 else
1359 *aParavirtProvider = ParavirtProvider_None;
1360 break;
1361 }
1362
1363 default: AssertFailedBreak(); /* Shut up MSC. */
1364 }
1365 break;
1366 }
1367 }
1368
1369 Assert( *aParavirtProvider == ParavirtProvider_None
1370 || *aParavirtProvider == ParavirtProvider_Minimal
1371 || *aParavirtProvider == ParavirtProvider_HyperV
1372 || *aParavirtProvider == ParavirtProvider_KVM);
1373 return S_OK;
1374}
1375
1376HRESULT Machine::getHardwareVersion(com::Utf8Str &aHardwareVersion)
1377{
1378 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1379
1380 aHardwareVersion = mHWData->mHWVersion;
1381
1382 return S_OK;
1383}
1384
1385HRESULT Machine::setHardwareVersion(const com::Utf8Str &aHardwareVersion)
1386{
1387 /* check known version */
1388 Utf8Str hwVersion = aHardwareVersion;
1389 if ( hwVersion.compare("1") != 0
1390 && hwVersion.compare("2") != 0) // VBox 2.1.x and later (VMMDev heap)
1391 return setError(E_INVALIDARG,
1392 tr("Invalid hardware version: %s\n"), aHardwareVersion.c_str());
1393
1394 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1395
1396 HRESULT rc = i_checkStateDependency(MutableStateDep);
1397 if (FAILED(rc)) return rc;
1398
1399 i_setModified(IsModified_MachineData);
1400 mHWData.backup();
1401 mHWData->mHWVersion = aHardwareVersion;
1402
1403 return S_OK;
1404}
1405
1406HRESULT Machine::getHardwareUUID(com::Guid &aHardwareUUID)
1407{
1408 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1409
1410 if (!mHWData->mHardwareUUID.isZero())
1411 aHardwareUUID = mHWData->mHardwareUUID;
1412 else
1413 aHardwareUUID = mData->mUuid;
1414
1415 return S_OK;
1416}
1417
1418HRESULT Machine::setHardwareUUID(const com::Guid &aHardwareUUID)
1419{
1420 if (!aHardwareUUID.isValid())
1421 return E_INVALIDARG;
1422
1423 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1424
1425 HRESULT rc = i_checkStateDependency(MutableStateDep);
1426 if (FAILED(rc)) return rc;
1427
1428 i_setModified(IsModified_MachineData);
1429 mHWData.backup();
1430 if (aHardwareUUID == mData->mUuid)
1431 mHWData->mHardwareUUID.clear();
1432 else
1433 mHWData->mHardwareUUID = aHardwareUUID;
1434
1435 return S_OK;
1436}
1437
1438HRESULT Machine::getMemorySize(ULONG *aMemorySize)
1439{
1440 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1441
1442 *aMemorySize = mHWData->mMemorySize;
1443
1444 return S_OK;
1445}
1446
1447HRESULT Machine::setMemorySize(ULONG aMemorySize)
1448{
1449 /* check RAM limits */
1450 if ( aMemorySize < MM_RAM_MIN_IN_MB
1451 || aMemorySize > MM_RAM_MAX_IN_MB
1452 )
1453 return setError(E_INVALIDARG,
1454 tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1455 aMemorySize, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
1456
1457 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1458
1459 HRESULT rc = i_checkStateDependency(MutableStateDep);
1460 if (FAILED(rc)) return rc;
1461
1462 i_setModified(IsModified_MachineData);
1463 mHWData.backup();
1464 mHWData->mMemorySize = aMemorySize;
1465
1466 return S_OK;
1467}
1468
1469HRESULT Machine::getCPUCount(ULONG *aCPUCount)
1470{
1471 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1472
1473 *aCPUCount = mHWData->mCPUCount;
1474
1475 return S_OK;
1476}
1477
1478HRESULT Machine::setCPUCount(ULONG aCPUCount)
1479{
1480 /* check CPU limits */
1481 if ( aCPUCount < SchemaDefs::MinCPUCount
1482 || aCPUCount > SchemaDefs::MaxCPUCount
1483 )
1484 return setError(E_INVALIDARG,
1485 tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
1486 aCPUCount, SchemaDefs::MinCPUCount, SchemaDefs::MaxCPUCount);
1487
1488 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1489
1490 /* We cant go below the current number of CPUs attached if hotplug is enabled*/
1491 if (mHWData->mCPUHotPlugEnabled)
1492 {
1493 for (unsigned idx = aCPUCount; idx < SchemaDefs::MaxCPUCount; idx++)
1494 {
1495 if (mHWData->mCPUAttached[idx])
1496 return setError(E_INVALIDARG,
1497 tr("There is still a CPU attached to socket %lu."
1498 "Detach the CPU before removing the socket"),
1499 aCPUCount, idx+1);
1500 }
1501 }
1502
1503 HRESULT rc = i_checkStateDependency(MutableStateDep);
1504 if (FAILED(rc)) return rc;
1505
1506 i_setModified(IsModified_MachineData);
1507 mHWData.backup();
1508 mHWData->mCPUCount = aCPUCount;
1509
1510 return S_OK;
1511}
1512
1513HRESULT Machine::getCPUExecutionCap(ULONG *aCPUExecutionCap)
1514{
1515 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1516
1517 *aCPUExecutionCap = mHWData->mCpuExecutionCap;
1518
1519 return S_OK;
1520}
1521
1522HRESULT Machine::setCPUExecutionCap(ULONG aCPUExecutionCap)
1523{
1524 HRESULT rc = S_OK;
1525
1526 /* check throttle limits */
1527 if ( aCPUExecutionCap < 1
1528 || aCPUExecutionCap > 100
1529 )
1530 return setError(E_INVALIDARG,
1531 tr("Invalid CPU execution cap value: %lu (must be in range [%lu, %lu])"),
1532 aCPUExecutionCap, 1, 100);
1533
1534 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1535
1536 alock.release();
1537 rc = i_onCPUExecutionCapChange(aCPUExecutionCap);
1538 alock.acquire();
1539 if (FAILED(rc)) return rc;
1540
1541 i_setModified(IsModified_MachineData);
1542 mHWData.backup();
1543 mHWData->mCpuExecutionCap = aCPUExecutionCap;
1544
1545 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1546 if (Global::IsOnline(mData->mMachineState))
1547 i_saveSettings(NULL);
1548
1549 return S_OK;
1550}
1551
1552HRESULT Machine::getCPUHotPlugEnabled(BOOL *aCPUHotPlugEnabled)
1553{
1554 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1555
1556 *aCPUHotPlugEnabled = mHWData->mCPUHotPlugEnabled;
1557
1558 return S_OK;
1559}
1560
1561HRESULT Machine::setCPUHotPlugEnabled(BOOL aCPUHotPlugEnabled)
1562{
1563 HRESULT rc = S_OK;
1564
1565 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1566
1567 rc = i_checkStateDependency(MutableStateDep);
1568 if (FAILED(rc)) return rc;
1569
1570 if (mHWData->mCPUHotPlugEnabled != aCPUHotPlugEnabled)
1571 {
1572 if (aCPUHotPlugEnabled)
1573 {
1574 i_setModified(IsModified_MachineData);
1575 mHWData.backup();
1576
1577 /* Add the amount of CPUs currently attached */
1578 for (unsigned i = 0; i < mHWData->mCPUCount; ++i)
1579 mHWData->mCPUAttached[i] = true;
1580 }
1581 else
1582 {
1583 /*
1584 * We can disable hotplug only if the amount of maximum CPUs is equal
1585 * to the amount of attached CPUs
1586 */
1587 unsigned cCpusAttached = 0;
1588 unsigned iHighestId = 0;
1589
1590 for (unsigned i = 0; i < SchemaDefs::MaxCPUCount; ++i)
1591 {
1592 if (mHWData->mCPUAttached[i])
1593 {
1594 cCpusAttached++;
1595 iHighestId = i;
1596 }
1597 }
1598
1599 if ( (cCpusAttached != mHWData->mCPUCount)
1600 || (iHighestId >= mHWData->mCPUCount))
1601 return setError(E_INVALIDARG,
1602 tr("CPU hotplugging can't be disabled because the maximum number of CPUs is not equal to the amount of CPUs attached"));
1603
1604 i_setModified(IsModified_MachineData);
1605 mHWData.backup();
1606 }
1607 }
1608
1609 mHWData->mCPUHotPlugEnabled = aCPUHotPlugEnabled;
1610
1611 return rc;
1612}
1613
1614HRESULT Machine::getCPUIDPortabilityLevel(ULONG *aCPUIDPortabilityLevel)
1615{
1616 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1617
1618 *aCPUIDPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
1619
1620 return S_OK;
1621}
1622
1623HRESULT Machine::setCPUIDPortabilityLevel(ULONG aCPUIDPortabilityLevel)
1624{
1625 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1626
1627 HRESULT hrc = i_checkStateDependency(MutableStateDep);
1628 if (SUCCEEDED(hrc))
1629 {
1630 i_setModified(IsModified_MachineData);
1631 mHWData.backup();
1632 mHWData->mCpuIdPortabilityLevel = aCPUIDPortabilityLevel;
1633 }
1634 return hrc;
1635}
1636
1637HRESULT Machine::getCPUProfile(com::Utf8Str &aCPUProfile)
1638{
1639 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1640 aCPUProfile = mHWData->mCpuProfile;
1641 return S_OK;
1642}
1643
1644HRESULT Machine::setCPUProfile(const com::Utf8Str &aCPUProfile)
1645{
1646 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1647 HRESULT hrc = i_checkStateDependency(MutableStateDep);
1648 if (SUCCEEDED(hrc))
1649 {
1650 i_setModified(IsModified_MachineData);
1651 mHWData.backup();
1652 /* Empty equals 'host'. */
1653 if (aCPUProfile.isNotEmpty())
1654 mHWData->mCpuProfile = aCPUProfile;
1655 else
1656 mHWData->mCpuProfile = "host";
1657 }
1658 return hrc;
1659}
1660
1661HRESULT Machine::getEmulatedUSBCardReaderEnabled(BOOL *aEmulatedUSBCardReaderEnabled)
1662{
1663#ifdef VBOX_WITH_USB_CARDREADER
1664 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1665
1666 *aEmulatedUSBCardReaderEnabled = mHWData->mEmulatedUSBCardReaderEnabled;
1667
1668 return S_OK;
1669#else
1670 NOREF(aEmulatedUSBCardReaderEnabled);
1671 return E_NOTIMPL;
1672#endif
1673}
1674
1675HRESULT Machine::setEmulatedUSBCardReaderEnabled(BOOL aEmulatedUSBCardReaderEnabled)
1676{
1677#ifdef VBOX_WITH_USB_CARDREADER
1678 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1679
1680 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
1681 if (FAILED(rc)) return rc;
1682
1683 i_setModified(IsModified_MachineData);
1684 mHWData.backup();
1685 mHWData->mEmulatedUSBCardReaderEnabled = aEmulatedUSBCardReaderEnabled;
1686
1687 return S_OK;
1688#else
1689 NOREF(aEmulatedUSBCardReaderEnabled);
1690 return E_NOTIMPL;
1691#endif
1692}
1693
1694HRESULT Machine::getHPETEnabled(BOOL *aHPETEnabled)
1695{
1696 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1697
1698 *aHPETEnabled = mHWData->mHPETEnabled;
1699
1700 return S_OK;
1701}
1702
1703HRESULT Machine::setHPETEnabled(BOOL aHPETEnabled)
1704{
1705 HRESULT rc = S_OK;
1706
1707 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1708
1709 rc = i_checkStateDependency(MutableStateDep);
1710 if (FAILED(rc)) return rc;
1711
1712 i_setModified(IsModified_MachineData);
1713 mHWData.backup();
1714
1715 mHWData->mHPETEnabled = aHPETEnabled;
1716
1717 return rc;
1718}
1719
1720HRESULT Machine::getVideoCaptureEnabled(BOOL *aVideoCaptureEnabled)
1721{
1722 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1723
1724 *aVideoCaptureEnabled = mHWData->mVideoCaptureEnabled;
1725 return S_OK;
1726}
1727
1728HRESULT Machine::setVideoCaptureEnabled(BOOL aVideoCaptureEnabled)
1729{
1730 HRESULT rc = S_OK;
1731
1732 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1733
1734 i_setModified(IsModified_MachineData);
1735 mHWData.backup();
1736 mHWData->mVideoCaptureEnabled = aVideoCaptureEnabled;
1737
1738 alock.release();
1739 rc = i_onVideoCaptureChange();
1740 alock.acquire();
1741 if (FAILED(rc))
1742 {
1743 /*
1744 * Normally we would do the actual change _after_ i_onVideoCaptureChange() succeeded.
1745 * We cannot do this because that function uses Machine::GetVideoCaptureEnabled to
1746 * determine if it should start or stop capturing. Therefore we need to manually
1747 * undo change.
1748 */
1749 mHWData->mVideoCaptureEnabled = mHWData.backedUpData()->mVideoCaptureEnabled;
1750 return rc;
1751 }
1752
1753 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1754 if (Global::IsOnline(mData->mMachineState))
1755 i_saveSettings(NULL);
1756
1757 return rc;
1758}
1759
1760HRESULT Machine::getVideoCaptureScreens(std::vector<BOOL> &aVideoCaptureScreens)
1761{
1762 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1763 aVideoCaptureScreens.resize(mHWData->mMonitorCount);
1764 for (unsigned i = 0; i < mHWData->mMonitorCount; ++i)
1765 aVideoCaptureScreens[i] = mHWData->maVideoCaptureScreens[i];
1766 return S_OK;
1767}
1768
1769HRESULT Machine::setVideoCaptureScreens(const std::vector<BOOL> &aVideoCaptureScreens)
1770{
1771 AssertReturn(aVideoCaptureScreens.size() <= RT_ELEMENTS(mHWData->maVideoCaptureScreens), E_INVALIDARG);
1772 bool fChanged = false;
1773
1774 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1775
1776 for (unsigned i = 0; i < aVideoCaptureScreens.size(); ++i)
1777 {
1778 if (mHWData->maVideoCaptureScreens[i] != RT_BOOL(aVideoCaptureScreens[i]))
1779 {
1780 mHWData->maVideoCaptureScreens[i] = RT_BOOL(aVideoCaptureScreens[i]);
1781 fChanged = true;
1782 }
1783 }
1784 if (fChanged)
1785 {
1786 alock.release();
1787 HRESULT rc = i_onVideoCaptureChange();
1788 alock.acquire();
1789 if (FAILED(rc)) return rc;
1790 i_setModified(IsModified_MachineData);
1791
1792 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1793 if (Global::IsOnline(mData->mMachineState))
1794 i_saveSettings(NULL);
1795 }
1796
1797 return S_OK;
1798}
1799
1800HRESULT Machine::getVideoCaptureFile(com::Utf8Str &aVideoCaptureFile)
1801{
1802 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1803 if (mHWData->mVideoCaptureFile.isEmpty())
1804 i_getDefaultVideoCaptureFile(aVideoCaptureFile);
1805 else
1806 aVideoCaptureFile = mHWData->mVideoCaptureFile;
1807 return S_OK;
1808}
1809
1810HRESULT Machine::setVideoCaptureFile(const com::Utf8Str &aVideoCaptureFile)
1811{
1812 Utf8Str strFile(aVideoCaptureFile);
1813 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1814
1815 if ( Global::IsOnline(mData->mMachineState)
1816 && mHWData->mVideoCaptureEnabled)
1817 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1818
1819 if (!RTPathStartsWithRoot(strFile.c_str()))
1820 return setError(E_INVALIDARG, tr("Video capture file name '%s' is not absolute"), strFile.c_str());
1821
1822 if (!strFile.isEmpty())
1823 {
1824 Utf8Str defaultFile;
1825 i_getDefaultVideoCaptureFile(defaultFile);
1826 if (!RTPathCompare(strFile.c_str(), defaultFile.c_str()))
1827 strFile.setNull();
1828 }
1829
1830 i_setModified(IsModified_MachineData);
1831 mHWData.backup();
1832 mHWData->mVideoCaptureFile = strFile;
1833
1834 return S_OK;
1835}
1836
1837HRESULT Machine::getVideoCaptureWidth(ULONG *aVideoCaptureWidth)
1838{
1839 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1840 *aVideoCaptureWidth = mHWData->mVideoCaptureWidth;
1841 return S_OK;
1842}
1843
1844HRESULT Machine::setVideoCaptureWidth(ULONG aVideoCaptureWidth)
1845{
1846 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1847
1848 if ( Global::IsOnline(mData->mMachineState)
1849 && mHWData->mVideoCaptureEnabled)
1850 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1851
1852 i_setModified(IsModified_MachineData);
1853 mHWData.backup();
1854 mHWData->mVideoCaptureWidth = aVideoCaptureWidth;
1855
1856 return S_OK;
1857}
1858
1859HRESULT Machine::getVideoCaptureHeight(ULONG *aVideoCaptureHeight)
1860{
1861 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1862 *aVideoCaptureHeight = mHWData->mVideoCaptureHeight;
1863 return S_OK;
1864}
1865
1866HRESULT Machine::setVideoCaptureHeight(ULONG aVideoCaptureHeight)
1867{
1868 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1869
1870 if ( Global::IsOnline(mData->mMachineState)
1871 && mHWData->mVideoCaptureEnabled)
1872 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1873
1874 i_setModified(IsModified_MachineData);
1875 mHWData.backup();
1876 mHWData->mVideoCaptureHeight = aVideoCaptureHeight;
1877
1878 return S_OK;
1879}
1880
1881HRESULT Machine::getVideoCaptureRate(ULONG *aVideoCaptureRate)
1882{
1883 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1884 *aVideoCaptureRate = mHWData->mVideoCaptureRate;
1885 return S_OK;
1886}
1887
1888HRESULT Machine::setVideoCaptureRate(ULONG aVideoCaptureRate)
1889{
1890 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1891
1892 if ( Global::IsOnline(mData->mMachineState)
1893 && mHWData->mVideoCaptureEnabled)
1894 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1895
1896 i_setModified(IsModified_MachineData);
1897 mHWData.backup();
1898 mHWData->mVideoCaptureRate = aVideoCaptureRate;
1899
1900 return S_OK;
1901}
1902
1903HRESULT Machine::getVideoCaptureFPS(ULONG *aVideoCaptureFPS)
1904{
1905 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1906 *aVideoCaptureFPS = mHWData->mVideoCaptureFPS;
1907 return S_OK;
1908}
1909
1910HRESULT Machine::setVideoCaptureFPS(ULONG aVideoCaptureFPS)
1911{
1912 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1913
1914 if ( Global::IsOnline(mData->mMachineState)
1915 && mHWData->mVideoCaptureEnabled)
1916 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1917
1918 i_setModified(IsModified_MachineData);
1919 mHWData.backup();
1920 mHWData->mVideoCaptureFPS = aVideoCaptureFPS;
1921
1922 return S_OK;
1923}
1924
1925HRESULT Machine::getVideoCaptureMaxTime(ULONG *aVideoCaptureMaxTime)
1926{
1927 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1928 *aVideoCaptureMaxTime = mHWData->mVideoCaptureMaxTime;
1929 return S_OK;
1930}
1931
1932HRESULT Machine::setVideoCaptureMaxTime(ULONG aVideoCaptureMaxTime)
1933{
1934 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1935
1936 if ( Global::IsOnline(mData->mMachineState)
1937 && mHWData->mVideoCaptureEnabled)
1938 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1939
1940 i_setModified(IsModified_MachineData);
1941 mHWData.backup();
1942 mHWData->mVideoCaptureMaxTime = aVideoCaptureMaxTime;
1943
1944 return S_OK;
1945}
1946
1947HRESULT Machine::getVideoCaptureMaxFileSize(ULONG *aVideoCaptureMaxFileSize)
1948{
1949 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1950 *aVideoCaptureMaxFileSize = mHWData->mVideoCaptureMaxFileSize;
1951 return S_OK;
1952}
1953
1954HRESULT Machine::setVideoCaptureMaxFileSize(ULONG aVideoCaptureMaxFileSize)
1955{
1956 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1957
1958 if ( Global::IsOnline(mData->mMachineState)
1959 && mHWData->mVideoCaptureEnabled)
1960 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1961
1962 i_setModified(IsModified_MachineData);
1963 mHWData.backup();
1964 mHWData->mVideoCaptureMaxFileSize = aVideoCaptureMaxFileSize;
1965
1966 return S_OK;
1967}
1968
1969HRESULT Machine::getVideoCaptureOptions(com::Utf8Str &aVideoCaptureOptions)
1970{
1971 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1972
1973 aVideoCaptureOptions = mHWData->mVideoCaptureOptions;
1974 return S_OK;
1975}
1976
1977HRESULT Machine::setVideoCaptureOptions(const com::Utf8Str &aVideoCaptureOptions)
1978{
1979 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1980
1981 if ( Global::IsOnline(mData->mMachineState)
1982 && mHWData->mVideoCaptureEnabled)
1983 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1984
1985 i_setModified(IsModified_MachineData);
1986 mHWData.backup();
1987 mHWData->mVideoCaptureOptions = aVideoCaptureOptions;
1988
1989 return S_OK;
1990}
1991
1992HRESULT Machine::getGraphicsControllerType(GraphicsControllerType_T *aGraphicsControllerType)
1993{
1994 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1995
1996 *aGraphicsControllerType = mHWData->mGraphicsControllerType;
1997
1998 return S_OK;
1999}
2000
2001HRESULT Machine::setGraphicsControllerType(GraphicsControllerType_T aGraphicsControllerType)
2002{
2003 switch (aGraphicsControllerType)
2004 {
2005 case GraphicsControllerType_Null:
2006 case GraphicsControllerType_VBoxVGA:
2007#ifdef VBOX_WITH_VMSVGA
2008 case GraphicsControllerType_VMSVGA:
2009#endif
2010 break;
2011 default:
2012 return setError(E_INVALIDARG, tr("The graphics controller type (%d) is invalid"), aGraphicsControllerType);
2013 }
2014
2015 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2016
2017 HRESULT rc = i_checkStateDependency(MutableStateDep);
2018 if (FAILED(rc)) return rc;
2019
2020 i_setModified(IsModified_MachineData);
2021 mHWData.backup();
2022 mHWData->mGraphicsControllerType = aGraphicsControllerType;
2023
2024 return S_OK;
2025}
2026
2027HRESULT Machine::getVRAMSize(ULONG *aVRAMSize)
2028{
2029 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2030
2031 *aVRAMSize = mHWData->mVRAMSize;
2032
2033 return S_OK;
2034}
2035
2036HRESULT Machine::setVRAMSize(ULONG aVRAMSize)
2037{
2038 /* check VRAM limits */
2039 if (aVRAMSize > SchemaDefs::MaxGuestVRAM)
2040 return setError(E_INVALIDARG,
2041 tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
2042 aVRAMSize, SchemaDefs::MinGuestVRAM, SchemaDefs::MaxGuestVRAM);
2043
2044 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2045
2046 HRESULT rc = i_checkStateDependency(MutableStateDep);
2047 if (FAILED(rc)) return rc;
2048
2049 i_setModified(IsModified_MachineData);
2050 mHWData.backup();
2051 mHWData->mVRAMSize = aVRAMSize;
2052
2053 return S_OK;
2054}
2055
2056/** @todo this method should not be public */
2057HRESULT Machine::getMemoryBalloonSize(ULONG *aMemoryBalloonSize)
2058{
2059 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2060
2061 *aMemoryBalloonSize = mHWData->mMemoryBalloonSize;
2062
2063 return S_OK;
2064}
2065
2066/**
2067 * Set the memory balloon size.
2068 *
2069 * This method is also called from IGuest::COMSETTER(MemoryBalloonSize) so
2070 * we have to make sure that we never call IGuest from here.
2071 */
2072HRESULT Machine::setMemoryBalloonSize(ULONG aMemoryBalloonSize)
2073{
2074 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
2075#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
2076 /* check limits */
2077 if (aMemoryBalloonSize >= VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize))
2078 return setError(E_INVALIDARG,
2079 tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
2080 aMemoryBalloonSize, 0, VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize));
2081
2082 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2083
2084 i_setModified(IsModified_MachineData);
2085 mHWData.backup();
2086 mHWData->mMemoryBalloonSize = aMemoryBalloonSize;
2087
2088 return S_OK;
2089#else
2090 NOREF(aMemoryBalloonSize);
2091 return setError(E_NOTIMPL, tr("Memory ballooning is only supported on 64-bit hosts"));
2092#endif
2093}
2094
2095HRESULT Machine::getPageFusionEnabled(BOOL *aPageFusionEnabled)
2096{
2097 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2098
2099 *aPageFusionEnabled = mHWData->mPageFusionEnabled;
2100 return S_OK;
2101}
2102
2103HRESULT Machine::setPageFusionEnabled(BOOL aPageFusionEnabled)
2104{
2105#ifdef VBOX_WITH_PAGE_SHARING
2106 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2107
2108 /** @todo must support changes for running vms and keep this in sync with IGuest. */
2109 i_setModified(IsModified_MachineData);
2110 mHWData.backup();
2111 mHWData->mPageFusionEnabled = aPageFusionEnabled;
2112 return S_OK;
2113#else
2114 NOREF(aPageFusionEnabled);
2115 return setError(E_NOTIMPL, tr("Page fusion is only supported on 64-bit hosts"));
2116#endif
2117}
2118
2119HRESULT Machine::getAccelerate3DEnabled(BOOL *aAccelerate3DEnabled)
2120{
2121 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2122
2123 *aAccelerate3DEnabled = mHWData->mAccelerate3DEnabled;
2124
2125 return S_OK;
2126}
2127
2128HRESULT Machine::setAccelerate3DEnabled(BOOL aAccelerate3DEnabled)
2129{
2130 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2131
2132 HRESULT rc = i_checkStateDependency(MutableStateDep);
2133 if (FAILED(rc)) return rc;
2134
2135 /** @todo check validity! */
2136
2137 i_setModified(IsModified_MachineData);
2138 mHWData.backup();
2139 mHWData->mAccelerate3DEnabled = aAccelerate3DEnabled;
2140
2141 return S_OK;
2142}
2143
2144
2145HRESULT Machine::getAccelerate2DVideoEnabled(BOOL *aAccelerate2DVideoEnabled)
2146{
2147 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2148
2149 *aAccelerate2DVideoEnabled = mHWData->mAccelerate2DVideoEnabled;
2150
2151 return S_OK;
2152}
2153
2154HRESULT Machine::setAccelerate2DVideoEnabled(BOOL aAccelerate2DVideoEnabled)
2155{
2156 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2157
2158 HRESULT rc = i_checkStateDependency(MutableStateDep);
2159 if (FAILED(rc)) return rc;
2160
2161 /** @todo check validity! */
2162 i_setModified(IsModified_MachineData);
2163 mHWData.backup();
2164 mHWData->mAccelerate2DVideoEnabled = aAccelerate2DVideoEnabled;
2165
2166 return S_OK;
2167}
2168
2169HRESULT Machine::getMonitorCount(ULONG *aMonitorCount)
2170{
2171 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2172
2173 *aMonitorCount = mHWData->mMonitorCount;
2174
2175 return S_OK;
2176}
2177
2178HRESULT Machine::setMonitorCount(ULONG aMonitorCount)
2179{
2180 /* make sure monitor count is a sensible number */
2181 if (aMonitorCount < 1 || aMonitorCount > SchemaDefs::MaxGuestMonitors)
2182 return setError(E_INVALIDARG,
2183 tr("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
2184 aMonitorCount, 1, SchemaDefs::MaxGuestMonitors);
2185
2186 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2187
2188 HRESULT rc = i_checkStateDependency(MutableStateDep);
2189 if (FAILED(rc)) return rc;
2190
2191 i_setModified(IsModified_MachineData);
2192 mHWData.backup();
2193 mHWData->mMonitorCount = aMonitorCount;
2194
2195 return S_OK;
2196}
2197
2198HRESULT Machine::getBIOSSettings(ComPtr<IBIOSSettings> &aBIOSSettings)
2199{
2200 /* mBIOSSettings is constant during life time, no need to lock */
2201 aBIOSSettings = mBIOSSettings;
2202
2203 return S_OK;
2204}
2205
2206HRESULT Machine::getCPUProperty(CPUPropertyType_T aProperty, BOOL *aValue)
2207{
2208 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2209
2210 switch (aProperty)
2211 {
2212 case CPUPropertyType_PAE:
2213 *aValue = mHWData->mPAEEnabled;
2214 break;
2215
2216 case CPUPropertyType_LongMode:
2217 if (mHWData->mLongMode == settings::Hardware::LongMode_Enabled)
2218 *aValue = TRUE;
2219 else if (mHWData->mLongMode == settings::Hardware::LongMode_Disabled)
2220 *aValue = FALSE;
2221#if HC_ARCH_BITS == 64
2222 else
2223 *aValue = TRUE;
2224#else
2225 else
2226 {
2227 *aValue = FALSE;
2228
2229 ComObjPtr<GuestOSType> pGuestOSType;
2230 HRESULT hrc2 = mParent->i_findGuestOSType(mUserData->s.strOsType,
2231 pGuestOSType);
2232 if (SUCCEEDED(hrc2))
2233 {
2234 if (pGuestOSType->i_is64Bit())
2235 {
2236 ComObjPtr<Host> pHost = mParent->i_host();
2237 alock.release();
2238
2239 hrc2 = pHost->GetProcessorFeature(ProcessorFeature_LongMode, aValue); AssertComRC(hrc2);
2240 if (FAILED(hrc2))
2241 *aValue = FALSE;
2242 }
2243 }
2244 }
2245#endif
2246 break;
2247
2248 case CPUPropertyType_TripleFaultReset:
2249 *aValue = mHWData->mTripleFaultReset;
2250 break;
2251
2252 case CPUPropertyType_APIC:
2253 *aValue = mHWData->mAPIC;
2254 break;
2255
2256 case CPUPropertyType_X2APIC:
2257 *aValue = mHWData->mX2APIC;
2258 break;
2259
2260 default:
2261 return E_INVALIDARG;
2262 }
2263 return S_OK;
2264}
2265
2266HRESULT Machine::setCPUProperty(CPUPropertyType_T aProperty, BOOL aValue)
2267{
2268 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2269
2270 HRESULT rc = i_checkStateDependency(MutableStateDep);
2271 if (FAILED(rc)) return rc;
2272
2273 switch (aProperty)
2274 {
2275 case CPUPropertyType_PAE:
2276 i_setModified(IsModified_MachineData);
2277 mHWData.backup();
2278 mHWData->mPAEEnabled = !!aValue;
2279 break;
2280
2281 case CPUPropertyType_LongMode:
2282 i_setModified(IsModified_MachineData);
2283 mHWData.backup();
2284 mHWData->mLongMode = !aValue ? settings::Hardware::LongMode_Disabled : settings::Hardware::LongMode_Enabled;
2285 break;
2286
2287 case CPUPropertyType_TripleFaultReset:
2288 i_setModified(IsModified_MachineData);
2289 mHWData.backup();
2290 mHWData->mTripleFaultReset = !!aValue;
2291 break;
2292
2293 case CPUPropertyType_APIC:
2294 if (mHWData->mX2APIC)
2295 aValue = TRUE;
2296 i_setModified(IsModified_MachineData);
2297 mHWData.backup();
2298 mHWData->mAPIC = !!aValue;
2299 break;
2300
2301 case CPUPropertyType_X2APIC:
2302 i_setModified(IsModified_MachineData);
2303 mHWData.backup();
2304 mHWData->mX2APIC = !!aValue;
2305 if (aValue)
2306 mHWData->mAPIC = !!aValue;
2307 break;
2308
2309 default:
2310 return E_INVALIDARG;
2311 }
2312 return S_OK;
2313}
2314
2315HRESULT Machine::getCPUIDLeaf(ULONG aId, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx)
2316{
2317 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2318
2319 switch(aId)
2320 {
2321 case 0x0:
2322 case 0x1:
2323 case 0x2:
2324 case 0x3:
2325 case 0x4:
2326 case 0x5:
2327 case 0x6:
2328 case 0x7:
2329 case 0x8:
2330 case 0x9:
2331 case 0xA:
2332 if (mHWData->mCpuIdStdLeafs[aId].ulId != aId)
2333 return E_INVALIDARG;
2334
2335 *aValEax = mHWData->mCpuIdStdLeafs[aId].ulEax;
2336 *aValEbx = mHWData->mCpuIdStdLeafs[aId].ulEbx;
2337 *aValEcx = mHWData->mCpuIdStdLeafs[aId].ulEcx;
2338 *aValEdx = mHWData->mCpuIdStdLeafs[aId].ulEdx;
2339 break;
2340
2341 case 0x80000000:
2342 case 0x80000001:
2343 case 0x80000002:
2344 case 0x80000003:
2345 case 0x80000004:
2346 case 0x80000005:
2347 case 0x80000006:
2348 case 0x80000007:
2349 case 0x80000008:
2350 case 0x80000009:
2351 case 0x8000000A:
2352 if (mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId != aId)
2353 return E_INVALIDARG;
2354
2355 *aValEax = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax;
2356 *aValEbx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx;
2357 *aValEcx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx;
2358 *aValEdx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx;
2359 break;
2360
2361 default:
2362 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2363 }
2364 return S_OK;
2365}
2366
2367
2368HRESULT Machine::setCPUIDLeaf(ULONG aId, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx)
2369{
2370 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2371
2372 HRESULT rc = i_checkStateDependency(MutableStateDep);
2373 if (FAILED(rc)) return rc;
2374
2375 switch(aId)
2376 {
2377 case 0x0:
2378 case 0x1:
2379 case 0x2:
2380 case 0x3:
2381 case 0x4:
2382 case 0x5:
2383 case 0x6:
2384 case 0x7:
2385 case 0x8:
2386 case 0x9:
2387 case 0xA:
2388 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2389 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2390 i_setModified(IsModified_MachineData);
2391 mHWData.backup();
2392 mHWData->mCpuIdStdLeafs[aId].ulId = aId;
2393 mHWData->mCpuIdStdLeafs[aId].ulEax = aValEax;
2394 mHWData->mCpuIdStdLeafs[aId].ulEbx = aValEbx;
2395 mHWData->mCpuIdStdLeafs[aId].ulEcx = aValEcx;
2396 mHWData->mCpuIdStdLeafs[aId].ulEdx = aValEdx;
2397 break;
2398
2399 case 0x80000000:
2400 case 0x80000001:
2401 case 0x80000002:
2402 case 0x80000003:
2403 case 0x80000004:
2404 case 0x80000005:
2405 case 0x80000006:
2406 case 0x80000007:
2407 case 0x80000008:
2408 case 0x80000009:
2409 case 0x8000000A:
2410 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2411 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2412 i_setModified(IsModified_MachineData);
2413 mHWData.backup();
2414 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = aId;
2415 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax = aValEax;
2416 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx = aValEbx;
2417 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx = aValEcx;
2418 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx = aValEdx;
2419 break;
2420
2421 default:
2422 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2423 }
2424 return S_OK;
2425}
2426
2427HRESULT Machine::removeCPUIDLeaf(ULONG aId)
2428{
2429 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2430
2431 HRESULT rc = i_checkStateDependency(MutableStateDep);
2432 if (FAILED(rc)) return rc;
2433
2434 switch(aId)
2435 {
2436 case 0x0:
2437 case 0x1:
2438 case 0x2:
2439 case 0x3:
2440 case 0x4:
2441 case 0x5:
2442 case 0x6:
2443 case 0x7:
2444 case 0x8:
2445 case 0x9:
2446 case 0xA:
2447 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2448 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2449 i_setModified(IsModified_MachineData);
2450 mHWData.backup();
2451 /* Invalidate leaf. */
2452 mHWData->mCpuIdStdLeafs[aId].ulId = UINT32_MAX;
2453 break;
2454
2455 case 0x80000000:
2456 case 0x80000001:
2457 case 0x80000002:
2458 case 0x80000003:
2459 case 0x80000004:
2460 case 0x80000005:
2461 case 0x80000006:
2462 case 0x80000007:
2463 case 0x80000008:
2464 case 0x80000009:
2465 case 0x8000000A:
2466 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2467 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2468 i_setModified(IsModified_MachineData);
2469 mHWData.backup();
2470 /* Invalidate leaf. */
2471 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = UINT32_MAX;
2472 break;
2473
2474 default:
2475 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2476 }
2477 return S_OK;
2478}
2479
2480HRESULT Machine::removeAllCPUIDLeaves()
2481{
2482 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2483
2484 HRESULT rc = i_checkStateDependency(MutableStateDep);
2485 if (FAILED(rc)) return rc;
2486
2487 i_setModified(IsModified_MachineData);
2488 mHWData.backup();
2489
2490 /* Invalidate all standard leafs. */
2491 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++i)
2492 mHWData->mCpuIdStdLeafs[i].ulId = UINT32_MAX;
2493
2494 /* Invalidate all extended leafs. */
2495 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++i)
2496 mHWData->mCpuIdExtLeafs[i].ulId = UINT32_MAX;
2497
2498 return S_OK;
2499}
2500HRESULT Machine::getHWVirtExProperty(HWVirtExPropertyType_T aProperty, BOOL *aValue)
2501{
2502 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2503
2504 switch(aProperty)
2505 {
2506 case HWVirtExPropertyType_Enabled:
2507 *aValue = mHWData->mHWVirtExEnabled;
2508 break;
2509
2510 case HWVirtExPropertyType_VPID:
2511 *aValue = mHWData->mHWVirtExVPIDEnabled;
2512 break;
2513
2514 case HWVirtExPropertyType_NestedPaging:
2515 *aValue = mHWData->mHWVirtExNestedPagingEnabled;
2516 break;
2517
2518 case HWVirtExPropertyType_UnrestrictedExecution:
2519 *aValue = mHWData->mHWVirtExUXEnabled;
2520 break;
2521
2522 case HWVirtExPropertyType_LargePages:
2523 *aValue = mHWData->mHWVirtExLargePagesEnabled;
2524#if defined(DEBUG_bird) && defined(RT_OS_LINUX) /* This feature is deadly here */
2525 *aValue = FALSE;
2526#endif
2527 break;
2528
2529 case HWVirtExPropertyType_Force:
2530 *aValue = mHWData->mHWVirtExForceEnabled;
2531 break;
2532
2533 default:
2534 return E_INVALIDARG;
2535 }
2536 return S_OK;
2537}
2538
2539HRESULT Machine::setHWVirtExProperty(HWVirtExPropertyType_T aProperty, BOOL aValue)
2540{
2541 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2542
2543 HRESULT rc = i_checkStateDependency(MutableStateDep);
2544 if (FAILED(rc)) return rc;
2545
2546 switch(aProperty)
2547 {
2548 case HWVirtExPropertyType_Enabled:
2549 i_setModified(IsModified_MachineData);
2550 mHWData.backup();
2551 mHWData->mHWVirtExEnabled = !!aValue;
2552 break;
2553
2554 case HWVirtExPropertyType_VPID:
2555 i_setModified(IsModified_MachineData);
2556 mHWData.backup();
2557 mHWData->mHWVirtExVPIDEnabled = !!aValue;
2558 break;
2559
2560 case HWVirtExPropertyType_NestedPaging:
2561 i_setModified(IsModified_MachineData);
2562 mHWData.backup();
2563 mHWData->mHWVirtExNestedPagingEnabled = !!aValue;
2564 break;
2565
2566 case HWVirtExPropertyType_UnrestrictedExecution:
2567 i_setModified(IsModified_MachineData);
2568 mHWData.backup();
2569 mHWData->mHWVirtExUXEnabled = !!aValue;
2570 break;
2571
2572 case HWVirtExPropertyType_LargePages:
2573 i_setModified(IsModified_MachineData);
2574 mHWData.backup();
2575 mHWData->mHWVirtExLargePagesEnabled = !!aValue;
2576 break;
2577
2578 case HWVirtExPropertyType_Force:
2579 i_setModified(IsModified_MachineData);
2580 mHWData.backup();
2581 mHWData->mHWVirtExForceEnabled = !!aValue;
2582 break;
2583
2584 default:
2585 return E_INVALIDARG;
2586 }
2587
2588 return S_OK;
2589}
2590
2591HRESULT Machine::getSnapshotFolder(com::Utf8Str &aSnapshotFolder)
2592{
2593 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2594
2595 i_calculateFullPath(mUserData->s.strSnapshotFolder, aSnapshotFolder);
2596
2597 return S_OK;
2598}
2599
2600HRESULT Machine::setSnapshotFolder(const com::Utf8Str &aSnapshotFolder)
2601{
2602 /** @todo (r=dmik):
2603 * 1. Allow to change the name of the snapshot folder containing snapshots
2604 * 2. Rename the folder on disk instead of just changing the property
2605 * value (to be smart and not to leave garbage). Note that it cannot be
2606 * done here because the change may be rolled back. Thus, the right
2607 * place is #saveSettings().
2608 */
2609
2610 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2611
2612 HRESULT rc = i_checkStateDependency(MutableStateDep);
2613 if (FAILED(rc)) return rc;
2614
2615 if (!mData->mCurrentSnapshot.isNull())
2616 return setError(E_FAIL,
2617 tr("The snapshot folder of a machine with snapshots cannot be changed (please delete all snapshots first)"));
2618
2619 Utf8Str strSnapshotFolder(aSnapshotFolder); // keep original
2620
2621 if (strSnapshotFolder.isEmpty())
2622 strSnapshotFolder = "Snapshots";
2623 int vrc = i_calculateFullPath(strSnapshotFolder,
2624 strSnapshotFolder);
2625 if (RT_FAILURE(vrc))
2626 return setError(E_FAIL,
2627 tr("Invalid snapshot folder '%s' (%Rrc)"),
2628 strSnapshotFolder.c_str(), vrc);
2629
2630 i_setModified(IsModified_MachineData);
2631 mUserData.backup();
2632
2633 i_copyPathRelativeToMachine(strSnapshotFolder, mUserData->s.strSnapshotFolder);
2634
2635 return S_OK;
2636}
2637
2638HRESULT Machine::getMediumAttachments(std::vector<ComPtr<IMediumAttachment> > &aMediumAttachments)
2639{
2640 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2641
2642 aMediumAttachments.resize(mMediumAttachments->size());
2643 size_t i = 0;
2644 for (MediumAttachmentList::const_iterator
2645 it = mMediumAttachments->begin();
2646 it != mMediumAttachments->end();
2647 ++it, ++i)
2648 aMediumAttachments[i] = *it;
2649
2650 return S_OK;
2651}
2652
2653HRESULT Machine::getVRDEServer(ComPtr<IVRDEServer> &aVRDEServer)
2654{
2655 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2656
2657 Assert(!!mVRDEServer);
2658
2659 aVRDEServer = mVRDEServer;
2660
2661 return S_OK;
2662}
2663
2664HRESULT Machine::getAudioAdapter(ComPtr<IAudioAdapter> &aAudioAdapter)
2665{
2666 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2667
2668 aAudioAdapter = mAudioAdapter;
2669
2670 return S_OK;
2671}
2672
2673HRESULT Machine::getUSBControllers(std::vector<ComPtr<IUSBController> > &aUSBControllers)
2674{
2675#ifdef VBOX_WITH_VUSB
2676 clearError();
2677 MultiResult rc(S_OK);
2678
2679# ifdef VBOX_WITH_USB
2680 rc = mParent->i_host()->i_checkUSBProxyService();
2681 if (FAILED(rc)) return rc;
2682# endif
2683
2684 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2685
2686 aUSBControllers.resize(mUSBControllers->size());
2687 size_t i = 0;
2688 for (USBControllerList::const_iterator
2689 it = mUSBControllers->begin();
2690 it != mUSBControllers->end();
2691 ++it, ++i)
2692 aUSBControllers[i] = *it;
2693
2694 return S_OK;
2695#else
2696 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2697 * extended error info to indicate that USB is simply not available
2698 * (w/o treating it as a failure), for example, as in OSE */
2699 NOREF(aUSBControllers);
2700 ReturnComNotImplemented();
2701#endif /* VBOX_WITH_VUSB */
2702}
2703
2704HRESULT Machine::getUSBDeviceFilters(ComPtr<IUSBDeviceFilters> &aUSBDeviceFilters)
2705{
2706#ifdef VBOX_WITH_VUSB
2707 clearError();
2708 MultiResult rc(S_OK);
2709
2710# ifdef VBOX_WITH_USB
2711 rc = mParent->i_host()->i_checkUSBProxyService();
2712 if (FAILED(rc)) return rc;
2713# endif
2714
2715 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2716
2717 aUSBDeviceFilters = mUSBDeviceFilters;
2718 return rc;
2719#else
2720 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2721 * extended error info to indicate that USB is simply not available
2722 * (w/o treating it as a failure), for example, as in OSE */
2723 NOREF(aUSBDeviceFilters);
2724 ReturnComNotImplemented();
2725#endif /* VBOX_WITH_VUSB */
2726}
2727
2728HRESULT Machine::getSettingsFilePath(com::Utf8Str &aSettingsFilePath)
2729{
2730 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2731
2732 aSettingsFilePath = mData->m_strConfigFileFull;
2733
2734 return S_OK;
2735}
2736
2737HRESULT Machine::getSettingsAuxFilePath(com::Utf8Str &aSettingsFilePath)
2738{
2739 RT_NOREF(aSettingsFilePath);
2740 ReturnComNotImplemented();
2741}
2742
2743HRESULT Machine::getSettingsModified(BOOL *aSettingsModified)
2744{
2745 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2746
2747 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2748 if (FAILED(rc)) return rc;
2749
2750 if (!mData->pMachineConfigFile->fileExists())
2751 // this is a new machine, and no config file exists yet:
2752 *aSettingsModified = TRUE;
2753 else
2754 *aSettingsModified = (mData->flModifications != 0);
2755
2756 return S_OK;
2757}
2758
2759HRESULT Machine::getSessionState(SessionState_T *aSessionState)
2760{
2761 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2762
2763 *aSessionState = mData->mSession.mState;
2764
2765 return S_OK;
2766}
2767
2768HRESULT Machine::getSessionName(com::Utf8Str &aSessionName)
2769{
2770 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2771
2772 aSessionName = mData->mSession.mName;
2773
2774 return S_OK;
2775}
2776
2777HRESULT Machine::getSessionPID(ULONG *aSessionPID)
2778{
2779 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2780
2781 *aSessionPID = mData->mSession.mPID;
2782
2783 return S_OK;
2784}
2785
2786HRESULT Machine::getState(MachineState_T *aState)
2787{
2788 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2789
2790 *aState = mData->mMachineState;
2791 Assert(mData->mMachineState != MachineState_Null);
2792
2793 return S_OK;
2794}
2795
2796HRESULT Machine::getLastStateChange(LONG64 *aLastStateChange)
2797{
2798 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2799
2800 *aLastStateChange = RTTimeSpecGetMilli(&mData->mLastStateChange);
2801
2802 return S_OK;
2803}
2804
2805HRESULT Machine::getStateFilePath(com::Utf8Str &aStateFilePath)
2806{
2807 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2808
2809 aStateFilePath = mSSData->strStateFilePath;
2810
2811 return S_OK;
2812}
2813
2814HRESULT Machine::getLogFolder(com::Utf8Str &aLogFolder)
2815{
2816 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2817
2818 i_getLogFolder(aLogFolder);
2819
2820 return S_OK;
2821}
2822
2823HRESULT Machine::getCurrentSnapshot(ComPtr<ISnapshot> &aCurrentSnapshot)
2824{
2825 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2826
2827 aCurrentSnapshot = mData->mCurrentSnapshot;
2828
2829 return S_OK;
2830}
2831
2832HRESULT Machine::getSnapshotCount(ULONG *aSnapshotCount)
2833{
2834 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2835
2836 *aSnapshotCount = mData->mFirstSnapshot.isNull()
2837 ? 0
2838 : mData->mFirstSnapshot->i_getAllChildrenCount() + 1;
2839
2840 return S_OK;
2841}
2842
2843HRESULT Machine::getCurrentStateModified(BOOL *aCurrentStateModified)
2844{
2845 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2846
2847 /* Note: for machines with no snapshots, we always return FALSE
2848 * (mData->mCurrentStateModified will be TRUE in this case, for historical
2849 * reasons :) */
2850
2851 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
2852 ? FALSE
2853 : mData->mCurrentStateModified;
2854
2855 return S_OK;
2856}
2857
2858HRESULT Machine::getSharedFolders(std::vector<ComPtr<ISharedFolder> > &aSharedFolders)
2859{
2860 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2861
2862 aSharedFolders.resize(mHWData->mSharedFolders.size());
2863 size_t i = 0;
2864 for (std::list<ComObjPtr<SharedFolder> >::const_iterator
2865 it = mHWData->mSharedFolders.begin();
2866 it != mHWData->mSharedFolders.end();
2867 ++it, ++i)
2868 aSharedFolders[i] = *it;
2869
2870 return S_OK;
2871}
2872
2873HRESULT Machine::getClipboardMode(ClipboardMode_T *aClipboardMode)
2874{
2875 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2876
2877 *aClipboardMode = mHWData->mClipboardMode;
2878
2879 return S_OK;
2880}
2881
2882HRESULT Machine::setClipboardMode(ClipboardMode_T aClipboardMode)
2883{
2884 HRESULT rc = S_OK;
2885
2886 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2887
2888 alock.release();
2889 rc = i_onClipboardModeChange(aClipboardMode);
2890 alock.acquire();
2891 if (FAILED(rc)) return rc;
2892
2893 i_setModified(IsModified_MachineData);
2894 mHWData.backup();
2895 mHWData->mClipboardMode = aClipboardMode;
2896
2897 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
2898 if (Global::IsOnline(mData->mMachineState))
2899 i_saveSettings(NULL);
2900
2901 return S_OK;
2902}
2903
2904HRESULT Machine::getDnDMode(DnDMode_T *aDnDMode)
2905{
2906 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2907
2908 *aDnDMode = mHWData->mDnDMode;
2909
2910 return S_OK;
2911}
2912
2913HRESULT Machine::setDnDMode(DnDMode_T aDnDMode)
2914{
2915 HRESULT rc = S_OK;
2916
2917 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2918
2919 alock.release();
2920 rc = i_onDnDModeChange(aDnDMode);
2921
2922 alock.acquire();
2923 if (FAILED(rc)) return rc;
2924
2925 i_setModified(IsModified_MachineData);
2926 mHWData.backup();
2927 mHWData->mDnDMode = aDnDMode;
2928
2929 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
2930 if (Global::IsOnline(mData->mMachineState))
2931 i_saveSettings(NULL);
2932
2933 return S_OK;
2934}
2935
2936HRESULT Machine::getStorageControllers(std::vector<ComPtr<IStorageController> > &aStorageControllers)
2937{
2938 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2939
2940 aStorageControllers.resize(mStorageControllers->size());
2941 size_t i = 0;
2942 for (StorageControllerList::const_iterator
2943 it = mStorageControllers->begin();
2944 it != mStorageControllers->end();
2945 ++it, ++i)
2946 aStorageControllers[i] = *it;
2947
2948 return S_OK;
2949}
2950
2951HRESULT Machine::getTeleporterEnabled(BOOL *aEnabled)
2952{
2953 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2954
2955 *aEnabled = mUserData->s.fTeleporterEnabled;
2956
2957 return S_OK;
2958}
2959
2960HRESULT Machine::setTeleporterEnabled(BOOL aTeleporterEnabled)
2961{
2962 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2963
2964 /* Only allow it to be set to true when PoweredOff or Aborted.
2965 (Clearing it is always permitted.) */
2966 if ( aTeleporterEnabled
2967 && mData->mRegistered
2968 && ( !i_isSessionMachine()
2969 || ( mData->mMachineState != MachineState_PoweredOff
2970 && mData->mMachineState != MachineState_Teleported
2971 && mData->mMachineState != MachineState_Aborted
2972 )
2973 )
2974 )
2975 return setError(VBOX_E_INVALID_VM_STATE,
2976 tr("The machine is not powered off (state is %s)"),
2977 Global::stringifyMachineState(mData->mMachineState));
2978
2979 i_setModified(IsModified_MachineData);
2980 mUserData.backup();
2981 mUserData->s.fTeleporterEnabled = !! aTeleporterEnabled;
2982
2983 return S_OK;
2984}
2985
2986HRESULT Machine::getTeleporterPort(ULONG *aTeleporterPort)
2987{
2988 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2989
2990 *aTeleporterPort = (ULONG)mUserData->s.uTeleporterPort;
2991
2992 return S_OK;
2993}
2994
2995HRESULT Machine::setTeleporterPort(ULONG aTeleporterPort)
2996{
2997 if (aTeleporterPort >= _64K)
2998 return setError(E_INVALIDARG, tr("Invalid port number %d"), aTeleporterPort);
2999
3000 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3001
3002 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3003 if (FAILED(rc)) return rc;
3004
3005 i_setModified(IsModified_MachineData);
3006 mUserData.backup();
3007 mUserData->s.uTeleporterPort = (uint32_t)aTeleporterPort;
3008
3009 return S_OK;
3010}
3011
3012HRESULT Machine::getTeleporterAddress(com::Utf8Str &aTeleporterAddress)
3013{
3014 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3015
3016 aTeleporterAddress = mUserData->s.strTeleporterAddress;
3017
3018 return S_OK;
3019}
3020
3021HRESULT Machine::setTeleporterAddress(const com::Utf8Str &aTeleporterAddress)
3022{
3023 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3024
3025 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3026 if (FAILED(rc)) return rc;
3027
3028 i_setModified(IsModified_MachineData);
3029 mUserData.backup();
3030 mUserData->s.strTeleporterAddress = aTeleporterAddress;
3031
3032 return S_OK;
3033}
3034
3035HRESULT Machine::getTeleporterPassword(com::Utf8Str &aTeleporterPassword)
3036{
3037 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3038 aTeleporterPassword = mUserData->s.strTeleporterPassword;
3039
3040 return S_OK;
3041}
3042
3043HRESULT Machine::setTeleporterPassword(const com::Utf8Str &aTeleporterPassword)
3044{
3045 /*
3046 * Hash the password first.
3047 */
3048 com::Utf8Str aT = aTeleporterPassword;
3049
3050 if (!aT.isEmpty())
3051 {
3052 if (VBoxIsPasswordHashed(&aT))
3053 return setError(E_INVALIDARG, tr("Cannot set an already hashed password, only plain text password please"));
3054 VBoxHashPassword(&aT);
3055 }
3056
3057 /*
3058 * Do the update.
3059 */
3060 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3061 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
3062 if (SUCCEEDED(hrc))
3063 {
3064 i_setModified(IsModified_MachineData);
3065 mUserData.backup();
3066 mUserData->s.strTeleporterPassword = aT;
3067 }
3068
3069 return hrc;
3070}
3071
3072HRESULT Machine::getFaultToleranceState(FaultToleranceState_T *aFaultToleranceState)
3073{
3074 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3075
3076 *aFaultToleranceState = mUserData->s.enmFaultToleranceState;
3077 return S_OK;
3078}
3079
3080HRESULT Machine::setFaultToleranceState(FaultToleranceState_T aFaultToleranceState)
3081{
3082 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3083
3084 /** @todo deal with running state change. */
3085 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
3086 if (FAILED(rc)) return rc;
3087
3088 i_setModified(IsModified_MachineData);
3089 mUserData.backup();
3090 mUserData->s.enmFaultToleranceState = aFaultToleranceState;
3091 return S_OK;
3092}
3093
3094HRESULT Machine::getFaultToleranceAddress(com::Utf8Str &aFaultToleranceAddress)
3095{
3096 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3097
3098 aFaultToleranceAddress = mUserData->s.strFaultToleranceAddress;
3099 return S_OK;
3100}
3101
3102HRESULT Machine::setFaultToleranceAddress(const com::Utf8Str &aFaultToleranceAddress)
3103{
3104 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3105
3106 /** @todo deal with running state change. */
3107 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3108 if (FAILED(rc)) return rc;
3109
3110 i_setModified(IsModified_MachineData);
3111 mUserData.backup();
3112 mUserData->s.strFaultToleranceAddress = aFaultToleranceAddress;
3113 return S_OK;
3114}
3115
3116HRESULT Machine::getFaultTolerancePort(ULONG *aFaultTolerancePort)
3117{
3118 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3119
3120 *aFaultTolerancePort = mUserData->s.uFaultTolerancePort;
3121 return S_OK;
3122}
3123
3124HRESULT Machine::setFaultTolerancePort(ULONG aFaultTolerancePort)
3125{
3126 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3127
3128 /** @todo deal with running state change. */
3129 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3130 if (FAILED(rc)) return rc;
3131
3132 i_setModified(IsModified_MachineData);
3133 mUserData.backup();
3134 mUserData->s.uFaultTolerancePort = aFaultTolerancePort;
3135 return S_OK;
3136}
3137
3138HRESULT Machine::getFaultTolerancePassword(com::Utf8Str &aFaultTolerancePassword)
3139{
3140 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3141
3142 aFaultTolerancePassword = mUserData->s.strFaultTolerancePassword;
3143
3144 return S_OK;
3145}
3146
3147HRESULT Machine::setFaultTolerancePassword(const com::Utf8Str &aFaultTolerancePassword)
3148{
3149 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3150
3151 /** @todo deal with running state change. */
3152 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3153 if (FAILED(rc)) return rc;
3154
3155 i_setModified(IsModified_MachineData);
3156 mUserData.backup();
3157 mUserData->s.strFaultTolerancePassword = aFaultTolerancePassword;
3158
3159 return S_OK;
3160}
3161
3162HRESULT Machine::getFaultToleranceSyncInterval(ULONG *aFaultToleranceSyncInterval)
3163{
3164 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3165
3166 *aFaultToleranceSyncInterval = mUserData->s.uFaultToleranceInterval;
3167 return S_OK;
3168}
3169
3170HRESULT Machine::setFaultToleranceSyncInterval(ULONG aFaultToleranceSyncInterval)
3171{
3172 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3173
3174 /** @todo deal with running state change. */
3175 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3176 if (FAILED(rc)) return rc;
3177
3178 i_setModified(IsModified_MachineData);
3179 mUserData.backup();
3180 mUserData->s.uFaultToleranceInterval = aFaultToleranceSyncInterval;
3181 return S_OK;
3182}
3183
3184HRESULT Machine::getRTCUseUTC(BOOL *aRTCUseUTC)
3185{
3186 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3187
3188 *aRTCUseUTC = mUserData->s.fRTCUseUTC;
3189
3190 return S_OK;
3191}
3192
3193HRESULT Machine::setRTCUseUTC(BOOL aRTCUseUTC)
3194{
3195 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3196
3197 /* Only allow it to be set to true when PoweredOff or Aborted.
3198 (Clearing it is always permitted.) */
3199 if ( aRTCUseUTC
3200 && mData->mRegistered
3201 && ( !i_isSessionMachine()
3202 || ( mData->mMachineState != MachineState_PoweredOff
3203 && mData->mMachineState != MachineState_Teleported
3204 && mData->mMachineState != MachineState_Aborted
3205 )
3206 )
3207 )
3208 return setError(VBOX_E_INVALID_VM_STATE,
3209 tr("The machine is not powered off (state is %s)"),
3210 Global::stringifyMachineState(mData->mMachineState));
3211
3212 i_setModified(IsModified_MachineData);
3213 mUserData.backup();
3214 mUserData->s.fRTCUseUTC = !!aRTCUseUTC;
3215
3216 return S_OK;
3217}
3218
3219HRESULT Machine::getIOCacheEnabled(BOOL *aIOCacheEnabled)
3220{
3221 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3222
3223 *aIOCacheEnabled = mHWData->mIOCacheEnabled;
3224
3225 return S_OK;
3226}
3227
3228HRESULT Machine::setIOCacheEnabled(BOOL aIOCacheEnabled)
3229{
3230 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3231
3232 HRESULT rc = i_checkStateDependency(MutableStateDep);
3233 if (FAILED(rc)) return rc;
3234
3235 i_setModified(IsModified_MachineData);
3236 mHWData.backup();
3237 mHWData->mIOCacheEnabled = aIOCacheEnabled;
3238
3239 return S_OK;
3240}
3241
3242HRESULT Machine::getIOCacheSize(ULONG *aIOCacheSize)
3243{
3244 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3245
3246 *aIOCacheSize = mHWData->mIOCacheSize;
3247
3248 return S_OK;
3249}
3250
3251HRESULT Machine::setIOCacheSize(ULONG aIOCacheSize)
3252{
3253 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3254
3255 HRESULT rc = i_checkStateDependency(MutableStateDep);
3256 if (FAILED(rc)) return rc;
3257
3258 i_setModified(IsModified_MachineData);
3259 mHWData.backup();
3260 mHWData->mIOCacheSize = aIOCacheSize;
3261
3262 return S_OK;
3263}
3264
3265
3266/**
3267 * @note Locks objects!
3268 */
3269HRESULT Machine::lockMachine(const ComPtr<ISession> &aSession,
3270 LockType_T aLockType)
3271{
3272 /* check the session state */
3273 SessionState_T state;
3274 HRESULT rc = aSession->COMGETTER(State)(&state);
3275 if (FAILED(rc)) return rc;
3276
3277 if (state != SessionState_Unlocked)
3278 return setError(VBOX_E_INVALID_OBJECT_STATE,
3279 tr("The given session is busy"));
3280
3281 // get the client's IInternalSessionControl interface
3282 ComPtr<IInternalSessionControl> pSessionControl = aSession;
3283 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
3284 E_INVALIDARG);
3285
3286 // session name (only used in some code paths)
3287 Utf8Str strSessionName;
3288
3289 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3290
3291 if (!mData->mRegistered)
3292 return setError(E_UNEXPECTED,
3293 tr("The machine '%s' is not registered"),
3294 mUserData->s.strName.c_str());
3295
3296 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3297
3298 SessionState_T oldState = mData->mSession.mState;
3299 /* Hack: in case the session is closing and there is a progress object
3300 * which allows waiting for the session to be closed, take the opportunity
3301 * and do a limited wait (max. 1 second). This helps a lot when the system
3302 * is busy and thus session closing can take a little while. */
3303 if ( mData->mSession.mState == SessionState_Unlocking
3304 && mData->mSession.mProgress)
3305 {
3306 alock.release();
3307 mData->mSession.mProgress->WaitForCompletion(1000);
3308 alock.acquire();
3309 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3310 }
3311
3312 // try again now
3313 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already
3314 // (i.e. session machine exists)
3315 && (aLockType == LockType_Shared) // caller wants a shared link to the
3316 // existing session that holds the write lock:
3317 )
3318 {
3319 // OK, share the session... we are now dealing with three processes:
3320 // 1) VBoxSVC (where this code runs);
3321 // 2) process C: the caller's client process (who wants a shared session);
3322 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
3323
3324 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
3325 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
3326 ComAssertRet(!pSessionW.isNull(), E_FAIL);
3327 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
3328 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
3329
3330 /*
3331 * Release the lock before calling the client process. It's safe here
3332 * since the only thing to do after we get the lock again is to add
3333 * the remote control to the list (which doesn't directly influence
3334 * anything).
3335 */
3336 alock.release();
3337
3338 // get the console of the session holding the write lock (this is a remote call)
3339 ComPtr<IConsole> pConsoleW;
3340 if (mData->mSession.mLockType == LockType_VM)
3341 {
3342 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
3343 rc = pSessionW->COMGETTER(RemoteConsole)(pConsoleW.asOutParam());
3344 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
3345 if (FAILED(rc))
3346 // the failure may occur w/o any error info (from RPC), so provide one
3347 return setError(VBOX_E_VM_ERROR,
3348 tr("Failed to get a console object from the direct session (%Rhrc)"), rc);
3349 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
3350 }
3351
3352 // share the session machine and W's console with the caller's session
3353 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3354 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
3355 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3356
3357 if (FAILED(rc))
3358 // the failure may occur w/o any error info (from RPC), so provide one
3359 return setError(VBOX_E_VM_ERROR,
3360 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
3361 alock.acquire();
3362
3363 // need to revalidate the state after acquiring the lock again
3364 if (mData->mSession.mState != SessionState_Locked)
3365 {
3366 pSessionControl->Uninitialize();
3367 return setError(VBOX_E_INVALID_SESSION_STATE,
3368 tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
3369 mUserData->s.strName.c_str());
3370 }
3371
3372 // add the caller's session to the list
3373 mData->mSession.mRemoteControls.push_back(pSessionControl);
3374 }
3375 else if ( mData->mSession.mState == SessionState_Locked
3376 || mData->mSession.mState == SessionState_Unlocking
3377 )
3378 {
3379 // sharing not permitted, or machine still unlocking:
3380 return setError(VBOX_E_INVALID_OBJECT_STATE,
3381 tr("The machine '%s' is already locked for a session (or being unlocked)"),
3382 mUserData->s.strName.c_str());
3383 }
3384 else
3385 {
3386 // machine is not locked: then write-lock the machine (create the session machine)
3387
3388 // must not be busy
3389 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
3390
3391 // get the caller's session PID
3392 RTPROCESS pid = NIL_RTPROCESS;
3393 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
3394 pSessionControl->COMGETTER(PID)((ULONG*)&pid);
3395 Assert(pid != NIL_RTPROCESS);
3396
3397 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
3398
3399 if (fLaunchingVMProcess)
3400 {
3401 if (mData->mSession.mPID == NIL_RTPROCESS)
3402 {
3403 // two or more clients racing for a lock, the one which set the
3404 // session state to Spawning will win, the others will get an
3405 // error as we can't decide here if waiting a little would help
3406 // (only for shared locks this would avoid an error)
3407 return setError(VBOX_E_INVALID_OBJECT_STATE,
3408 tr("The machine '%s' already has a lock request pending"),
3409 mUserData->s.strName.c_str());
3410 }
3411
3412 // this machine is awaiting for a spawning session to be opened:
3413 // then the calling process must be the one that got started by
3414 // LaunchVMProcess()
3415
3416 LogFlowThisFunc(("mSession.mPID=%d(0x%x)\n", mData->mSession.mPID, mData->mSession.mPID));
3417 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3418
3419#if defined(VBOX_WITH_HARDENING) && defined(RT_OS_WINDOWS)
3420 /* Hardened windows builds spawns three processes when a VM is
3421 launched, the 3rd one is the one that will end up here. */
3422 RTPROCESS ppid;
3423 int rc = RTProcQueryParent(pid, &ppid);
3424 if (RT_SUCCESS(rc))
3425 rc = RTProcQueryParent(ppid, &ppid);
3426 if ( (RT_SUCCESS(rc) && mData->mSession.mPID == ppid)
3427 || rc == VERR_ACCESS_DENIED)
3428 {
3429 LogFlowThisFunc(("mSession.mPID => %d(%#x) - windows hardening stub\n", mData->mSession.mPID, pid));
3430 mData->mSession.mPID = pid;
3431 }
3432#endif
3433
3434 if (mData->mSession.mPID != pid)
3435 return setError(E_ACCESSDENIED,
3436 tr("An unexpected process (PID=0x%08X) has tried to lock the "
3437 "machine '%s', while only the process started by LaunchVMProcess (PID=0x%08X) is allowed"),
3438 pid, mUserData->s.strName.c_str(), mData->mSession.mPID);
3439 }
3440
3441 // create the mutable SessionMachine from the current machine
3442 ComObjPtr<SessionMachine> sessionMachine;
3443 sessionMachine.createObject();
3444 rc = sessionMachine->init(this);
3445 AssertComRC(rc);
3446
3447 /* NOTE: doing return from this function after this point but
3448 * before the end is forbidden since it may call SessionMachine::uninit()
3449 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3450 * lock while still holding the Machine lock in alock so that a deadlock
3451 * is possible due to the wrong lock order. */
3452
3453 if (SUCCEEDED(rc))
3454 {
3455 /*
3456 * Set the session state to Spawning to protect against subsequent
3457 * attempts to open a session and to unregister the machine after
3458 * we release the lock.
3459 */
3460 SessionState_T origState = mData->mSession.mState;
3461 mData->mSession.mState = SessionState_Spawning;
3462
3463#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
3464 /* Get the client token ID to be passed to the client process */
3465 Utf8Str strTokenId;
3466 sessionMachine->i_getTokenId(strTokenId);
3467 Assert(!strTokenId.isEmpty());
3468#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3469 /* Get the client token to be passed to the client process */
3470 ComPtr<IToken> pToken(sessionMachine->i_getToken());
3471 /* The token is now "owned" by pToken, fix refcount */
3472 if (!pToken.isNull())
3473 pToken->Release();
3474#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3475
3476 /*
3477 * Release the lock before calling the client process -- it will call
3478 * Machine/SessionMachine methods. Releasing the lock here is quite safe
3479 * because the state is Spawning, so that LaunchVMProcess() and
3480 * LockMachine() calls will fail. This method, called before we
3481 * acquire the lock again, will fail because of the wrong PID.
3482 *
3483 * Note that mData->mSession.mRemoteControls accessed outside
3484 * the lock may not be modified when state is Spawning, so it's safe.
3485 */
3486 alock.release();
3487
3488 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3489#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
3490 rc = pSessionControl->AssignMachine(sessionMachine, aLockType, Bstr(strTokenId).raw());
3491#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3492 rc = pSessionControl->AssignMachine(sessionMachine, aLockType, pToken);
3493 /* Now the token is owned by the client process. */
3494 pToken.setNull();
3495#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3496 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3497
3498 /* The failure may occur w/o any error info (from RPC), so provide one */
3499 if (FAILED(rc))
3500 setError(VBOX_E_VM_ERROR,
3501 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
3502
3503 // get session name, either to remember or to compare against
3504 // the already known session name.
3505 {
3506 Bstr bstrSessionName;
3507 HRESULT rc2 = aSession->COMGETTER(Name)(bstrSessionName.asOutParam());
3508 if (SUCCEEDED(rc2))
3509 strSessionName = bstrSessionName;
3510 }
3511
3512 if ( SUCCEEDED(rc)
3513 && fLaunchingVMProcess
3514 )
3515 {
3516 /* complete the remote session initialization */
3517
3518 /* get the console from the direct session */
3519 ComPtr<IConsole> console;
3520 rc = pSessionControl->COMGETTER(RemoteConsole)(console.asOutParam());
3521 ComAssertComRC(rc);
3522
3523 if (SUCCEEDED(rc) && !console)
3524 {
3525 ComAssert(!!console);
3526 rc = E_FAIL;
3527 }
3528
3529 /* assign machine & console to the remote session */
3530 if (SUCCEEDED(rc))
3531 {
3532 /*
3533 * after LaunchVMProcess(), the first and the only
3534 * entry in remoteControls is that remote session
3535 */
3536 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3537 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
3538 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3539
3540 /* The failure may occur w/o any error info (from RPC), so provide one */
3541 if (FAILED(rc))
3542 setError(VBOX_E_VM_ERROR,
3543 tr("Failed to assign the machine to the remote session (%Rhrc)"), rc);
3544 }
3545
3546 if (FAILED(rc))
3547 pSessionControl->Uninitialize();
3548 }
3549
3550 /* acquire the lock again */
3551 alock.acquire();
3552
3553 /* Restore the session state */
3554 mData->mSession.mState = origState;
3555 }
3556
3557 // finalize spawning anyway (this is why we don't return on errors above)
3558 if (fLaunchingVMProcess)
3559 {
3560 Assert(mData->mSession.mName == strSessionName);
3561 /* Note that the progress object is finalized later */
3562 /** @todo Consider checking mData->mSession.mProgress for cancellation
3563 * around here. */
3564
3565 /* We don't reset mSession.mPID here because it is necessary for
3566 * SessionMachine::uninit() to reap the child process later. */
3567
3568 if (FAILED(rc))
3569 {
3570 /* Close the remote session, remove the remote control from the list
3571 * and reset session state to Closed (@note keep the code in sync
3572 * with the relevant part in checkForSpawnFailure()). */
3573
3574 Assert(mData->mSession.mRemoteControls.size() == 1);
3575 if (mData->mSession.mRemoteControls.size() == 1)
3576 {
3577 ErrorInfoKeeper eik;
3578 mData->mSession.mRemoteControls.front()->Uninitialize();
3579 }
3580
3581 mData->mSession.mRemoteControls.clear();
3582 mData->mSession.mState = SessionState_Unlocked;
3583 }
3584 }
3585 else
3586 {
3587 /* memorize PID of the directly opened session */
3588 if (SUCCEEDED(rc))
3589 mData->mSession.mPID = pid;
3590 }
3591
3592 if (SUCCEEDED(rc))
3593 {
3594 mData->mSession.mLockType = aLockType;
3595 /* memorize the direct session control and cache IUnknown for it */
3596 mData->mSession.mDirectControl = pSessionControl;
3597 mData->mSession.mState = SessionState_Locked;
3598 if (!fLaunchingVMProcess)
3599 mData->mSession.mName = strSessionName;
3600 /* associate the SessionMachine with this Machine */
3601 mData->mSession.mMachine = sessionMachine;
3602
3603 /* request an IUnknown pointer early from the remote party for later
3604 * identity checks (it will be internally cached within mDirectControl
3605 * at least on XPCOM) */
3606 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3607 NOREF(unk);
3608 }
3609
3610 /* Release the lock since SessionMachine::uninit() locks VirtualBox which
3611 * would break the lock order */
3612 alock.release();
3613
3614 /* uninitialize the created session machine on failure */
3615 if (FAILED(rc))
3616 sessionMachine->uninit();
3617 }
3618
3619 if (SUCCEEDED(rc))
3620 {
3621 /*
3622 * tell the client watcher thread to update the set of
3623 * machines that have open sessions
3624 */
3625 mParent->i_updateClientWatcher();
3626
3627 if (oldState != SessionState_Locked)
3628 /* fire an event */
3629 mParent->i_onSessionStateChange(i_getId(), SessionState_Locked);
3630 }
3631
3632 return rc;
3633}
3634
3635/**
3636 * @note Locks objects!
3637 */
3638HRESULT Machine::launchVMProcess(const ComPtr<ISession> &aSession,
3639 const com::Utf8Str &aName,
3640 const com::Utf8Str &aEnvironment,
3641 ComPtr<IProgress> &aProgress)
3642{
3643 Utf8Str strFrontend(aName);
3644 /* "emergencystop" doesn't need the session, so skip the checks/interface
3645 * retrieval. This code doesn't quite fit in here, but introducing a
3646 * special API method would be even more effort, and would require explicit
3647 * support by every API client. It's better to hide the feature a bit. */
3648 if (strFrontend != "emergencystop")
3649 CheckComArgNotNull(aSession);
3650
3651 HRESULT rc = S_OK;
3652 if (strFrontend.isEmpty())
3653 {
3654 Bstr bstrFrontend;
3655 rc = COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3656 if (FAILED(rc))
3657 return rc;
3658 strFrontend = bstrFrontend;
3659 if (strFrontend.isEmpty())
3660 {
3661 ComPtr<ISystemProperties> systemProperties;
3662 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
3663 if (FAILED(rc))
3664 return rc;
3665 rc = systemProperties->COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3666 if (FAILED(rc))
3667 return rc;
3668 strFrontend = bstrFrontend;
3669 }
3670 /* paranoia - emergencystop is not a valid default */
3671 if (strFrontend == "emergencystop")
3672 strFrontend = Utf8Str::Empty;
3673 }
3674 /* default frontend: Qt GUI */
3675 if (strFrontend.isEmpty())
3676 strFrontend = "GUI/Qt";
3677
3678 if (strFrontend != "emergencystop")
3679 {
3680 /* check the session state */
3681 SessionState_T state;
3682 rc = aSession->COMGETTER(State)(&state);
3683 if (FAILED(rc))
3684 return rc;
3685
3686 if (state != SessionState_Unlocked)
3687 return setError(VBOX_E_INVALID_OBJECT_STATE,
3688 tr("The given session is busy"));
3689
3690 /* get the IInternalSessionControl interface */
3691 ComPtr<IInternalSessionControl> control(aSession);
3692 ComAssertMsgRet(!control.isNull(),
3693 ("No IInternalSessionControl interface"),
3694 E_INVALIDARG);
3695
3696 /* get the teleporter enable state for the progress object init. */
3697 BOOL fTeleporterEnabled;
3698 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3699 if (FAILED(rc))
3700 return rc;
3701
3702 /* create a progress object */
3703 ComObjPtr<ProgressProxy> progress;
3704 progress.createObject();
3705 rc = progress->init(mParent,
3706 static_cast<IMachine*>(this),
3707 Bstr(tr("Starting VM")).raw(),
3708 TRUE /* aCancelable */,
3709 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3710 BstrFmt(tr("Creating process for virtual machine \"%s\" (%s)"),
3711 mUserData->s.strName.c_str(), strFrontend.c_str()).raw(),
3712 2 /* uFirstOperationWeight */,
3713 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3714
3715 if (SUCCEEDED(rc))
3716 {
3717 rc = i_launchVMProcess(control, strFrontend, aEnvironment, progress);
3718 if (SUCCEEDED(rc))
3719 {
3720 aProgress = progress;
3721
3722 /* signal the client watcher thread */
3723 mParent->i_updateClientWatcher();
3724
3725 /* fire an event */
3726 mParent->i_onSessionStateChange(i_getId(), SessionState_Spawning);
3727 }
3728 }
3729 }
3730 else
3731 {
3732 /* no progress object - either instant success or failure */
3733 aProgress = NULL;
3734
3735 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3736
3737 if (mData->mSession.mState != SessionState_Locked)
3738 return setError(VBOX_E_INVALID_OBJECT_STATE,
3739 tr("The machine '%s' is not locked by a session"),
3740 mUserData->s.strName.c_str());
3741
3742 /* must have a VM process associated - do not kill normal API clients
3743 * with an open session */
3744 if (!Global::IsOnline(mData->mMachineState))
3745 return setError(VBOX_E_INVALID_OBJECT_STATE,
3746 tr("The machine '%s' does not have a VM process"),
3747 mUserData->s.strName.c_str());
3748
3749 /* forcibly terminate the VM process */
3750 if (mData->mSession.mPID != NIL_RTPROCESS)
3751 RTProcTerminate(mData->mSession.mPID);
3752
3753 /* signal the client watcher thread, as most likely the client has
3754 * been terminated */
3755 mParent->i_updateClientWatcher();
3756 }
3757
3758 return rc;
3759}
3760
3761HRESULT Machine::setBootOrder(ULONG aPosition, DeviceType_T aDevice)
3762{
3763 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3764 return setError(E_INVALIDARG,
3765 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3766 aPosition, SchemaDefs::MaxBootPosition);
3767
3768 if (aDevice == DeviceType_USB)
3769 return setError(E_NOTIMPL,
3770 tr("Booting from USB device is currently not supported"));
3771
3772 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3773
3774 HRESULT rc = i_checkStateDependency(MutableStateDep);
3775 if (FAILED(rc)) return rc;
3776
3777 i_setModified(IsModified_MachineData);
3778 mHWData.backup();
3779 mHWData->mBootOrder[aPosition - 1] = aDevice;
3780
3781 return S_OK;
3782}
3783
3784HRESULT Machine::getBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3785{
3786 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3787 return setError(E_INVALIDARG,
3788 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3789 aPosition, SchemaDefs::MaxBootPosition);
3790
3791 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3792
3793 *aDevice = mHWData->mBootOrder[aPosition - 1];
3794
3795 return S_OK;
3796}
3797
3798HRESULT Machine::attachDevice(const com::Utf8Str &aName,
3799 LONG aControllerPort,
3800 LONG aDevice,
3801 DeviceType_T aType,
3802 const ComPtr<IMedium> &aMedium)
3803{
3804 IMedium *aM = aMedium;
3805 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
3806 aName.c_str(), aControllerPort, aDevice, aType, aM));
3807
3808 // request the host lock first, since might be calling Host methods for getting host drives;
3809 // next, protect the media tree all the while we're in here, as well as our member variables
3810 AutoMultiWriteLock2 alock(mParent->i_host(), this COMMA_LOCKVAL_SRC_POS);
3811 AutoWriteLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3812
3813 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
3814 if (FAILED(rc)) return rc;
3815
3816 /// @todo NEWMEDIA implicit machine registration
3817 if (!mData->mRegistered)
3818 return setError(VBOX_E_INVALID_OBJECT_STATE,
3819 tr("Cannot attach storage devices to an unregistered machine"));
3820
3821 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3822
3823 /* Check for an existing controller. */
3824 ComObjPtr<StorageController> ctl;
3825 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
3826 if (FAILED(rc)) return rc;
3827
3828 StorageControllerType_T ctrlType;
3829 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
3830 if (FAILED(rc))
3831 return setError(E_FAIL,
3832 tr("Could not get type of controller '%s'"),
3833 aName.c_str());
3834
3835 bool fSilent = false;
3836 Utf8Str strReconfig;
3837
3838 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
3839 strReconfig = i_getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
3840 if ( mData->mMachineState == MachineState_Paused
3841 && strReconfig == "1")
3842 fSilent = true;
3843
3844 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
3845 bool fHotplug = false;
3846 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
3847 fHotplug = true;
3848
3849 if (fHotplug && !i_isControllerHotplugCapable(ctrlType))
3850 return setError(VBOX_E_INVALID_VM_STATE,
3851 tr("Controller '%s' does not support hotplugging"),
3852 aName.c_str());
3853
3854 // check that the port and device are not out of range
3855 rc = ctl->i_checkPortAndDeviceValid(aControllerPort, aDevice);
3856 if (FAILED(rc)) return rc;
3857
3858 /* check if the device slot is already busy */
3859 MediumAttachment *pAttachTemp;
3860 if ((pAttachTemp = i_findAttachment(*mMediumAttachments.data(),
3861 aName,
3862 aControllerPort,
3863 aDevice)))
3864 {
3865 Medium *pMedium = pAttachTemp->i_getMedium();
3866 if (pMedium)
3867 {
3868 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3869 return setError(VBOX_E_OBJECT_IN_USE,
3870 tr("Medium '%s' is already attached to port %d, device %d of controller '%s' of this virtual machine"),
3871 pMedium->i_getLocationFull().c_str(),
3872 aControllerPort,
3873 aDevice,
3874 aName.c_str());
3875 }
3876 else
3877 return setError(VBOX_E_OBJECT_IN_USE,
3878 tr("Device is already attached to port %d, device %d of controller '%s' of this virtual machine"),
3879 aControllerPort, aDevice, aName.c_str());
3880 }
3881
3882 ComObjPtr<Medium> medium = static_cast<Medium*>(aM);
3883 if (aMedium && medium.isNull())
3884 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3885
3886 AutoCaller mediumCaller(medium);
3887 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3888
3889 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3890
3891 if ( (pAttachTemp = i_findAttachment(*mMediumAttachments.data(), medium))
3892 && !medium.isNull()
3893 )
3894 return setError(VBOX_E_OBJECT_IN_USE,
3895 tr("Medium '%s' is already attached to this virtual machine"),
3896 medium->i_getLocationFull().c_str());
3897
3898 if (!medium.isNull())
3899 {
3900 MediumType_T mtype = medium->i_getType();
3901 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3902 // For DVDs it's not written to the config file, so needs no global config
3903 // version bump. For floppies it's a new attribute "type", which is ignored
3904 // by older VirtualBox version, so needs no global config version bump either.
3905 // For hard disks this type is not accepted.
3906 if (mtype == MediumType_MultiAttach)
3907 {
3908 // This type is new with VirtualBox 4.0 and therefore requires settings
3909 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3910 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3911 // two reasons: The medium type is a property of the media registry tree, which
3912 // can reside in the global config file (for pre-4.0 media); we would therefore
3913 // possibly need to bump the global config version. We don't want to do that though
3914 // because that might make downgrading to pre-4.0 impossible.
3915 // As a result, we can only use these two new types if the medium is NOT in the
3916 // global registry:
3917 const Guid &uuidGlobalRegistry = mParent->i_getGlobalRegistryId();
3918 if ( medium->i_isInRegistry(uuidGlobalRegistry)
3919 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3920 )
3921 return setError(VBOX_E_INVALID_OBJECT_STATE,
3922 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3923 "to machines that were created with VirtualBox 4.0 or later"),
3924 medium->i_getLocationFull().c_str());
3925 }
3926 }
3927
3928 bool fIndirect = false;
3929 if (!medium.isNull())
3930 fIndirect = medium->i_isReadOnly();
3931 bool associate = true;
3932
3933 do
3934 {
3935 if ( aType == DeviceType_HardDisk
3936 && mMediumAttachments.isBackedUp())
3937 {
3938 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
3939
3940 /* check if the medium was attached to the VM before we started
3941 * changing attachments in which case the attachment just needs to
3942 * be restored */
3943 if ((pAttachTemp = i_findAttachment(oldAtts, medium)))
3944 {
3945 AssertReturn(!fIndirect, E_FAIL);
3946
3947 /* see if it's the same bus/channel/device */
3948 if (pAttachTemp->i_matches(aName, aControllerPort, aDevice))
3949 {
3950 /* the simplest case: restore the whole attachment
3951 * and return, nothing else to do */
3952 mMediumAttachments->push_back(pAttachTemp);
3953
3954 /* Reattach the medium to the VM. */
3955 if (fHotplug || fSilent)
3956 {
3957 mediumLock.release();
3958 treeLock.release();
3959 alock.release();
3960
3961 MediumLockList *pMediumLockList(new MediumLockList());
3962
3963 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
3964 medium /* pToLockWrite */,
3965 false /* fMediumLockWriteAll */,
3966 NULL,
3967 *pMediumLockList);
3968 alock.acquire();
3969 if (FAILED(rc))
3970 delete pMediumLockList;
3971 else
3972 {
3973 mData->mSession.mLockedMedia.Unlock();
3974 alock.release();
3975 rc = mData->mSession.mLockedMedia.Insert(pAttachTemp, pMediumLockList);
3976 mData->mSession.mLockedMedia.Lock();
3977 alock.acquire();
3978 }
3979 alock.release();
3980
3981 if (SUCCEEDED(rc))
3982 {
3983 rc = i_onStorageDeviceChange(pAttachTemp, FALSE /* aRemove */, fSilent);
3984 /* Remove lock list in case of error. */
3985 if (FAILED(rc))
3986 {
3987 mData->mSession.mLockedMedia.Unlock();
3988 mData->mSession.mLockedMedia.Remove(pAttachTemp);
3989 mData->mSession.mLockedMedia.Lock();
3990 }
3991 }
3992 }
3993
3994 return S_OK;
3995 }
3996
3997 /* bus/channel/device differ; we need a new attachment object,
3998 * but don't try to associate it again */
3999 associate = false;
4000 break;
4001 }
4002 }
4003
4004 /* go further only if the attachment is to be indirect */
4005 if (!fIndirect)
4006 break;
4007
4008 /* perform the so called smart attachment logic for indirect
4009 * attachments. Note that smart attachment is only applicable to base
4010 * hard disks. */
4011
4012 if (medium->i_getParent().isNull())
4013 {
4014 /* first, investigate the backup copy of the current hard disk
4015 * attachments to make it possible to re-attach existing diffs to
4016 * another device slot w/o losing their contents */
4017 if (mMediumAttachments.isBackedUp())
4018 {
4019 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
4020
4021 MediumAttachmentList::const_iterator foundIt = oldAtts.end();
4022 uint32_t foundLevel = 0;
4023
4024 for (MediumAttachmentList::const_iterator
4025 it = oldAtts.begin();
4026 it != oldAtts.end();
4027 ++it)
4028 {
4029 uint32_t level = 0;
4030 MediumAttachment *pAttach = *it;
4031 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
4032 Assert(!pMedium.isNull() || pAttach->i_getType() != DeviceType_HardDisk);
4033 if (pMedium.isNull())
4034 continue;
4035
4036 if (pMedium->i_getBase(&level) == medium)
4037 {
4038 /* skip the hard disk if its currently attached (we
4039 * cannot attach the same hard disk twice) */
4040 if (i_findAttachment(*mMediumAttachments.data(),
4041 pMedium))
4042 continue;
4043
4044 /* matched device, channel and bus (i.e. attached to the
4045 * same place) will win and immediately stop the search;
4046 * otherwise the attachment that has the youngest
4047 * descendant of medium will be used
4048 */
4049 if (pAttach->i_matches(aName, aControllerPort, aDevice))
4050 {
4051 /* the simplest case: restore the whole attachment
4052 * and return, nothing else to do */
4053 mMediumAttachments->push_back(*it);
4054
4055 /* Reattach the medium to the VM. */
4056 if (fHotplug || fSilent)
4057 {
4058 mediumLock.release();
4059 treeLock.release();
4060 alock.release();
4061
4062 MediumLockList *pMediumLockList(new MediumLockList());
4063
4064 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
4065 medium /* pToLockWrite */,
4066 false /* fMediumLockWriteAll */,
4067 NULL,
4068 *pMediumLockList);
4069 alock.acquire();
4070 if (FAILED(rc))
4071 delete pMediumLockList;
4072 else
4073 {
4074 mData->mSession.mLockedMedia.Unlock();
4075 alock.release();
4076 rc = mData->mSession.mLockedMedia.Insert(pAttachTemp, pMediumLockList);
4077 mData->mSession.mLockedMedia.Lock();
4078 alock.acquire();
4079 }
4080 alock.release();
4081
4082 if (SUCCEEDED(rc))
4083 {
4084 rc = i_onStorageDeviceChange(pAttachTemp, FALSE /* aRemove */, fSilent);
4085 /* Remove lock list in case of error. */
4086 if (FAILED(rc))
4087 {
4088 mData->mSession.mLockedMedia.Unlock();
4089 mData->mSession.mLockedMedia.Remove(pAttachTemp);
4090 mData->mSession.mLockedMedia.Lock();
4091 }
4092 }
4093 }
4094
4095 return S_OK;
4096 }
4097 else if ( foundIt == oldAtts.end()
4098 || level > foundLevel /* prefer younger */
4099 )
4100 {
4101 foundIt = it;
4102 foundLevel = level;
4103 }
4104 }
4105 }
4106
4107 if (foundIt != oldAtts.end())
4108 {
4109 /* use the previously attached hard disk */
4110 medium = (*foundIt)->i_getMedium();
4111 mediumCaller.attach(medium);
4112 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4113 mediumLock.attach(medium);
4114 /* not implicit, doesn't require association with this VM */
4115 fIndirect = false;
4116 associate = false;
4117 /* go right to the MediumAttachment creation */
4118 break;
4119 }
4120 }
4121
4122 /* must give up the medium lock and medium tree lock as below we
4123 * go over snapshots, which needs a lock with higher lock order. */
4124 mediumLock.release();
4125 treeLock.release();
4126
4127 /* then, search through snapshots for the best diff in the given
4128 * hard disk's chain to base the new diff on */
4129
4130 ComObjPtr<Medium> base;
4131 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
4132 while (snap)
4133 {
4134 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
4135
4136 const MediumAttachmentList &snapAtts = *snap->i_getSnapshotMachine()->mMediumAttachments.data();
4137
4138 MediumAttachment *pAttachFound = NULL;
4139 uint32_t foundLevel = 0;
4140
4141 for (MediumAttachmentList::const_iterator
4142 it = snapAtts.begin();
4143 it != snapAtts.end();
4144 ++it)
4145 {
4146 MediumAttachment *pAttach = *it;
4147 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
4148 Assert(!pMedium.isNull() || pAttach->i_getType() != DeviceType_HardDisk);
4149 if (pMedium.isNull())
4150 continue;
4151
4152 uint32_t level = 0;
4153 if (pMedium->i_getBase(&level) == medium)
4154 {
4155 /* matched device, channel and bus (i.e. attached to the
4156 * same place) will win and immediately stop the search;
4157 * otherwise the attachment that has the youngest
4158 * descendant of medium will be used
4159 */
4160 if ( pAttach->i_getDevice() == aDevice
4161 && pAttach->i_getPort() == aControllerPort
4162 && pAttach->i_getControllerName() == aName
4163 )
4164 {
4165 pAttachFound = pAttach;
4166 break;
4167 }
4168 else if ( !pAttachFound
4169 || level > foundLevel /* prefer younger */
4170 )
4171 {
4172 pAttachFound = pAttach;
4173 foundLevel = level;
4174 }
4175 }
4176 }
4177
4178 if (pAttachFound)
4179 {
4180 base = pAttachFound->i_getMedium();
4181 break;
4182 }
4183
4184 snap = snap->i_getParent();
4185 }
4186
4187 /* re-lock medium tree and the medium, as we need it below */
4188 treeLock.acquire();
4189 mediumLock.acquire();
4190
4191 /* found a suitable diff, use it as a base */
4192 if (!base.isNull())
4193 {
4194 medium = base;
4195 mediumCaller.attach(medium);
4196 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4197 mediumLock.attach(medium);
4198 }
4199 }
4200
4201 Utf8Str strFullSnapshotFolder;
4202 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4203
4204 ComObjPtr<Medium> diff;
4205 diff.createObject();
4206 // store this diff in the same registry as the parent
4207 Guid uuidRegistryParent;
4208 if (!medium->i_getFirstRegistryMachineId(uuidRegistryParent))
4209 {
4210 // parent image has no registry: this can happen if we're attaching a new immutable
4211 // image that has not yet been attached (medium then points to the base and we're
4212 // creating the diff image for the immutable, and the parent is not yet registered);
4213 // put the parent in the machine registry then
4214 mediumLock.release();
4215 treeLock.release();
4216 alock.release();
4217 i_addMediumToRegistry(medium);
4218 alock.acquire();
4219 treeLock.acquire();
4220 mediumLock.acquire();
4221 medium->i_getFirstRegistryMachineId(uuidRegistryParent);
4222 }
4223 rc = diff->init(mParent,
4224 medium->i_getPreferredDiffFormat(),
4225 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
4226 uuidRegistryParent,
4227 DeviceType_HardDisk);
4228 if (FAILED(rc)) return rc;
4229
4230 /* Apply the normal locking logic to the entire chain. */
4231 MediumLockList *pMediumLockList(new MediumLockList());
4232 mediumLock.release();
4233 treeLock.release();
4234 rc = diff->i_createMediumLockList(true /* fFailIfInaccessible */,
4235 diff /* pToLockWrite */,
4236 false /* fMediumLockWriteAll */,
4237 medium,
4238 *pMediumLockList);
4239 treeLock.acquire();
4240 mediumLock.acquire();
4241 if (SUCCEEDED(rc))
4242 {
4243 mediumLock.release();
4244 treeLock.release();
4245 rc = pMediumLockList->Lock();
4246 treeLock.acquire();
4247 mediumLock.acquire();
4248 if (FAILED(rc))
4249 setError(rc,
4250 tr("Could not lock medium when creating diff '%s'"),
4251 diff->i_getLocationFull().c_str());
4252 else
4253 {
4254 /* will release the lock before the potentially lengthy
4255 * operation, so protect with the special state */
4256 MachineState_T oldState = mData->mMachineState;
4257 i_setMachineState(MachineState_SettingUp);
4258
4259 mediumLock.release();
4260 treeLock.release();
4261 alock.release();
4262
4263 rc = medium->i_createDiffStorage(diff,
4264 medium->i_getPreferredDiffVariant(),
4265 pMediumLockList,
4266 NULL /* aProgress */,
4267 true /* aWait */);
4268
4269 alock.acquire();
4270 treeLock.acquire();
4271 mediumLock.acquire();
4272
4273 i_setMachineState(oldState);
4274 }
4275 }
4276
4277 /* Unlock the media and free the associated memory. */
4278 delete pMediumLockList;
4279
4280 if (FAILED(rc)) return rc;
4281
4282 /* use the created diff for the actual attachment */
4283 medium = diff;
4284 mediumCaller.attach(medium);
4285 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4286 mediumLock.attach(medium);
4287 }
4288 while (0);
4289
4290 ComObjPtr<MediumAttachment> attachment;
4291 attachment.createObject();
4292 rc = attachment->init(this,
4293 medium,
4294 aName,
4295 aControllerPort,
4296 aDevice,
4297 aType,
4298 fIndirect,
4299 false /* fPassthrough */,
4300 false /* fTempEject */,
4301 false /* fNonRotational */,
4302 false /* fDiscard */,
4303 fHotplug /* fHotPluggable */,
4304 Utf8Str::Empty);
4305 if (FAILED(rc)) return rc;
4306
4307 if (associate && !medium.isNull())
4308 {
4309 // as the last step, associate the medium to the VM
4310 rc = medium->i_addBackReference(mData->mUuid);
4311 // here we can fail because of Deleting, or being in process of creating a Diff
4312 if (FAILED(rc)) return rc;
4313
4314 mediumLock.release();
4315 treeLock.release();
4316 alock.release();
4317 i_addMediumToRegistry(medium);
4318 alock.acquire();
4319 treeLock.acquire();
4320 mediumLock.acquire();
4321 }
4322
4323 /* success: finally remember the attachment */
4324 i_setModified(IsModified_Storage);
4325 mMediumAttachments.backup();
4326 mMediumAttachments->push_back(attachment);
4327
4328 mediumLock.release();
4329 treeLock.release();
4330 alock.release();
4331
4332 if (fHotplug || fSilent)
4333 {
4334 if (!medium.isNull())
4335 {
4336 MediumLockList *pMediumLockList(new MediumLockList());
4337
4338 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
4339 medium /* pToLockWrite */,
4340 false /* fMediumLockWriteAll */,
4341 NULL,
4342 *pMediumLockList);
4343 alock.acquire();
4344 if (FAILED(rc))
4345 delete pMediumLockList;
4346 else
4347 {
4348 mData->mSession.mLockedMedia.Unlock();
4349 alock.release();
4350 rc = mData->mSession.mLockedMedia.Insert(attachment, pMediumLockList);
4351 mData->mSession.mLockedMedia.Lock();
4352 alock.acquire();
4353 }
4354 alock.release();
4355 }
4356
4357 if (SUCCEEDED(rc))
4358 {
4359 rc = i_onStorageDeviceChange(attachment, FALSE /* aRemove */, fSilent);
4360 /* Remove lock list in case of error. */
4361 if (FAILED(rc))
4362 {
4363 mData->mSession.mLockedMedia.Unlock();
4364 mData->mSession.mLockedMedia.Remove(attachment);
4365 mData->mSession.mLockedMedia.Lock();
4366 }
4367 }
4368 }
4369
4370 /* Save modified registries, but skip this machine as it's the caller's
4371 * job to save its settings like all other settings changes. */
4372 mParent->i_unmarkRegistryModified(i_getId());
4373 mParent->i_saveModifiedRegistries();
4374
4375 return rc;
4376}
4377
4378HRESULT Machine::detachDevice(const com::Utf8Str &aName, LONG aControllerPort,
4379 LONG aDevice)
4380{
4381 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
4382 aName.c_str(), aControllerPort, aDevice));
4383
4384 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4385
4386 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
4387 if (FAILED(rc)) return rc;
4388
4389 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4390
4391 /* Check for an existing controller. */
4392 ComObjPtr<StorageController> ctl;
4393 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
4394 if (FAILED(rc)) return rc;
4395
4396 StorageControllerType_T ctrlType;
4397 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4398 if (FAILED(rc))
4399 return setError(E_FAIL,
4400 tr("Could not get type of controller '%s'"),
4401 aName.c_str());
4402
4403 bool fSilent = false;
4404 Utf8Str strReconfig;
4405
4406 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
4407 strReconfig = i_getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
4408 if ( mData->mMachineState == MachineState_Paused
4409 && strReconfig == "1")
4410 fSilent = true;
4411
4412 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
4413 bool fHotplug = false;
4414 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
4415 fHotplug = true;
4416
4417 if (fHotplug && !i_isControllerHotplugCapable(ctrlType))
4418 return setError(VBOX_E_INVALID_VM_STATE,
4419 tr("Controller '%s' does not support hotplugging"),
4420 aName.c_str());
4421
4422 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4423 aName,
4424 aControllerPort,
4425 aDevice);
4426 if (!pAttach)
4427 return setError(VBOX_E_OBJECT_NOT_FOUND,
4428 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4429 aDevice, aControllerPort, aName.c_str());
4430
4431 if (fHotplug && !pAttach->i_getHotPluggable())
4432 return setError(VBOX_E_NOT_SUPPORTED,
4433 tr("The device slot %d on port %d of controller '%s' does not support hotplugging"),
4434 aDevice, aControllerPort, aName.c_str());
4435
4436 /*
4437 * The VM has to detach the device before we delete any implicit diffs.
4438 * If this fails we can roll back without loosing data.
4439 */
4440 if (fHotplug || fSilent)
4441 {
4442 alock.release();
4443 rc = i_onStorageDeviceChange(pAttach, TRUE /* aRemove */, fSilent);
4444 alock.acquire();
4445 }
4446 if (FAILED(rc)) return rc;
4447
4448 /* If we are here everything went well and we can delete the implicit now. */
4449 rc = i_detachDevice(pAttach, alock, NULL /* pSnapshot */);
4450
4451 alock.release();
4452
4453 /* Save modified registries, but skip this machine as it's the caller's
4454 * job to save its settings like all other settings changes. */
4455 mParent->i_unmarkRegistryModified(i_getId());
4456 mParent->i_saveModifiedRegistries();
4457
4458 return rc;
4459}
4460
4461HRESULT Machine::passthroughDevice(const com::Utf8Str &aName, LONG aControllerPort,
4462 LONG aDevice, BOOL aPassthrough)
4463{
4464 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aPassthrough=%d\n",
4465 aName.c_str(), aControllerPort, aDevice, aPassthrough));
4466
4467 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4468
4469 HRESULT rc = i_checkStateDependency(MutableStateDep);
4470 if (FAILED(rc)) return rc;
4471
4472 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4473
4474 if (Global::IsOnlineOrTransient(mData->mMachineState))
4475 return setError(VBOX_E_INVALID_VM_STATE,
4476 tr("Invalid machine state: %s"),
4477 Global::stringifyMachineState(mData->mMachineState));
4478
4479 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4480 aName,
4481 aControllerPort,
4482 aDevice);
4483 if (!pAttach)
4484 return setError(VBOX_E_OBJECT_NOT_FOUND,
4485 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4486 aDevice, aControllerPort, aName.c_str());
4487
4488
4489 i_setModified(IsModified_Storage);
4490 mMediumAttachments.backup();
4491
4492 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4493
4494 if (pAttach->i_getType() != DeviceType_DVD)
4495 return setError(E_INVALIDARG,
4496 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
4497 aDevice, aControllerPort, aName.c_str());
4498 pAttach->i_updatePassthrough(!!aPassthrough);
4499
4500 return S_OK;
4501}
4502
4503HRESULT Machine::temporaryEjectDevice(const com::Utf8Str &aName, LONG aControllerPort,
4504 LONG aDevice, BOOL aTemporaryEject)
4505{
4506
4507 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aTemporaryEject=%d\n",
4508 aName.c_str(), aControllerPort, aDevice, aTemporaryEject));
4509
4510 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4511
4512 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
4513 if (FAILED(rc)) return rc;
4514
4515 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4516 aName,
4517 aControllerPort,
4518 aDevice);
4519 if (!pAttach)
4520 return setError(VBOX_E_OBJECT_NOT_FOUND,
4521 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4522 aDevice, aControllerPort, aName.c_str());
4523
4524
4525 i_setModified(IsModified_Storage);
4526 mMediumAttachments.backup();
4527
4528 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4529
4530 if (pAttach->i_getType() != DeviceType_DVD)
4531 return setError(E_INVALIDARG,
4532 tr("Setting temporary eject flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
4533 aDevice, aControllerPort, aName.c_str());
4534 pAttach->i_updateTempEject(!!aTemporaryEject);
4535
4536 return S_OK;
4537}
4538
4539HRESULT Machine::nonRotationalDevice(const com::Utf8Str &aName, LONG aControllerPort,
4540 LONG aDevice, BOOL aNonRotational)
4541{
4542
4543 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aNonRotational=%d\n",
4544 aName.c_str(), aControllerPort, aDevice, aNonRotational));
4545
4546 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4547
4548 HRESULT rc = i_checkStateDependency(MutableStateDep);
4549 if (FAILED(rc)) return rc;
4550
4551 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4552
4553 if (Global::IsOnlineOrTransient(mData->mMachineState))
4554 return setError(VBOX_E_INVALID_VM_STATE,
4555 tr("Invalid machine state: %s"),
4556 Global::stringifyMachineState(mData->mMachineState));
4557
4558 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4559 aName,
4560 aControllerPort,
4561 aDevice);
4562 if (!pAttach)
4563 return setError(VBOX_E_OBJECT_NOT_FOUND,
4564 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4565 aDevice, aControllerPort, aName.c_str());
4566
4567
4568 i_setModified(IsModified_Storage);
4569 mMediumAttachments.backup();
4570
4571 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4572
4573 if (pAttach->i_getType() != DeviceType_HardDisk)
4574 return setError(E_INVALIDARG,
4575 tr("Setting the non-rotational medium flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a hard disk"),
4576 aDevice, aControllerPort, aName.c_str());
4577 pAttach->i_updateNonRotational(!!aNonRotational);
4578
4579 return S_OK;
4580}
4581
4582HRESULT Machine::setAutoDiscardForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4583 LONG aDevice, BOOL aDiscard)
4584{
4585
4586 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aDiscard=%d\n",
4587 aName.c_str(), aControllerPort, aDevice, aDiscard));
4588
4589 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4590
4591 HRESULT rc = i_checkStateDependency(MutableStateDep);
4592 if (FAILED(rc)) return rc;
4593
4594 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4595
4596 if (Global::IsOnlineOrTransient(mData->mMachineState))
4597 return setError(VBOX_E_INVALID_VM_STATE,
4598 tr("Invalid machine state: %s"),
4599 Global::stringifyMachineState(mData->mMachineState));
4600
4601 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4602 aName,
4603 aControllerPort,
4604 aDevice);
4605 if (!pAttach)
4606 return setError(VBOX_E_OBJECT_NOT_FOUND,
4607 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4608 aDevice, aControllerPort, aName.c_str());
4609
4610
4611 i_setModified(IsModified_Storage);
4612 mMediumAttachments.backup();
4613
4614 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4615
4616 if (pAttach->i_getType() != DeviceType_HardDisk)
4617 return setError(E_INVALIDARG,
4618 tr("Setting the discard medium flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a hard disk"),
4619 aDevice, aControllerPort, aName.c_str());
4620 pAttach->i_updateDiscard(!!aDiscard);
4621
4622 return S_OK;
4623}
4624
4625HRESULT Machine::setHotPluggableForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4626 LONG aDevice, BOOL aHotPluggable)
4627{
4628 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aHotPluggable=%d\n",
4629 aName.c_str(), aControllerPort, aDevice, aHotPluggable));
4630
4631 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4632
4633 HRESULT rc = i_checkStateDependency(MutableStateDep);
4634 if (FAILED(rc)) return rc;
4635
4636 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4637
4638 if (Global::IsOnlineOrTransient(mData->mMachineState))
4639 return setError(VBOX_E_INVALID_VM_STATE,
4640 tr("Invalid machine state: %s"),
4641 Global::stringifyMachineState(mData->mMachineState));
4642
4643 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4644 aName,
4645 aControllerPort,
4646 aDevice);
4647 if (!pAttach)
4648 return setError(VBOX_E_OBJECT_NOT_FOUND,
4649 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4650 aDevice, aControllerPort, aName.c_str());
4651
4652 /* Check for an existing controller. */
4653 ComObjPtr<StorageController> ctl;
4654 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
4655 if (FAILED(rc)) return rc;
4656
4657 StorageControllerType_T ctrlType;
4658 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4659 if (FAILED(rc))
4660 return setError(E_FAIL,
4661 tr("Could not get type of controller '%s'"),
4662 aName.c_str());
4663
4664 if (!i_isControllerHotplugCapable(ctrlType))
4665 return setError(VBOX_E_NOT_SUPPORTED,
4666 tr("Controller '%s' does not support changing the hot-pluggable device flag"),
4667 aName.c_str());
4668
4669 i_setModified(IsModified_Storage);
4670 mMediumAttachments.backup();
4671
4672 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4673
4674 if (pAttach->i_getType() == DeviceType_Floppy)
4675 return setError(E_INVALIDARG,
4676 tr("Setting the hot-pluggable device flag rejected as the device attached to device slot %d on port %d of controller '%s' is a floppy drive"),
4677 aDevice, aControllerPort, aName.c_str());
4678 pAttach->i_updateHotPluggable(!!aHotPluggable);
4679
4680 return S_OK;
4681}
4682
4683HRESULT Machine::setNoBandwidthGroupForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4684 LONG aDevice)
4685{
4686 int rc = S_OK;
4687 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4688 aName.c_str(), aControllerPort, aDevice));
4689
4690 rc = setBandwidthGroupForDevice(aName, aControllerPort, aDevice, NULL);
4691
4692 return rc;
4693}
4694
4695HRESULT Machine::setBandwidthGroupForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4696 LONG aDevice, const ComPtr<IBandwidthGroup> &aBandwidthGroup)
4697{
4698 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4699 aName.c_str(), aControllerPort, aDevice));
4700
4701 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4702
4703 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
4704 if (FAILED(rc)) return rc;
4705
4706 if (Global::IsOnlineOrTransient(mData->mMachineState))
4707 return setError(VBOX_E_INVALID_VM_STATE,
4708 tr("Invalid machine state: %s"),
4709 Global::stringifyMachineState(mData->mMachineState));
4710
4711 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4712 aName,
4713 aControllerPort,
4714 aDevice);
4715 if (!pAttach)
4716 return setError(VBOX_E_OBJECT_NOT_FOUND,
4717 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4718 aDevice, aControllerPort, aName.c_str());
4719
4720
4721 i_setModified(IsModified_Storage);
4722 mMediumAttachments.backup();
4723
4724 IBandwidthGroup *iB = aBandwidthGroup;
4725 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(iB);
4726 if (aBandwidthGroup && group.isNull())
4727 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
4728
4729 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4730
4731 const Utf8Str strBandwidthGroupOld = pAttach->i_getBandwidthGroup();
4732 if (strBandwidthGroupOld.isNotEmpty())
4733 {
4734 /* Get the bandwidth group object and release it - this must not fail. */
4735 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
4736 rc = i_getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
4737 Assert(SUCCEEDED(rc));
4738
4739 pBandwidthGroupOld->i_release();
4740 pAttach->i_updateBandwidthGroup(Utf8Str::Empty);
4741 }
4742
4743 if (!group.isNull())
4744 {
4745 group->i_reference();
4746 pAttach->i_updateBandwidthGroup(group->i_getName());
4747 }
4748
4749 return S_OK;
4750}
4751
4752HRESULT Machine::attachDeviceWithoutMedium(const com::Utf8Str &aName,
4753 LONG aControllerPort,
4754 LONG aDevice,
4755 DeviceType_T aType)
4756{
4757 HRESULT rc = S_OK;
4758
4759 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aType=%d\n",
4760 aName.c_str(), aControllerPort, aDevice, aType));
4761
4762 rc = attachDevice(aName, aControllerPort, aDevice, aType, NULL);
4763
4764 return rc;
4765}
4766
4767
4768HRESULT Machine::unmountMedium(const com::Utf8Str &aName,
4769 LONG aControllerPort,
4770 LONG aDevice,
4771 BOOL aForce)
4772{
4773 int rc = S_OK;
4774 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d",
4775 aName.c_str(), aControllerPort, aForce));
4776
4777 rc = mountMedium(aName, aControllerPort, aDevice, NULL, aForce);
4778
4779 return rc;
4780}
4781
4782HRESULT Machine::mountMedium(const com::Utf8Str &aName,
4783 LONG aControllerPort,
4784 LONG aDevice,
4785 const ComPtr<IMedium> &aMedium,
4786 BOOL aForce)
4787{
4788 int rc = S_OK;
4789 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aForce=%d\n",
4790 aName.c_str(), aControllerPort, aDevice, aForce));
4791
4792 // request the host lock first, since might be calling Host methods for getting host drives;
4793 // next, protect the media tree all the while we're in here, as well as our member variables
4794 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
4795 this->lockHandle(),
4796 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4797
4798 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(*mMediumAttachments.data(),
4799 aName,
4800 aControllerPort,
4801 aDevice);
4802 if (pAttach.isNull())
4803 return setError(VBOX_E_OBJECT_NOT_FOUND,
4804 tr("No drive attached to device slot %d on port %d of controller '%s'"),
4805 aDevice, aControllerPort, aName.c_str());
4806
4807 /* Remember previously mounted medium. The medium before taking the
4808 * backup is not necessarily the same thing. */
4809 ComObjPtr<Medium> oldmedium;
4810 oldmedium = pAttach->i_getMedium();
4811
4812 IMedium *iM = aMedium;
4813 ComObjPtr<Medium> pMedium = static_cast<Medium*>(iM);
4814 if (aMedium && pMedium.isNull())
4815 return setError(E_INVALIDARG, "The given medium pointer is invalid");
4816
4817 AutoCaller mediumCaller(pMedium);
4818 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4819
4820 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4821 if (pMedium)
4822 {
4823 DeviceType_T mediumType = pAttach->i_getType();
4824 switch (mediumType)
4825 {
4826 case DeviceType_DVD:
4827 case DeviceType_Floppy:
4828 break;
4829
4830 default:
4831 return setError(VBOX_E_INVALID_OBJECT_STATE,
4832 tr("The device at port %d, device %d of controller '%s' of this virtual machine is not removeable"),
4833 aControllerPort,
4834 aDevice,
4835 aName.c_str());
4836 }
4837 }
4838
4839 i_setModified(IsModified_Storage);
4840 mMediumAttachments.backup();
4841
4842 {
4843 // The backup operation makes the pAttach reference point to the
4844 // old settings. Re-get the correct reference.
4845 pAttach = i_findAttachment(*mMediumAttachments.data(),
4846 aName,
4847 aControllerPort,
4848 aDevice);
4849 if (!oldmedium.isNull())
4850 oldmedium->i_removeBackReference(mData->mUuid);
4851 if (!pMedium.isNull())
4852 {
4853 pMedium->i_addBackReference(mData->mUuid);
4854
4855 mediumLock.release();
4856 multiLock.release();
4857 i_addMediumToRegistry(pMedium);
4858 multiLock.acquire();
4859 mediumLock.acquire();
4860 }
4861
4862 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4863 pAttach->i_updateMedium(pMedium);
4864 }
4865
4866 i_setModified(IsModified_Storage);
4867
4868 mediumLock.release();
4869 multiLock.release();
4870 rc = i_onMediumChange(pAttach, aForce);
4871 multiLock.acquire();
4872 mediumLock.acquire();
4873
4874 /* On error roll back this change only. */
4875 if (FAILED(rc))
4876 {
4877 if (!pMedium.isNull())
4878 pMedium->i_removeBackReference(mData->mUuid);
4879 pAttach = i_findAttachment(*mMediumAttachments.data(),
4880 aName,
4881 aControllerPort,
4882 aDevice);
4883 /* If the attachment is gone in the meantime, bail out. */
4884 if (pAttach.isNull())
4885 return rc;
4886 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4887 if (!oldmedium.isNull())
4888 oldmedium->i_addBackReference(mData->mUuid);
4889 pAttach->i_updateMedium(oldmedium);
4890 }
4891
4892 mediumLock.release();
4893 multiLock.release();
4894
4895 /* Save modified registries, but skip this machine as it's the caller's
4896 * job to save its settings like all other settings changes. */
4897 mParent->i_unmarkRegistryModified(i_getId());
4898 mParent->i_saveModifiedRegistries();
4899
4900 return rc;
4901}
4902HRESULT Machine::getMedium(const com::Utf8Str &aName,
4903 LONG aControllerPort,
4904 LONG aDevice,
4905 ComPtr<IMedium> &aMedium)
4906{
4907 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4908 aName.c_str(), aControllerPort, aDevice));
4909
4910 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4911
4912 aMedium = NULL;
4913
4914 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(*mMediumAttachments.data(),
4915 aName,
4916 aControllerPort,
4917 aDevice);
4918 if (pAttach.isNull())
4919 return setError(VBOX_E_OBJECT_NOT_FOUND,
4920 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4921 aDevice, aControllerPort, aName.c_str());
4922
4923 aMedium = pAttach->i_getMedium();
4924
4925 return S_OK;
4926}
4927
4928HRESULT Machine::getSerialPort(ULONG aSlot, ComPtr<ISerialPort> &aPort)
4929{
4930
4931 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4932
4933 mSerialPorts[aSlot].queryInterfaceTo(aPort.asOutParam());
4934
4935 return S_OK;
4936}
4937
4938HRESULT Machine::getParallelPort(ULONG aSlot, ComPtr<IParallelPort> &aPort)
4939{
4940 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4941
4942 mParallelPorts[aSlot].queryInterfaceTo(aPort.asOutParam());
4943
4944 return S_OK;
4945}
4946
4947HRESULT Machine::getNetworkAdapter(ULONG aSlot, ComPtr<INetworkAdapter> &aAdapter)
4948{
4949 /* Do not assert if slot is out of range, just return the advertised
4950 status. testdriver/vbox.py triggers this in logVmInfo. */
4951 if (aSlot >= mNetworkAdapters.size())
4952 return setError(E_INVALIDARG,
4953 tr("No network adapter in slot %RU32 (total %RU32 adapters)"),
4954 aSlot, mNetworkAdapters.size());
4955
4956 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4957
4958 mNetworkAdapters[aSlot].queryInterfaceTo(aAdapter.asOutParam());
4959
4960 return S_OK;
4961}
4962
4963HRESULT Machine::getExtraDataKeys(std::vector<com::Utf8Str> &aKeys)
4964{
4965 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4966
4967 aKeys.resize(mData->pMachineConfigFile->mapExtraDataItems.size());
4968 size_t i = 0;
4969 for (settings::StringsMap::const_iterator
4970 it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4971 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4972 ++it, ++i)
4973 aKeys[i] = it->first;
4974
4975 return S_OK;
4976}
4977
4978 /**
4979 * @note Locks this object for reading.
4980 */
4981HRESULT Machine::getExtraData(const com::Utf8Str &aKey,
4982 com::Utf8Str &aValue)
4983{
4984 /* start with nothing found */
4985 aValue = "";
4986
4987 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4988
4989 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(aKey);
4990 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4991 // found:
4992 aValue = it->second; // source is a Utf8Str
4993
4994 /* return the result to caller (may be empty) */
4995 return S_OK;
4996}
4997
4998 /**
4999 * @note Locks mParent for writing + this object for writing.
5000 */
5001HRESULT Machine::setExtraData(const com::Utf8Str &aKey, const com::Utf8Str &aValue)
5002{
5003 Utf8Str strOldValue; // empty
5004
5005 // locking note: we only hold the read lock briefly to look up the old value,
5006 // then release it and call the onExtraCanChange callbacks. There is a small
5007 // chance of a race insofar as the callback might be called twice if two callers
5008 // change the same key at the same time, but that's a much better solution
5009 // than the deadlock we had here before. The actual changing of the extradata
5010 // is then performed under the write lock and race-free.
5011
5012 // look up the old value first; if nothing has changed then we need not do anything
5013 {
5014 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
5015
5016 // For snapshots don't even think about allowing changes, extradata
5017 // is global for a machine, so there is nothing snapshot specific.
5018 if (i_isSnapshotMachine())
5019 return setError(VBOX_E_INVALID_VM_STATE,
5020 tr("Cannot set extradata for a snapshot"));
5021
5022 // check if the right IMachine instance is used
5023 if (mData->mRegistered && !i_isSessionMachine())
5024 return setError(VBOX_E_INVALID_VM_STATE,
5025 tr("Cannot set extradata for an immutable machine"));
5026
5027 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(aKey);
5028 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
5029 strOldValue = it->second;
5030 }
5031
5032 bool fChanged;
5033 if ((fChanged = (strOldValue != aValue)))
5034 {
5035 // ask for permission from all listeners outside the locks;
5036 // i_onExtraDataCanChange() only briefly requests the VirtualBox
5037 // lock to copy the list of callbacks to invoke
5038 Bstr error;
5039 Bstr bstrValue(aValue);
5040
5041 if (!mParent->i_onExtraDataCanChange(mData->mUuid, Bstr(aKey).raw(), bstrValue.raw(), error))
5042 {
5043 const char *sep = error.isEmpty() ? "" : ": ";
5044 CBSTR err = error.raw();
5045 Log1WarningFunc(("Someone vetoed! Change refused%s%ls\n", sep, err));
5046 return setError(E_ACCESSDENIED,
5047 tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
5048 aKey.c_str(),
5049 aValue.c_str(),
5050 sep,
5051 err);
5052 }
5053
5054 // data is changing and change not vetoed: then write it out under the lock
5055 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5056
5057 if (aValue.isEmpty())
5058 mData->pMachineConfigFile->mapExtraDataItems.erase(aKey);
5059 else
5060 mData->pMachineConfigFile->mapExtraDataItems[aKey] = aValue;
5061 // creates a new key if needed
5062
5063 bool fNeedsGlobalSaveSettings = false;
5064 // This saving of settings is tricky: there is no "old state" for the
5065 // extradata items at all (unlike all other settings), so the old/new
5066 // settings comparison would give a wrong result!
5067 i_saveSettings(&fNeedsGlobalSaveSettings, SaveS_Force);
5068
5069 if (fNeedsGlobalSaveSettings)
5070 {
5071 // save the global settings; for that we should hold only the VirtualBox lock
5072 alock.release();
5073 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
5074 mParent->i_saveSettings();
5075 }
5076 }
5077
5078 // fire notification outside the lock
5079 if (fChanged)
5080 mParent->i_onExtraDataChange(mData->mUuid, Bstr(aKey).raw(), Bstr(aValue).raw());
5081
5082 return S_OK;
5083}
5084
5085HRESULT Machine::setSettingsFilePath(const com::Utf8Str &aSettingsFilePath, ComPtr<IProgress> &aProgress)
5086{
5087 aProgress = NULL;
5088 NOREF(aSettingsFilePath);
5089 ReturnComNotImplemented();
5090}
5091
5092HRESULT Machine::saveSettings()
5093{
5094 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
5095
5096 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
5097 if (FAILED(rc)) return rc;
5098
5099 /* the settings file path may never be null */
5100 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
5101
5102 /* save all VM data excluding snapshots */
5103 bool fNeedsGlobalSaveSettings = false;
5104 rc = i_saveSettings(&fNeedsGlobalSaveSettings);
5105 mlock.release();
5106
5107 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
5108 {
5109 // save the global settings; for that we should hold only the VirtualBox lock
5110 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
5111 rc = mParent->i_saveSettings();
5112 }
5113
5114 return rc;
5115}
5116
5117
5118HRESULT Machine::discardSettings()
5119{
5120 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5121
5122 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
5123 if (FAILED(rc)) return rc;
5124
5125 /*
5126 * during this rollback, the session will be notified if data has
5127 * been actually changed
5128 */
5129 i_rollback(true /* aNotify */);
5130
5131 return S_OK;
5132}
5133
5134/** @note Locks objects! */
5135HRESULT Machine::unregister(AutoCaller &autoCaller,
5136 CleanupMode_T aCleanupMode,
5137 std::vector<ComPtr<IMedium> > &aMedia)
5138{
5139 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5140
5141 Guid id(i_getId());
5142
5143 if (mData->mSession.mState != SessionState_Unlocked)
5144 return setError(VBOX_E_INVALID_OBJECT_STATE,
5145 tr("Cannot unregister the machine '%s' while it is locked"),
5146 mUserData->s.strName.c_str());
5147
5148 // wait for state dependents to drop to zero
5149 i_ensureNoStateDependencies();
5150
5151 if (!mData->mAccessible)
5152 {
5153 // inaccessible maschines can only be unregistered; uninitialize ourselves
5154 // here because currently there may be no unregistered that are inaccessible
5155 // (this state combination is not supported). Note releasing the caller and
5156 // leaving the lock before calling uninit()
5157 alock.release();
5158 autoCaller.release();
5159
5160 uninit();
5161
5162 mParent->i_unregisterMachine(this, id);
5163 // calls VirtualBox::i_saveSettings()
5164
5165 return S_OK;
5166 }
5167
5168 HRESULT rc = S_OK;
5169
5170 /// @todo r=klaus this is stupid... why is the saved state always deleted?
5171 // discard saved state
5172 if (mData->mMachineState == MachineState_Saved)
5173 {
5174 // add the saved state file to the list of files the caller should delete
5175 Assert(!mSSData->strStateFilePath.isEmpty());
5176 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
5177
5178 mSSData->strStateFilePath.setNull();
5179
5180 // unconditionally set the machine state to powered off, we now
5181 // know no session has locked the machine
5182 mData->mMachineState = MachineState_PoweredOff;
5183 }
5184
5185 size_t cSnapshots = 0;
5186 if (mData->mFirstSnapshot)
5187 cSnapshots = mData->mFirstSnapshot->i_getAllChildrenCount() + 1;
5188 if (cSnapshots && aCleanupMode == CleanupMode_UnregisterOnly)
5189 // fail now before we start detaching media
5190 return setError(VBOX_E_INVALID_OBJECT_STATE,
5191 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
5192 mUserData->s.strName.c_str(), cSnapshots);
5193
5194 // This list collects the medium objects from all medium attachments
5195 // which we will detach from the machine and its snapshots, in a specific
5196 // order which allows for closing all media without getting "media in use"
5197 // errors, simply by going through the list from the front to the back:
5198 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
5199 // and must be closed before the parent media from the snapshots, or closing the parents
5200 // will fail because they still have children);
5201 // 2) media from the youngest snapshots followed by those from the parent snapshots until
5202 // the root ("first") snapshot of the machine.
5203 MediaList llMedia;
5204
5205 if ( !mMediumAttachments.isNull() // can be NULL if machine is inaccessible
5206 && mMediumAttachments->size()
5207 )
5208 {
5209 // we have media attachments: detach them all and add the Medium objects to our list
5210 if (aCleanupMode != CleanupMode_UnregisterOnly)
5211 i_detachAllMedia(alock, NULL /* pSnapshot */, aCleanupMode, llMedia);
5212 else
5213 return setError(VBOX_E_INVALID_OBJECT_STATE,
5214 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
5215 mUserData->s.strName.c_str(), mMediumAttachments->size());
5216 }
5217
5218 if (cSnapshots)
5219 {
5220 // add the media from the medium attachments of the snapshots to llMedia
5221 // as well, after the "main" machine media; Snapshot::uninitRecursively()
5222 // calls Machine::detachAllMedia() for the snapshot machine, recursing
5223 // into the children first
5224
5225 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
5226 MachineState_T oldState = mData->mMachineState;
5227 mData->mMachineState = MachineState_DeletingSnapshot;
5228
5229 // make a copy of the first snapshot so the refcount does not drop to 0
5230 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
5231 // because of the AutoCaller voodoo)
5232 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
5233
5234 // GO!
5235 pFirstSnapshot->i_uninitRecursively(alock, aCleanupMode, llMedia, mData->llFilesToDelete);
5236
5237 mData->mMachineState = oldState;
5238 }
5239
5240 if (FAILED(rc))
5241 {
5242 i_rollbackMedia();
5243 return rc;
5244 }
5245
5246 // commit all the media changes made above
5247 i_commitMedia();
5248
5249 mData->mRegistered = false;
5250
5251 // machine lock no longer needed
5252 alock.release();
5253
5254 // return media to caller
5255 aMedia.resize(llMedia.size());
5256 size_t i = 0;
5257 for (MediaList::const_iterator
5258 it = llMedia.begin();
5259 it != llMedia.end();
5260 ++it, ++i)
5261 (*it).queryInterfaceTo(aMedia[i].asOutParam());
5262
5263 mParent->i_unregisterMachine(this, id);
5264 // calls VirtualBox::i_saveSettings() and VirtualBox::saveModifiedRegistries()
5265
5266 return S_OK;
5267}
5268
5269/**
5270 * Task record for deleting a machine config.
5271 */
5272class Machine::DeleteConfigTask
5273 : public Machine::Task
5274{
5275public:
5276 DeleteConfigTask(Machine *m,
5277 Progress *p,
5278 const Utf8Str &t,
5279 const RTCList<ComPtr<IMedium> > &llMediums,
5280 const StringsList &llFilesToDelete)
5281 : Task(m, p, t),
5282 m_llMediums(llMediums),
5283 m_llFilesToDelete(llFilesToDelete)
5284 {}
5285
5286private:
5287 void handler()
5288 {
5289 try
5290 {
5291 m_pMachine->i_deleteConfigHandler(*this);
5292 }
5293 catch (...)
5294 {
5295 LogRel(("Some exception in the function Machine::i_deleteConfigHandler()\n"));
5296 }
5297 }
5298
5299 RTCList<ComPtr<IMedium> > m_llMediums;
5300 StringsList m_llFilesToDelete;
5301
5302 friend void Machine::i_deleteConfigHandler(DeleteConfigTask &task);
5303};
5304
5305/**
5306 * Task thread implementation for SessionMachine::DeleteConfig(), called from
5307 * SessionMachine::taskHandler().
5308 *
5309 * @note Locks this object for writing.
5310 *
5311 * @param task
5312 * @return
5313 */
5314void Machine::i_deleteConfigHandler(DeleteConfigTask &task)
5315{
5316 LogFlowThisFuncEnter();
5317
5318 AutoCaller autoCaller(this);
5319 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
5320 if (FAILED(autoCaller.rc()))
5321 {
5322 /* we might have been uninitialized because the session was accidentally
5323 * closed by the client, so don't assert */
5324 HRESULT rc = setError(E_FAIL,
5325 tr("The session has been accidentally closed"));
5326 task.m_pProgress->i_notifyComplete(rc);
5327 LogFlowThisFuncLeave();
5328 return;
5329 }
5330
5331 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5332
5333 HRESULT rc = S_OK;
5334
5335 try
5336 {
5337 ULONG uLogHistoryCount = 3;
5338 ComPtr<ISystemProperties> systemProperties;
5339 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
5340 if (FAILED(rc)) throw rc;
5341
5342 if (!systemProperties.isNull())
5343 {
5344 rc = systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
5345 if (FAILED(rc)) throw rc;
5346 }
5347
5348 MachineState_T oldState = mData->mMachineState;
5349 i_setMachineState(MachineState_SettingUp);
5350 alock.release();
5351 for (size_t i = 0; i < task.m_llMediums.size(); ++i)
5352 {
5353 ComObjPtr<Medium> pMedium = (Medium*)(IMedium*)(task.m_llMediums.at(i));
5354 {
5355 AutoCaller mac(pMedium);
5356 if (FAILED(mac.rc())) throw mac.rc();
5357 Utf8Str strLocation = pMedium->i_getLocationFull();
5358 LogFunc(("Deleting file %s\n", strLocation.c_str()));
5359 rc = task.m_pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), strLocation.c_str()).raw(), 1);
5360 if (FAILED(rc)) throw rc;
5361 }
5362 if (pMedium->i_isMediumFormatFile())
5363 {
5364 ComPtr<IProgress> pProgress2;
5365 rc = pMedium->DeleteStorage(pProgress2.asOutParam());
5366 if (FAILED(rc)) throw rc;
5367 rc = task.m_pProgress->WaitForAsyncProgressCompletion(pProgress2);
5368 if (FAILED(rc)) throw rc;
5369 /* Check the result of the asynchronous process. */
5370 LONG iRc;
5371 rc = pProgress2->COMGETTER(ResultCode)(&iRc);
5372 if (FAILED(rc)) throw rc;
5373 /* If the thread of the progress object has an error, then
5374 * retrieve the error info from there, or it'll be lost. */
5375 if (FAILED(iRc))
5376 throw setError(ProgressErrorInfo(pProgress2));
5377 }
5378
5379 /* Close the medium, deliberately without checking the return
5380 * code, and without leaving any trace in the error info, as
5381 * a failure here is a very minor issue, which shouldn't happen
5382 * as above we even managed to delete the medium. */
5383 {
5384 ErrorInfoKeeper eik;
5385 pMedium->Close();
5386 }
5387 }
5388 i_setMachineState(oldState);
5389 alock.acquire();
5390
5391 // delete the files pushed on the task list by Machine::Delete()
5392 // (this includes saved states of the machine and snapshots and
5393 // medium storage files from the IMedium list passed in, and the
5394 // machine XML file)
5395 for (StringsList::const_iterator
5396 it = task.m_llFilesToDelete.begin();
5397 it != task.m_llFilesToDelete.end();
5398 ++it)
5399 {
5400 const Utf8Str &strFile = *it;
5401 LogFunc(("Deleting file %s\n", strFile.c_str()));
5402 rc = task.m_pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
5403 if (FAILED(rc)) throw rc;
5404
5405 int vrc = RTFileDelete(strFile.c_str());
5406 if (RT_FAILURE(vrc))
5407 throw setError(VBOX_E_IPRT_ERROR,
5408 tr("Could not delete file '%s' (%Rrc)"), strFile.c_str(), vrc);
5409 }
5410
5411 rc = task.m_pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
5412 if (FAILED(rc)) throw rc;
5413
5414 /* delete the settings only when the file actually exists */
5415 if (mData->pMachineConfigFile->fileExists())
5416 {
5417 /* Delete any backup or uncommitted XML files. Ignore failures.
5418 See the fSafe parameter of xml::XmlFileWriter::write for details. */
5419 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
5420 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
5421 RTFileDelete(otherXml.c_str());
5422 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
5423 RTFileDelete(otherXml.c_str());
5424
5425 /* delete the Logs folder, nothing important should be left
5426 * there (we don't check for errors because the user might have
5427 * some private files there that we don't want to delete) */
5428 Utf8Str logFolder;
5429 getLogFolder(logFolder);
5430 Assert(logFolder.length());
5431 if (RTDirExists(logFolder.c_str()))
5432 {
5433 /* Delete all VBox.log[.N] files from the Logs folder
5434 * (this must be in sync with the rotation logic in
5435 * Console::powerUpThread()). Also, delete the VBox.png[.N]
5436 * files that may have been created by the GUI. */
5437 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
5438 logFolder.c_str(), RTPATH_DELIMITER);
5439 RTFileDelete(log.c_str());
5440 log = Utf8StrFmt("%s%cVBox.png",
5441 logFolder.c_str(), RTPATH_DELIMITER);
5442 RTFileDelete(log.c_str());
5443 for (int i = uLogHistoryCount; i > 0; i--)
5444 {
5445 log = Utf8StrFmt("%s%cVBox.log.%d",
5446 logFolder.c_str(), RTPATH_DELIMITER, i);
5447 RTFileDelete(log.c_str());
5448 log = Utf8StrFmt("%s%cVBox.png.%d",
5449 logFolder.c_str(), RTPATH_DELIMITER, i);
5450 RTFileDelete(log.c_str());
5451 }
5452#if defined(RT_OS_WINDOWS)
5453 log = Utf8StrFmt("%s%cVBoxStartup.log", logFolder.c_str(), RTPATH_DELIMITER);
5454 RTFileDelete(log.c_str());
5455 log = Utf8StrFmt("%s%cVBoxHardening.log", logFolder.c_str(), RTPATH_DELIMITER);
5456 RTFileDelete(log.c_str());
5457#endif
5458
5459 RTDirRemove(logFolder.c_str());
5460 }
5461
5462 /* delete the Snapshots folder, nothing important should be left
5463 * there (we don't check for errors because the user might have
5464 * some private files there that we don't want to delete) */
5465 Utf8Str strFullSnapshotFolder;
5466 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
5467 Assert(!strFullSnapshotFolder.isEmpty());
5468 if (RTDirExists(strFullSnapshotFolder.c_str()))
5469 RTDirRemove(strFullSnapshotFolder.c_str());
5470
5471 // delete the directory that contains the settings file, but only
5472 // if it matches the VM name
5473 Utf8Str settingsDir;
5474 if (i_isInOwnDir(&settingsDir))
5475 RTDirRemove(settingsDir.c_str());
5476 }
5477
5478 alock.release();
5479
5480 mParent->i_saveModifiedRegistries();
5481 }
5482 catch (HRESULT aRC) { rc = aRC; }
5483
5484 task.m_pProgress->i_notifyComplete(rc);
5485
5486 LogFlowThisFuncLeave();
5487}
5488
5489HRESULT Machine::deleteConfig(const std::vector<ComPtr<IMedium> > &aMedia, ComPtr<IProgress> &aProgress)
5490{
5491 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5492
5493 HRESULT rc = i_checkStateDependency(MutableStateDep);
5494 if (FAILED(rc)) return rc;
5495
5496 if (mData->mRegistered)
5497 return setError(VBOX_E_INVALID_VM_STATE,
5498 tr("Cannot delete settings of a registered machine"));
5499
5500 // collect files to delete
5501 StringsList llFilesToDelete(mData->llFilesToDelete); // saved states pushed here by Unregister()
5502 if (mData->pMachineConfigFile->fileExists())
5503 llFilesToDelete.push_back(mData->m_strConfigFileFull);
5504
5505 RTCList<ComPtr<IMedium> > llMediums;
5506 for (size_t i = 0; i < aMedia.size(); ++i)
5507 {
5508 IMedium *pIMedium(aMedia[i]);
5509 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
5510 if (pMedium.isNull())
5511 return setError(E_INVALIDARG, "The given medium pointer with index %d is invalid", i);
5512 SafeArray<BSTR> ids;
5513 rc = pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(ids));
5514 if (FAILED(rc)) return rc;
5515 /* At this point the medium should not have any back references
5516 * anymore. If it has it is attached to another VM and *must* not
5517 * deleted. */
5518 if (ids.size() < 1)
5519 llMediums.append(pMedium);
5520 }
5521
5522 ComObjPtr<Progress> pProgress;
5523 pProgress.createObject();
5524 rc = pProgress->init(i_getVirtualBox(),
5525 static_cast<IMachine*>(this) /* aInitiator */,
5526 tr("Deleting files"),
5527 true /* fCancellable */,
5528 (ULONG)(1 + llMediums.size() + llFilesToDelete.size() + 1), // cOperations
5529 tr("Collecting file inventory"));
5530 if (FAILED(rc))
5531 return rc;
5532
5533 /* create and start the task on a separate thread (note that it will not
5534 * start working until we release alock) */
5535 DeleteConfigTask *pTask = new DeleteConfigTask(this, pProgress, "DeleteVM", llMediums, llFilesToDelete);
5536 rc = pTask->createThread();
5537 if (FAILED(rc))
5538 return rc;
5539
5540 pProgress.queryInterfaceTo(aProgress.asOutParam());
5541
5542 LogFlowFuncLeave();
5543
5544 return S_OK;
5545}
5546
5547HRESULT Machine::findSnapshot(const com::Utf8Str &aNameOrId, ComPtr<ISnapshot> &aSnapshot)
5548{
5549 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5550
5551 ComObjPtr<Snapshot> pSnapshot;
5552 HRESULT rc;
5553
5554 if (aNameOrId.isEmpty())
5555 // null case (caller wants root snapshot): i_findSnapshotById() handles this
5556 rc = i_findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
5557 else
5558 {
5559 Guid uuid(aNameOrId);
5560 if (uuid.isValid())
5561 rc = i_findSnapshotById(uuid, pSnapshot, true /* aSetError */);
5562 else
5563 rc = i_findSnapshotByName(aNameOrId, pSnapshot, true /* aSetError */);
5564 }
5565 pSnapshot.queryInterfaceTo(aSnapshot.asOutParam());
5566
5567 return rc;
5568}
5569
5570HRESULT Machine::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable, BOOL aAutomount)
5571{
5572 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5573
5574 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
5575 if (FAILED(rc)) return rc;
5576
5577 ComObjPtr<SharedFolder> sharedFolder;
5578 rc = i_findSharedFolder(aName, sharedFolder, false /* aSetError */);
5579 if (SUCCEEDED(rc))
5580 return setError(VBOX_E_OBJECT_IN_USE,
5581 tr("Shared folder named '%s' already exists"),
5582 aName.c_str());
5583
5584 sharedFolder.createObject();
5585 rc = sharedFolder->init(i_getMachine(),
5586 aName,
5587 aHostPath,
5588 !!aWritable,
5589 !!aAutomount,
5590 true /* fFailOnError */);
5591 if (FAILED(rc)) return rc;
5592
5593 i_setModified(IsModified_SharedFolders);
5594 mHWData.backup();
5595 mHWData->mSharedFolders.push_back(sharedFolder);
5596
5597 /* inform the direct session if any */
5598 alock.release();
5599 i_onSharedFolderChange();
5600
5601 return S_OK;
5602}
5603
5604HRESULT Machine::removeSharedFolder(const com::Utf8Str &aName)
5605{
5606 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5607
5608 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
5609 if (FAILED(rc)) return rc;
5610
5611 ComObjPtr<SharedFolder> sharedFolder;
5612 rc = i_findSharedFolder(aName, sharedFolder, true /* aSetError */);
5613 if (FAILED(rc)) return rc;
5614
5615 i_setModified(IsModified_SharedFolders);
5616 mHWData.backup();
5617 mHWData->mSharedFolders.remove(sharedFolder);
5618
5619 /* inform the direct session if any */
5620 alock.release();
5621 i_onSharedFolderChange();
5622
5623 return S_OK;
5624}
5625
5626HRESULT Machine::canShowConsoleWindow(BOOL *aCanShow)
5627{
5628 /* start with No */
5629 *aCanShow = FALSE;
5630
5631 ComPtr<IInternalSessionControl> directControl;
5632 {
5633 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5634
5635 if (mData->mSession.mState != SessionState_Locked)
5636 return setError(VBOX_E_INVALID_VM_STATE,
5637 tr("Machine is not locked for session (session state: %s)"),
5638 Global::stringifySessionState(mData->mSession.mState));
5639
5640 if (mData->mSession.mLockType == LockType_VM)
5641 directControl = mData->mSession.mDirectControl;
5642 }
5643
5644 /* ignore calls made after #OnSessionEnd() is called */
5645 if (!directControl)
5646 return S_OK;
5647
5648 LONG64 dummy;
5649 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
5650}
5651
5652HRESULT Machine::showConsoleWindow(LONG64 *aWinId)
5653{
5654 ComPtr<IInternalSessionControl> directControl;
5655 {
5656 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5657
5658 if (mData->mSession.mState != SessionState_Locked)
5659 return setError(E_FAIL,
5660 tr("Machine is not locked for session (session state: %s)"),
5661 Global::stringifySessionState(mData->mSession.mState));
5662
5663 if (mData->mSession.mLockType == LockType_VM)
5664 directControl = mData->mSession.mDirectControl;
5665 }
5666
5667 /* ignore calls made after #OnSessionEnd() is called */
5668 if (!directControl)
5669 return S_OK;
5670
5671 BOOL dummy;
5672 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
5673}
5674
5675#ifdef VBOX_WITH_GUEST_PROPS
5676/**
5677 * Look up a guest property in VBoxSVC's internal structures.
5678 */
5679HRESULT Machine::i_getGuestPropertyFromService(const com::Utf8Str &aName,
5680 com::Utf8Str &aValue,
5681 LONG64 *aTimestamp,
5682 com::Utf8Str &aFlags) const
5683{
5684 using namespace guestProp;
5685
5686 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5687 HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.find(aName);
5688
5689 if (it != mHWData->mGuestProperties.end())
5690 {
5691 char szFlags[MAX_FLAGS_LEN + 1];
5692 aValue = it->second.strValue;
5693 *aTimestamp = it->second.mTimestamp;
5694 writeFlags(it->second.mFlags, szFlags);
5695 aFlags = Utf8Str(szFlags);
5696 }
5697
5698 return S_OK;
5699}
5700
5701/**
5702 * Query the VM that a guest property belongs to for the property.
5703 * @returns E_ACCESSDENIED if the VM process is not available or not
5704 * currently handling queries and the lookup should then be done in
5705 * VBoxSVC.
5706 */
5707HRESULT Machine::i_getGuestPropertyFromVM(const com::Utf8Str &aName,
5708 com::Utf8Str &aValue,
5709 LONG64 *aTimestamp,
5710 com::Utf8Str &aFlags) const
5711{
5712 HRESULT rc = S_OK;
5713 BSTR bValue = NULL;
5714 BSTR bFlags = NULL;
5715
5716 ComPtr<IInternalSessionControl> directControl;
5717 {
5718 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5719 if (mData->mSession.mLockType == LockType_VM)
5720 directControl = mData->mSession.mDirectControl;
5721 }
5722
5723 /* ignore calls made after #OnSessionEnd() is called */
5724 if (!directControl)
5725 rc = E_ACCESSDENIED;
5726 else
5727 rc = directControl->AccessGuestProperty(Bstr(aName).raw(), Bstr::Empty.raw(), Bstr::Empty.raw(),
5728 0 /* accessMode */,
5729 &bValue, aTimestamp, &bFlags);
5730
5731 aValue = bValue;
5732 aFlags = bFlags;
5733
5734 return rc;
5735}
5736#endif // VBOX_WITH_GUEST_PROPS
5737
5738HRESULT Machine::getGuestProperty(const com::Utf8Str &aName,
5739 com::Utf8Str &aValue,
5740 LONG64 *aTimestamp,
5741 com::Utf8Str &aFlags)
5742{
5743#ifndef VBOX_WITH_GUEST_PROPS
5744 ReturnComNotImplemented();
5745#else // VBOX_WITH_GUEST_PROPS
5746
5747 HRESULT rc = i_getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
5748
5749 if (rc == E_ACCESSDENIED)
5750 /* The VM is not running or the service is not (yet) accessible */
5751 rc = i_getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
5752 return rc;
5753#endif // VBOX_WITH_GUEST_PROPS
5754}
5755
5756HRESULT Machine::getGuestPropertyValue(const com::Utf8Str &aProperty, com::Utf8Str &aValue)
5757{
5758 LONG64 dummyTimestamp;
5759 com::Utf8Str dummyFlags;
5760 HRESULT rc = getGuestProperty(aProperty, aValue, &dummyTimestamp, dummyFlags);
5761 return rc;
5762
5763}
5764HRESULT Machine::getGuestPropertyTimestamp(const com::Utf8Str &aProperty, LONG64 *aValue)
5765{
5766 com::Utf8Str dummyFlags;
5767 com::Utf8Str dummyValue;
5768 HRESULT rc = getGuestProperty(aProperty, dummyValue, aValue, dummyFlags);
5769 return rc;
5770}
5771
5772#ifdef VBOX_WITH_GUEST_PROPS
5773/**
5774 * Set a guest property in VBoxSVC's internal structures.
5775 */
5776HRESULT Machine::i_setGuestPropertyToService(const com::Utf8Str &aName, const com::Utf8Str &aValue,
5777 const com::Utf8Str &aFlags, bool fDelete)
5778{
5779 using namespace guestProp;
5780
5781 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5782 HRESULT rc = S_OK;
5783
5784 rc = i_checkStateDependency(MutableOrSavedStateDep);
5785 if (FAILED(rc)) return rc;
5786
5787 try
5788 {
5789 uint32_t fFlags = NILFLAG;
5790 if (aFlags.length() && RT_FAILURE(validateFlags(aFlags.c_str(), &fFlags)))
5791 return setError(E_INVALIDARG, tr("Invalid guest property flag values: '%s'"), aFlags.c_str());
5792
5793 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
5794 if (it == mHWData->mGuestProperties.end())
5795 {
5796 if (!fDelete)
5797 {
5798 i_setModified(IsModified_MachineData);
5799 mHWData.backupEx();
5800
5801 RTTIMESPEC time;
5802 HWData::GuestProperty prop;
5803 prop.strValue = Bstr(aValue).raw();
5804 prop.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5805 prop.mFlags = fFlags;
5806 mHWData->mGuestProperties[aName] = prop;
5807 }
5808 }
5809 else
5810 {
5811 if (it->second.mFlags & (RDONLYHOST))
5812 {
5813 rc = setError(E_ACCESSDENIED, tr("The property '%s' cannot be changed by the host"), aName.c_str());
5814 }
5815 else
5816 {
5817 i_setModified(IsModified_MachineData);
5818 mHWData.backupEx();
5819
5820 /* The backupEx() operation invalidates our iterator,
5821 * so get a new one. */
5822 it = mHWData->mGuestProperties.find(aName);
5823 Assert(it != mHWData->mGuestProperties.end());
5824
5825 if (!fDelete)
5826 {
5827 RTTIMESPEC time;
5828 it->second.strValue = aValue;
5829 it->second.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5830 it->second.mFlags = fFlags;
5831 }
5832 else
5833 mHWData->mGuestProperties.erase(it);
5834 }
5835 }
5836
5837 if (SUCCEEDED(rc))
5838 {
5839 alock.release();
5840
5841 mParent->i_onGuestPropertyChange(mData->mUuid,
5842 Bstr(aName).raw(),
5843 Bstr(aValue).raw(),
5844 Bstr(aFlags).raw());
5845 }
5846 }
5847 catch (std::bad_alloc &)
5848 {
5849 rc = E_OUTOFMEMORY;
5850 }
5851
5852 return rc;
5853}
5854
5855/**
5856 * Set a property on the VM that that property belongs to.
5857 * @returns E_ACCESSDENIED if the VM process is not available or not
5858 * currently handling queries and the setting should then be done in
5859 * VBoxSVC.
5860 */
5861HRESULT Machine::i_setGuestPropertyToVM(const com::Utf8Str &aName, const com::Utf8Str &aValue,
5862 const com::Utf8Str &aFlags, bool fDelete)
5863{
5864 HRESULT rc;
5865
5866 try
5867 {
5868 ComPtr<IInternalSessionControl> directControl;
5869 {
5870 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5871 if (mData->mSession.mLockType == LockType_VM)
5872 directControl = mData->mSession.mDirectControl;
5873 }
5874
5875 BSTR dummy = NULL; /* will not be changed (setter) */
5876 LONG64 dummy64;
5877 if (!directControl)
5878 rc = E_ACCESSDENIED;
5879 else
5880 /** @todo Fix when adding DeleteGuestProperty(), see defect. */
5881 rc = directControl->AccessGuestProperty(Bstr(aName).raw(), Bstr(aValue).raw(), Bstr(aFlags).raw(),
5882 fDelete? 2: 1 /* accessMode */,
5883 &dummy, &dummy64, &dummy);
5884 }
5885 catch (std::bad_alloc &)
5886 {
5887 rc = E_OUTOFMEMORY;
5888 }
5889
5890 return rc;
5891}
5892#endif // VBOX_WITH_GUEST_PROPS
5893
5894HRESULT Machine::setGuestProperty(const com::Utf8Str &aProperty, const com::Utf8Str &aValue,
5895 const com::Utf8Str &aFlags)
5896{
5897#ifndef VBOX_WITH_GUEST_PROPS
5898 ReturnComNotImplemented();
5899#else // VBOX_WITH_GUEST_PROPS
5900 HRESULT rc = i_setGuestPropertyToVM(aProperty, aValue, aFlags, /* fDelete = */ false);
5901 if (rc == E_ACCESSDENIED)
5902 /* The VM is not running or the service is not (yet) accessible */
5903 rc = i_setGuestPropertyToService(aProperty, aValue, aFlags, /* fDelete = */ false);
5904 return rc;
5905#endif // VBOX_WITH_GUEST_PROPS
5906}
5907
5908HRESULT Machine::setGuestPropertyValue(const com::Utf8Str &aProperty, const com::Utf8Str &aValue)
5909{
5910 return setGuestProperty(aProperty, aValue, "");
5911}
5912
5913HRESULT Machine::deleteGuestProperty(const com::Utf8Str &aName)
5914{
5915#ifndef VBOX_WITH_GUEST_PROPS
5916 ReturnComNotImplemented();
5917#else // VBOX_WITH_GUEST_PROPS
5918 HRESULT rc = i_setGuestPropertyToVM(aName, "", "", /* fDelete = */ true);
5919 if (rc == E_ACCESSDENIED)
5920 /* The VM is not running or the service is not (yet) accessible */
5921 rc = i_setGuestPropertyToService(aName, "", "", /* fDelete = */ true);
5922 return rc;
5923#endif // VBOX_WITH_GUEST_PROPS
5924}
5925
5926#ifdef VBOX_WITH_GUEST_PROPS
5927/**
5928 * Enumerate the guest properties in VBoxSVC's internal structures.
5929 */
5930HRESULT Machine::i_enumerateGuestPropertiesInService(const com::Utf8Str &aPatterns,
5931 std::vector<com::Utf8Str> &aNames,
5932 std::vector<com::Utf8Str> &aValues,
5933 std::vector<LONG64> &aTimestamps,
5934 std::vector<com::Utf8Str> &aFlags)
5935{
5936 using namespace guestProp;
5937
5938 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5939 Utf8Str strPatterns(aPatterns);
5940
5941 HWData::GuestPropertyMap propMap;
5942
5943 /*
5944 * Look for matching patterns and build up a list.
5945 */
5946 for (HWData::GuestPropertyMap::const_iterator
5947 it = mHWData->mGuestProperties.begin();
5948 it != mHWData->mGuestProperties.end();
5949 ++it)
5950 {
5951 if ( strPatterns.isEmpty()
5952 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5953 RTSTR_MAX,
5954 it->first.c_str(),
5955 RTSTR_MAX,
5956 NULL)
5957 )
5958 propMap.insert(*it);
5959 }
5960
5961 alock.release();
5962
5963 /*
5964 * And build up the arrays for returning the property information.
5965 */
5966 size_t cEntries = propMap.size();
5967
5968 aNames.resize(cEntries);
5969 aValues.resize(cEntries);
5970 aTimestamps.resize(cEntries);
5971 aFlags.resize(cEntries);
5972
5973 char szFlags[MAX_FLAGS_LEN + 1];
5974 size_t i = 0;
5975 for (HWData::GuestPropertyMap::const_iterator
5976 it = propMap.begin();
5977 it != propMap.end();
5978 ++it, ++i)
5979 {
5980 aNames[i] = it->first;
5981 aValues[i] = it->second.strValue;
5982 aTimestamps[i] = it->second.mTimestamp;
5983 writeFlags(it->second.mFlags, szFlags);
5984 aFlags[i] = Utf8Str(szFlags);
5985 }
5986
5987 return S_OK;
5988}
5989
5990/**
5991 * Enumerate the properties managed by a VM.
5992 * @returns E_ACCESSDENIED if the VM process is not available or not
5993 * currently handling queries and the setting should then be done in
5994 * VBoxSVC.
5995 */
5996HRESULT Machine::i_enumerateGuestPropertiesOnVM(const com::Utf8Str &aPatterns,
5997 std::vector<com::Utf8Str> &aNames,
5998 std::vector<com::Utf8Str> &aValues,
5999 std::vector<LONG64> &aTimestamps,
6000 std::vector<com::Utf8Str> &aFlags)
6001{
6002 HRESULT rc;
6003 ComPtr<IInternalSessionControl> directControl;
6004 {
6005 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6006 if (mData->mSession.mLockType == LockType_VM)
6007 directControl = mData->mSession.mDirectControl;
6008 }
6009
6010 com::SafeArray<BSTR> bNames;
6011 com::SafeArray<BSTR> bValues;
6012 com::SafeArray<LONG64> bTimestamps;
6013 com::SafeArray<BSTR> bFlags;
6014
6015 if (!directControl)
6016 rc = E_ACCESSDENIED;
6017 else
6018 rc = directControl->EnumerateGuestProperties(Bstr(aPatterns).raw(),
6019 ComSafeArrayAsOutParam(bNames),
6020 ComSafeArrayAsOutParam(bValues),
6021 ComSafeArrayAsOutParam(bTimestamps),
6022 ComSafeArrayAsOutParam(bFlags));
6023 size_t i;
6024 aNames.resize(bNames.size());
6025 for (i = 0; i < bNames.size(); ++i)
6026 aNames[i] = Utf8Str(bNames[i]);
6027 aValues.resize(bValues.size());
6028 for (i = 0; i < bValues.size(); ++i)
6029 aValues[i] = Utf8Str(bValues[i]);
6030 aTimestamps.resize(bTimestamps.size());
6031 for (i = 0; i < bTimestamps.size(); ++i)
6032 aTimestamps[i] = bTimestamps[i];
6033 aFlags.resize(bFlags.size());
6034 for (i = 0; i < bFlags.size(); ++i)
6035 aFlags[i] = Utf8Str(bFlags[i]);
6036
6037 return rc;
6038}
6039#endif // VBOX_WITH_GUEST_PROPS
6040HRESULT Machine::enumerateGuestProperties(const com::Utf8Str &aPatterns,
6041 std::vector<com::Utf8Str> &aNames,
6042 std::vector<com::Utf8Str> &aValues,
6043 std::vector<LONG64> &aTimestamps,
6044 std::vector<com::Utf8Str> &aFlags)
6045{
6046#ifndef VBOX_WITH_GUEST_PROPS
6047 ReturnComNotImplemented();
6048#else // VBOX_WITH_GUEST_PROPS
6049
6050 HRESULT rc = i_enumerateGuestPropertiesOnVM(aPatterns, aNames, aValues, aTimestamps, aFlags);
6051
6052 if (rc == E_ACCESSDENIED)
6053 /* The VM is not running or the service is not (yet) accessible */
6054 rc = i_enumerateGuestPropertiesInService(aPatterns, aNames, aValues, aTimestamps, aFlags);
6055 return rc;
6056#endif // VBOX_WITH_GUEST_PROPS
6057}
6058
6059HRESULT Machine::getMediumAttachmentsOfController(const com::Utf8Str &aName,
6060 std::vector<ComPtr<IMediumAttachment> > &aMediumAttachments)
6061{
6062 MediumAttachmentList atts;
6063
6064 HRESULT rc = i_getMediumAttachmentsOfController(aName, atts);
6065 if (FAILED(rc)) return rc;
6066
6067 aMediumAttachments.resize(atts.size());
6068 size_t i = 0;
6069 for (MediumAttachmentList::const_iterator
6070 it = atts.begin();
6071 it != atts.end();
6072 ++it, ++i)
6073 (*it).queryInterfaceTo(aMediumAttachments[i].asOutParam());
6074
6075 return S_OK;
6076}
6077
6078HRESULT Machine::getMediumAttachment(const com::Utf8Str &aName,
6079 LONG aControllerPort,
6080 LONG aDevice,
6081 ComPtr<IMediumAttachment> &aAttachment)
6082{
6083 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
6084 aName.c_str(), aControllerPort, aDevice));
6085
6086 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6087
6088 aAttachment = NULL;
6089
6090 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(*mMediumAttachments.data(),
6091 aName,
6092 aControllerPort,
6093 aDevice);
6094 if (pAttach.isNull())
6095 return setError(VBOX_E_OBJECT_NOT_FOUND,
6096 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
6097 aDevice, aControllerPort, aName.c_str());
6098
6099 pAttach.queryInterfaceTo(aAttachment.asOutParam());
6100
6101 return S_OK;
6102}
6103
6104
6105HRESULT Machine::addStorageController(const com::Utf8Str &aName,
6106 StorageBus_T aConnectionType,
6107 ComPtr<IStorageController> &aController)
6108{
6109 if ( (aConnectionType <= StorageBus_Null)
6110 || (aConnectionType > StorageBus_PCIe))
6111 return setError(E_INVALIDARG,
6112 tr("Invalid connection type: %d"),
6113 aConnectionType);
6114
6115 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6116
6117 HRESULT rc = i_checkStateDependency(MutableStateDep);
6118 if (FAILED(rc)) return rc;
6119
6120 /* try to find one with the name first. */
6121 ComObjPtr<StorageController> ctrl;
6122
6123 rc = i_getStorageControllerByName(aName, ctrl, false /* aSetError */);
6124 if (SUCCEEDED(rc))
6125 return setError(VBOX_E_OBJECT_IN_USE,
6126 tr("Storage controller named '%s' already exists"),
6127 aName.c_str());
6128
6129 ctrl.createObject();
6130
6131 /* get a new instance number for the storage controller */
6132 ULONG ulInstance = 0;
6133 bool fBootable = true;
6134 for (StorageControllerList::const_iterator
6135 it = mStorageControllers->begin();
6136 it != mStorageControllers->end();
6137 ++it)
6138 {
6139 if ((*it)->i_getStorageBus() == aConnectionType)
6140 {
6141 ULONG ulCurInst = (*it)->i_getInstance();
6142
6143 if (ulCurInst >= ulInstance)
6144 ulInstance = ulCurInst + 1;
6145
6146 /* Only one controller of each type can be marked as bootable. */
6147 if ((*it)->i_getBootable())
6148 fBootable = false;
6149 }
6150 }
6151
6152 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
6153 if (FAILED(rc)) return rc;
6154
6155 i_setModified(IsModified_Storage);
6156 mStorageControllers.backup();
6157 mStorageControllers->push_back(ctrl);
6158
6159 ctrl.queryInterfaceTo(aController.asOutParam());
6160
6161 /* inform the direct session if any */
6162 alock.release();
6163 i_onStorageControllerChange();
6164
6165 return S_OK;
6166}
6167
6168HRESULT Machine::getStorageControllerByName(const com::Utf8Str &aName,
6169 ComPtr<IStorageController> &aStorageController)
6170{
6171 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6172
6173 ComObjPtr<StorageController> ctrl;
6174
6175 HRESULT rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6176 if (SUCCEEDED(rc))
6177 ctrl.queryInterfaceTo(aStorageController.asOutParam());
6178
6179 return rc;
6180}
6181
6182HRESULT Machine::getStorageControllerByInstance(StorageBus_T aConnectionType,
6183 ULONG aInstance,
6184 ComPtr<IStorageController> &aStorageController)
6185{
6186 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6187
6188 for (StorageControllerList::const_iterator
6189 it = mStorageControllers->begin();
6190 it != mStorageControllers->end();
6191 ++it)
6192 {
6193 if ( (*it)->i_getStorageBus() == aConnectionType
6194 && (*it)->i_getInstance() == aInstance)
6195 {
6196 (*it).queryInterfaceTo(aStorageController.asOutParam());
6197 return S_OK;
6198 }
6199 }
6200
6201 return setError(VBOX_E_OBJECT_NOT_FOUND,
6202 tr("Could not find a storage controller with instance number '%lu'"),
6203 aInstance);
6204}
6205
6206HRESULT Machine::setStorageControllerBootable(const com::Utf8Str &aName, BOOL aBootable)
6207{
6208 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6209
6210 HRESULT rc = i_checkStateDependency(MutableStateDep);
6211 if (FAILED(rc)) return rc;
6212
6213 ComObjPtr<StorageController> ctrl;
6214
6215 rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6216 if (SUCCEEDED(rc))
6217 {
6218 /* Ensure that only one controller of each type is marked as bootable. */
6219 if (aBootable == TRUE)
6220 {
6221 for (StorageControllerList::const_iterator
6222 it = mStorageControllers->begin();
6223 it != mStorageControllers->end();
6224 ++it)
6225 {
6226 ComObjPtr<StorageController> aCtrl = (*it);
6227
6228 if ( (aCtrl->i_getName() != aName)
6229 && aCtrl->i_getBootable() == TRUE
6230 && aCtrl->i_getStorageBus() == ctrl->i_getStorageBus()
6231 && aCtrl->i_getControllerType() == ctrl->i_getControllerType())
6232 {
6233 aCtrl->i_setBootable(FALSE);
6234 break;
6235 }
6236 }
6237 }
6238
6239 if (SUCCEEDED(rc))
6240 {
6241 ctrl->i_setBootable(aBootable);
6242 i_setModified(IsModified_Storage);
6243 }
6244 }
6245
6246 if (SUCCEEDED(rc))
6247 {
6248 /* inform the direct session if any */
6249 alock.release();
6250 i_onStorageControllerChange();
6251 }
6252
6253 return rc;
6254}
6255
6256HRESULT Machine::removeStorageController(const com::Utf8Str &aName)
6257{
6258 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6259
6260 HRESULT rc = i_checkStateDependency(MutableStateDep);
6261 if (FAILED(rc)) return rc;
6262
6263 ComObjPtr<StorageController> ctrl;
6264 rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6265 if (FAILED(rc)) return rc;
6266
6267 {
6268 /* find all attached devices to the appropriate storage controller and detach them all */
6269 // make a temporary list because detachDevice invalidates iterators into
6270 // mMediumAttachments
6271 MediumAttachmentList llAttachments2 = *mMediumAttachments.data();
6272
6273 for (MediumAttachmentList::const_iterator
6274 it = llAttachments2.begin();
6275 it != llAttachments2.end();
6276 ++it)
6277 {
6278 MediumAttachment *pAttachTemp = *it;
6279
6280 AutoCaller localAutoCaller(pAttachTemp);
6281 if (FAILED(localAutoCaller.rc())) return localAutoCaller.rc();
6282
6283 AutoReadLock local_alock(pAttachTemp COMMA_LOCKVAL_SRC_POS);
6284
6285 if (pAttachTemp->i_getControllerName() == aName)
6286 {
6287 rc = i_detachDevice(pAttachTemp, alock, NULL);
6288 if (FAILED(rc)) return rc;
6289 }
6290 }
6291 }
6292
6293 /* We can remove it now. */
6294 i_setModified(IsModified_Storage);
6295 mStorageControllers.backup();
6296
6297 ctrl->i_unshare();
6298
6299 mStorageControllers->remove(ctrl);
6300
6301 /* inform the direct session if any */
6302 alock.release();
6303 i_onStorageControllerChange();
6304
6305 return S_OK;
6306}
6307
6308HRESULT Machine::addUSBController(const com::Utf8Str &aName, USBControllerType_T aType,
6309 ComPtr<IUSBController> &aController)
6310{
6311 if ( (aType <= USBControllerType_Null)
6312 || (aType >= USBControllerType_Last))
6313 return setError(E_INVALIDARG,
6314 tr("Invalid USB controller type: %d"),
6315 aType);
6316
6317 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6318
6319 HRESULT rc = i_checkStateDependency(MutableStateDep);
6320 if (FAILED(rc)) return rc;
6321
6322 /* try to find one with the same type first. */
6323 ComObjPtr<USBController> ctrl;
6324
6325 rc = i_getUSBControllerByName(aName, ctrl, false /* aSetError */);
6326 if (SUCCEEDED(rc))
6327 return setError(VBOX_E_OBJECT_IN_USE,
6328 tr("USB controller named '%s' already exists"),
6329 aName.c_str());
6330
6331 /* Check that we don't exceed the maximum number of USB controllers for the given type. */
6332 ULONG maxInstances;
6333 rc = mParent->i_getSystemProperties()->GetMaxInstancesOfUSBControllerType(mHWData->mChipsetType, aType, &maxInstances);
6334 if (FAILED(rc))
6335 return rc;
6336
6337 ULONG cInstances = i_getUSBControllerCountByType(aType);
6338 if (cInstances >= maxInstances)
6339 return setError(E_INVALIDARG,
6340 tr("Too many USB controllers of this type"));
6341
6342 ctrl.createObject();
6343
6344 rc = ctrl->init(this, aName, aType);
6345 if (FAILED(rc)) return rc;
6346
6347 i_setModified(IsModified_USB);
6348 mUSBControllers.backup();
6349 mUSBControllers->push_back(ctrl);
6350
6351 ctrl.queryInterfaceTo(aController.asOutParam());
6352
6353 /* inform the direct session if any */
6354 alock.release();
6355 i_onUSBControllerChange();
6356
6357 return S_OK;
6358}
6359
6360HRESULT Machine::getUSBControllerByName(const com::Utf8Str &aName, ComPtr<IUSBController> &aController)
6361{
6362 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6363
6364 ComObjPtr<USBController> ctrl;
6365
6366 HRESULT rc = i_getUSBControllerByName(aName, ctrl, true /* aSetError */);
6367 if (SUCCEEDED(rc))
6368 ctrl.queryInterfaceTo(aController.asOutParam());
6369
6370 return rc;
6371}
6372
6373HRESULT Machine::getUSBControllerCountByType(USBControllerType_T aType,
6374 ULONG *aControllers)
6375{
6376 if ( (aType <= USBControllerType_Null)
6377 || (aType >= USBControllerType_Last))
6378 return setError(E_INVALIDARG,
6379 tr("Invalid USB controller type: %d"),
6380 aType);
6381
6382 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6383
6384 ComObjPtr<USBController> ctrl;
6385
6386 *aControllers = i_getUSBControllerCountByType(aType);
6387
6388 return S_OK;
6389}
6390
6391HRESULT Machine::removeUSBController(const com::Utf8Str &aName)
6392{
6393
6394 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6395
6396 HRESULT rc = i_checkStateDependency(MutableStateDep);
6397 if (FAILED(rc)) return rc;
6398
6399 ComObjPtr<USBController> ctrl;
6400 rc = i_getUSBControllerByName(aName, ctrl, true /* aSetError */);
6401 if (FAILED(rc)) return rc;
6402
6403 i_setModified(IsModified_USB);
6404 mUSBControllers.backup();
6405
6406 ctrl->i_unshare();
6407
6408 mUSBControllers->remove(ctrl);
6409
6410 /* inform the direct session if any */
6411 alock.release();
6412 i_onUSBControllerChange();
6413
6414 return S_OK;
6415}
6416
6417HRESULT Machine::querySavedGuestScreenInfo(ULONG aScreenId,
6418 ULONG *aOriginX,
6419 ULONG *aOriginY,
6420 ULONG *aWidth,
6421 ULONG *aHeight,
6422 BOOL *aEnabled)
6423{
6424 uint32_t u32OriginX= 0;
6425 uint32_t u32OriginY= 0;
6426 uint32_t u32Width = 0;
6427 uint32_t u32Height = 0;
6428 uint16_t u16Flags = 0;
6429
6430 int vrc = readSavedGuestScreenInfo(mSSData->strStateFilePath, aScreenId,
6431 &u32OriginX, &u32OriginY, &u32Width, &u32Height, &u16Flags);
6432 if (RT_FAILURE(vrc))
6433 {
6434#ifdef RT_OS_WINDOWS
6435 /* HACK: GUI sets *pfEnabled to 'true' and expects it to stay so if the API fails.
6436 * This works with XPCOM. But Windows COM sets all output parameters to zero.
6437 * So just assign fEnable to TRUE again.
6438 * The right fix would be to change GUI API wrappers to make sure that parameters
6439 * are changed only if API succeeds.
6440 */
6441 *aEnabled = TRUE;
6442#endif
6443 return setError(VBOX_E_IPRT_ERROR,
6444 tr("Saved guest size is not available (%Rrc)"),
6445 vrc);
6446 }
6447
6448 *aOriginX = u32OriginX;
6449 *aOriginY = u32OriginY;
6450 *aWidth = u32Width;
6451 *aHeight = u32Height;
6452 *aEnabled = (u16Flags & VBVA_SCREEN_F_DISABLED) == 0;
6453
6454 return S_OK;
6455}
6456
6457HRESULT Machine::readSavedThumbnailToArray(ULONG aScreenId, BitmapFormat_T aBitmapFormat,
6458 ULONG *aWidth, ULONG *aHeight, std::vector<BYTE> &aData)
6459{
6460 if (aScreenId != 0)
6461 return E_NOTIMPL;
6462
6463 if ( aBitmapFormat != BitmapFormat_BGR0
6464 && aBitmapFormat != BitmapFormat_BGRA
6465 && aBitmapFormat != BitmapFormat_RGBA
6466 && aBitmapFormat != BitmapFormat_PNG)
6467 return setError(E_NOTIMPL,
6468 tr("Unsupported saved thumbnail format 0x%08X"), aBitmapFormat);
6469
6470 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6471
6472 uint8_t *pu8Data = NULL;
6473 uint32_t cbData = 0;
6474 uint32_t u32Width = 0;
6475 uint32_t u32Height = 0;
6476
6477 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6478
6479 if (RT_FAILURE(vrc))
6480 return setError(VBOX_E_IPRT_ERROR,
6481 tr("Saved thumbnail data is not available (%Rrc)"),
6482 vrc);
6483
6484 HRESULT hr = S_OK;
6485
6486 *aWidth = u32Width;
6487 *aHeight = u32Height;
6488
6489 if (cbData > 0)
6490 {
6491 /* Convert pixels to the format expected by the API caller. */
6492 if (aBitmapFormat == BitmapFormat_BGR0)
6493 {
6494 /* [0] B, [1] G, [2] R, [3] 0. */
6495 aData.resize(cbData);
6496 memcpy(&aData.front(), pu8Data, cbData);
6497 }
6498 else if (aBitmapFormat == BitmapFormat_BGRA)
6499 {
6500 /* [0] B, [1] G, [2] R, [3] A. */
6501 aData.resize(cbData);
6502 for (uint32_t i = 0; i < cbData; i += 4)
6503 {
6504 aData[i] = pu8Data[i];
6505 aData[i + 1] = pu8Data[i + 1];
6506 aData[i + 2] = pu8Data[i + 2];
6507 aData[i + 3] = 0xff;
6508 }
6509 }
6510 else if (aBitmapFormat == BitmapFormat_RGBA)
6511 {
6512 /* [0] R, [1] G, [2] B, [3] A. */
6513 aData.resize(cbData);
6514 for (uint32_t i = 0; i < cbData; i += 4)
6515 {
6516 aData[i] = pu8Data[i + 2];
6517 aData[i + 1] = pu8Data[i + 1];
6518 aData[i + 2] = pu8Data[i];
6519 aData[i + 3] = 0xff;
6520 }
6521 }
6522 else if (aBitmapFormat == BitmapFormat_PNG)
6523 {
6524 uint8_t *pu8PNG = NULL;
6525 uint32_t cbPNG = 0;
6526 uint32_t cxPNG = 0;
6527 uint32_t cyPNG = 0;
6528
6529 vrc = DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
6530
6531 if (RT_SUCCESS(vrc))
6532 {
6533 aData.resize(cbPNG);
6534 if (cbPNG)
6535 memcpy(&aData.front(), pu8PNG, cbPNG);
6536 }
6537 else
6538 hr = setError(VBOX_E_IPRT_ERROR,
6539 tr("Could not convert saved thumbnail to PNG (%Rrc)"),
6540 vrc);
6541
6542 RTMemFree(pu8PNG);
6543 }
6544 }
6545
6546 freeSavedDisplayScreenshot(pu8Data);
6547
6548 return hr;
6549}
6550
6551HRESULT Machine::querySavedScreenshotInfo(ULONG aScreenId,
6552 ULONG *aWidth,
6553 ULONG *aHeight,
6554 std::vector<BitmapFormat_T> &aBitmapFormats)
6555{
6556 if (aScreenId != 0)
6557 return E_NOTIMPL;
6558
6559 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6560
6561 uint8_t *pu8Data = NULL;
6562 uint32_t cbData = 0;
6563 uint32_t u32Width = 0;
6564 uint32_t u32Height = 0;
6565
6566 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6567
6568 if (RT_FAILURE(vrc))
6569 return setError(VBOX_E_IPRT_ERROR,
6570 tr("Saved screenshot data is not available (%Rrc)"),
6571 vrc);
6572
6573 *aWidth = u32Width;
6574 *aHeight = u32Height;
6575 aBitmapFormats.resize(1);
6576 aBitmapFormats[0] = BitmapFormat_PNG;
6577
6578 freeSavedDisplayScreenshot(pu8Data);
6579
6580 return S_OK;
6581}
6582
6583HRESULT Machine::readSavedScreenshotToArray(ULONG aScreenId,
6584 BitmapFormat_T aBitmapFormat,
6585 ULONG *aWidth,
6586 ULONG *aHeight,
6587 std::vector<BYTE> &aData)
6588{
6589 if (aScreenId != 0)
6590 return E_NOTIMPL;
6591
6592 if (aBitmapFormat != BitmapFormat_PNG)
6593 return E_NOTIMPL;
6594
6595 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6596
6597 uint8_t *pu8Data = NULL;
6598 uint32_t cbData = 0;
6599 uint32_t u32Width = 0;
6600 uint32_t u32Height = 0;
6601
6602 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6603
6604 if (RT_FAILURE(vrc))
6605 return setError(VBOX_E_IPRT_ERROR,
6606 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
6607 vrc);
6608
6609 *aWidth = u32Width;
6610 *aHeight = u32Height;
6611
6612 aData.resize(cbData);
6613 if (cbData)
6614 memcpy(&aData.front(), pu8Data, cbData);
6615
6616 freeSavedDisplayScreenshot(pu8Data);
6617
6618 return S_OK;
6619}
6620
6621HRESULT Machine::hotPlugCPU(ULONG aCpu)
6622{
6623 HRESULT rc = S_OK;
6624 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6625
6626 if (!mHWData->mCPUHotPlugEnabled)
6627 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6628
6629 if (aCpu >= mHWData->mCPUCount)
6630 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
6631
6632 if (mHWData->mCPUAttached[aCpu])
6633 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
6634
6635 alock.release();
6636 rc = i_onCPUChange(aCpu, false);
6637 alock.acquire();
6638 if (FAILED(rc)) return rc;
6639
6640 i_setModified(IsModified_MachineData);
6641 mHWData.backup();
6642 mHWData->mCPUAttached[aCpu] = true;
6643
6644 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
6645 if (Global::IsOnline(mData->mMachineState))
6646 i_saveSettings(NULL);
6647
6648 return S_OK;
6649}
6650
6651HRESULT Machine::hotUnplugCPU(ULONG aCpu)
6652{
6653 HRESULT rc = S_OK;
6654
6655 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6656
6657 if (!mHWData->mCPUHotPlugEnabled)
6658 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6659
6660 if (aCpu >= SchemaDefs::MaxCPUCount)
6661 return setError(E_INVALIDARG,
6662 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
6663 SchemaDefs::MaxCPUCount);
6664
6665 if (!mHWData->mCPUAttached[aCpu])
6666 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
6667
6668 /* CPU 0 can't be detached */
6669 if (aCpu == 0)
6670 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
6671
6672 alock.release();
6673 rc = i_onCPUChange(aCpu, true);
6674 alock.acquire();
6675 if (FAILED(rc)) return rc;
6676
6677 i_setModified(IsModified_MachineData);
6678 mHWData.backup();
6679 mHWData->mCPUAttached[aCpu] = false;
6680
6681 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
6682 if (Global::IsOnline(mData->mMachineState))
6683 i_saveSettings(NULL);
6684
6685 return S_OK;
6686}
6687
6688HRESULT Machine::getCPUStatus(ULONG aCpu, BOOL *aAttached)
6689{
6690 *aAttached = false;
6691
6692 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6693
6694 /* If hotplug is enabled the CPU is always enabled. */
6695 if (!mHWData->mCPUHotPlugEnabled)
6696 {
6697 if (aCpu < mHWData->mCPUCount)
6698 *aAttached = true;
6699 }
6700 else
6701 {
6702 if (aCpu < SchemaDefs::MaxCPUCount)
6703 *aAttached = mHWData->mCPUAttached[aCpu];
6704 }
6705
6706 return S_OK;
6707}
6708
6709HRESULT Machine::queryLogFilename(ULONG aIdx, com::Utf8Str &aFilename)
6710{
6711 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6712
6713 Utf8Str log = i_getLogFilename(aIdx);
6714 if (!RTFileExists(log.c_str()))
6715 log.setNull();
6716 aFilename = log;
6717
6718 return S_OK;
6719}
6720
6721HRESULT Machine::readLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, std::vector<BYTE> &aData)
6722{
6723 if (aSize < 0)
6724 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
6725
6726 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6727
6728 HRESULT rc = S_OK;
6729 Utf8Str log = i_getLogFilename(aIdx);
6730
6731 /* do not unnecessarily hold the lock while doing something which does
6732 * not need the lock and potentially takes a long time. */
6733 alock.release();
6734
6735 /* Limit the chunk size to 32K for now, as that gives better performance
6736 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
6737 * One byte expands to approx. 25 bytes of breathtaking XML. */
6738 size_t cbData = (size_t)RT_MIN(aSize, 32768);
6739 aData.resize(cbData);
6740
6741 RTFILE LogFile;
6742 int vrc = RTFileOpen(&LogFile, log.c_str(),
6743 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
6744 if (RT_SUCCESS(vrc))
6745 {
6746 vrc = RTFileReadAt(LogFile, aOffset, cbData? &aData.front(): NULL, cbData, &cbData);
6747 if (RT_SUCCESS(vrc))
6748 aData.resize(cbData);
6749 else
6750 rc = setError(VBOX_E_IPRT_ERROR,
6751 tr("Could not read log file '%s' (%Rrc)"),
6752 log.c_str(), vrc);
6753 RTFileClose(LogFile);
6754 }
6755 else
6756 rc = setError(VBOX_E_IPRT_ERROR,
6757 tr("Could not open log file '%s' (%Rrc)"),
6758 log.c_str(), vrc);
6759
6760 if (FAILED(rc))
6761 aData.resize(0);
6762
6763 return rc;
6764}
6765
6766
6767/**
6768 * Currently this method doesn't attach device to the running VM,
6769 * just makes sure it's plugged on next VM start.
6770 */
6771HRESULT Machine::attachHostPCIDevice(LONG aHostAddress, LONG aDesiredGuestAddress, BOOL /* aTryToUnbind */)
6772{
6773 // lock scope
6774 {
6775 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6776
6777 HRESULT rc = i_checkStateDependency(MutableStateDep);
6778 if (FAILED(rc)) return rc;
6779
6780 ChipsetType_T aChipset = ChipsetType_PIIX3;
6781 COMGETTER(ChipsetType)(&aChipset);
6782
6783 if (aChipset != ChipsetType_ICH9)
6784 {
6785 return setError(E_INVALIDARG,
6786 tr("Host PCI attachment only supported with ICH9 chipset"));
6787 }
6788
6789 // check if device with this host PCI address already attached
6790 for (HWData::PCIDeviceAssignmentList::const_iterator
6791 it = mHWData->mPCIDeviceAssignments.begin();
6792 it != mHWData->mPCIDeviceAssignments.end();
6793 ++it)
6794 {
6795 LONG iHostAddress = -1;
6796 ComPtr<PCIDeviceAttachment> pAttach;
6797 pAttach = *it;
6798 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6799 if (iHostAddress == aHostAddress)
6800 return setError(E_INVALIDARG,
6801 tr("Device with host PCI address already attached to this VM"));
6802 }
6803
6804 ComObjPtr<PCIDeviceAttachment> pda;
6805 char name[32];
6806
6807 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (aHostAddress>>8) & 0xff,
6808 (aHostAddress & 0xf8) >> 3, aHostAddress & 7);
6809 pda.createObject();
6810 pda->init(this, name, aHostAddress, aDesiredGuestAddress, TRUE);
6811 i_setModified(IsModified_MachineData);
6812 mHWData.backup();
6813 mHWData->mPCIDeviceAssignments.push_back(pda);
6814 }
6815
6816 return S_OK;
6817}
6818
6819/**
6820 * Currently this method doesn't detach device from the running VM,
6821 * just makes sure it's not plugged on next VM start.
6822 */
6823HRESULT Machine::detachHostPCIDevice(LONG aHostAddress)
6824{
6825 ComObjPtr<PCIDeviceAttachment> pAttach;
6826 bool fRemoved = false;
6827 HRESULT rc;
6828
6829 // lock scope
6830 {
6831 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6832
6833 rc = i_checkStateDependency(MutableStateDep);
6834 if (FAILED(rc)) return rc;
6835
6836 for (HWData::PCIDeviceAssignmentList::const_iterator
6837 it = mHWData->mPCIDeviceAssignments.begin();
6838 it != mHWData->mPCIDeviceAssignments.end();
6839 ++it)
6840 {
6841 LONG iHostAddress = -1;
6842 pAttach = *it;
6843 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6844 if (iHostAddress != -1 && iHostAddress == aHostAddress)
6845 {
6846 i_setModified(IsModified_MachineData);
6847 mHWData.backup();
6848 mHWData->mPCIDeviceAssignments.remove(pAttach);
6849 fRemoved = true;
6850 break;
6851 }
6852 }
6853 }
6854
6855
6856 /* Fire event outside of the lock */
6857 if (fRemoved)
6858 {
6859 Assert(!pAttach.isNull());
6860 ComPtr<IEventSource> es;
6861 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
6862 Assert(SUCCEEDED(rc));
6863 Bstr mid;
6864 rc = this->COMGETTER(Id)(mid.asOutParam());
6865 Assert(SUCCEEDED(rc));
6866 fireHostPCIDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
6867 }
6868
6869 return fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
6870 tr("No host PCI device %08x attached"),
6871 aHostAddress
6872 );
6873}
6874
6875HRESULT Machine::getPCIDeviceAssignments(std::vector<ComPtr<IPCIDeviceAttachment> > &aPCIDeviceAssignments)
6876{
6877 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6878
6879 aPCIDeviceAssignments.resize(mHWData->mPCIDeviceAssignments.size());
6880 size_t i = 0;
6881 for (std::list<ComObjPtr<PCIDeviceAttachment> >::const_iterator
6882 it = mHWData->mPCIDeviceAssignments.begin();
6883 it != mHWData->mPCIDeviceAssignments.end();
6884 ++it, ++i)
6885 (*it).queryInterfaceTo(aPCIDeviceAssignments[i].asOutParam());
6886
6887 return S_OK;
6888}
6889
6890HRESULT Machine::getBandwidthControl(ComPtr<IBandwidthControl> &aBandwidthControl)
6891{
6892 mBandwidthControl.queryInterfaceTo(aBandwidthControl.asOutParam());
6893
6894 return S_OK;
6895}
6896
6897HRESULT Machine::getTracingEnabled(BOOL *aTracingEnabled)
6898{
6899 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6900
6901 *aTracingEnabled = mHWData->mDebugging.fTracingEnabled;
6902
6903 return S_OK;
6904}
6905
6906HRESULT Machine::setTracingEnabled(BOOL aTracingEnabled)
6907{
6908 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6909 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6910 if (SUCCEEDED(hrc))
6911 {
6912 hrc = mHWData.backupEx();
6913 if (SUCCEEDED(hrc))
6914 {
6915 i_setModified(IsModified_MachineData);
6916 mHWData->mDebugging.fTracingEnabled = aTracingEnabled != FALSE;
6917 }
6918 }
6919 return hrc;
6920}
6921
6922HRESULT Machine::getTracingConfig(com::Utf8Str &aTracingConfig)
6923{
6924 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6925 aTracingConfig = mHWData->mDebugging.strTracingConfig;
6926 return S_OK;
6927}
6928
6929HRESULT Machine::setTracingConfig(const com::Utf8Str &aTracingConfig)
6930{
6931 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6932 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6933 if (SUCCEEDED(hrc))
6934 {
6935 hrc = mHWData.backupEx();
6936 if (SUCCEEDED(hrc))
6937 {
6938 mHWData->mDebugging.strTracingConfig = aTracingConfig;
6939 if (SUCCEEDED(hrc))
6940 i_setModified(IsModified_MachineData);
6941 }
6942 }
6943 return hrc;
6944}
6945
6946HRESULT Machine::getAllowTracingToAccessVM(BOOL *aAllowTracingToAccessVM)
6947{
6948 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6949
6950 *aAllowTracingToAccessVM = mHWData->mDebugging.fAllowTracingToAccessVM;
6951
6952 return S_OK;
6953}
6954
6955HRESULT Machine::setAllowTracingToAccessVM(BOOL aAllowTracingToAccessVM)
6956{
6957 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6958 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6959 if (SUCCEEDED(hrc))
6960 {
6961 hrc = mHWData.backupEx();
6962 if (SUCCEEDED(hrc))
6963 {
6964 i_setModified(IsModified_MachineData);
6965 mHWData->mDebugging.fAllowTracingToAccessVM = aAllowTracingToAccessVM != FALSE;
6966 }
6967 }
6968 return hrc;
6969}
6970
6971HRESULT Machine::getAutostartEnabled(BOOL *aAutostartEnabled)
6972{
6973 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6974
6975 *aAutostartEnabled = mHWData->mAutostart.fAutostartEnabled;
6976
6977 return S_OK;
6978}
6979
6980HRESULT Machine::setAutostartEnabled(BOOL aAutostartEnabled)
6981{
6982 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6983
6984 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
6985 if ( SUCCEEDED(hrc)
6986 && mHWData->mAutostart.fAutostartEnabled != !!aAutostartEnabled)
6987 {
6988 AutostartDb *autostartDb = mParent->i_getAutostartDb();
6989 int vrc;
6990
6991 if (aAutostartEnabled)
6992 vrc = autostartDb->addAutostartVM(mUserData->s.strName.c_str());
6993 else
6994 vrc = autostartDb->removeAutostartVM(mUserData->s.strName.c_str());
6995
6996 if (RT_SUCCESS(vrc))
6997 {
6998 hrc = mHWData.backupEx();
6999 if (SUCCEEDED(hrc))
7000 {
7001 i_setModified(IsModified_MachineData);
7002 mHWData->mAutostart.fAutostartEnabled = aAutostartEnabled != FALSE;
7003 }
7004 }
7005 else if (vrc == VERR_NOT_SUPPORTED)
7006 hrc = setError(VBOX_E_NOT_SUPPORTED,
7007 tr("The VM autostart feature is not supported on this platform"));
7008 else if (vrc == VERR_PATH_NOT_FOUND)
7009 hrc = setError(E_FAIL,
7010 tr("The path to the autostart database is not set"));
7011 else
7012 hrc = setError(E_UNEXPECTED,
7013 tr("%s machine '%s' to the autostart database failed with %Rrc"),
7014 aAutostartEnabled ? "Adding" : "Removing",
7015 mUserData->s.strName.c_str(), vrc);
7016 }
7017 return hrc;
7018}
7019
7020HRESULT Machine::getAutostartDelay(ULONG *aAutostartDelay)
7021{
7022 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7023
7024 *aAutostartDelay = mHWData->mAutostart.uAutostartDelay;
7025
7026 return S_OK;
7027}
7028
7029HRESULT Machine::setAutostartDelay(ULONG aAutostartDelay)
7030{
7031 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7032 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7033 if (SUCCEEDED(hrc))
7034 {
7035 hrc = mHWData.backupEx();
7036 if (SUCCEEDED(hrc))
7037 {
7038 i_setModified(IsModified_MachineData);
7039 mHWData->mAutostart.uAutostartDelay = aAutostartDelay;
7040 }
7041 }
7042 return hrc;
7043}
7044
7045HRESULT Machine::getAutostopType(AutostopType_T *aAutostopType)
7046{
7047 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7048
7049 *aAutostopType = mHWData->mAutostart.enmAutostopType;
7050
7051 return S_OK;
7052}
7053
7054HRESULT Machine::setAutostopType(AutostopType_T aAutostopType)
7055{
7056 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7057 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7058 if ( SUCCEEDED(hrc)
7059 && mHWData->mAutostart.enmAutostopType != aAutostopType)
7060 {
7061 AutostartDb *autostartDb = mParent->i_getAutostartDb();
7062 int vrc;
7063
7064 if (aAutostopType != AutostopType_Disabled)
7065 vrc = autostartDb->addAutostopVM(mUserData->s.strName.c_str());
7066 else
7067 vrc = autostartDb->removeAutostopVM(mUserData->s.strName.c_str());
7068
7069 if (RT_SUCCESS(vrc))
7070 {
7071 hrc = mHWData.backupEx();
7072 if (SUCCEEDED(hrc))
7073 {
7074 i_setModified(IsModified_MachineData);
7075 mHWData->mAutostart.enmAutostopType = aAutostopType;
7076 }
7077 }
7078 else if (vrc == VERR_NOT_SUPPORTED)
7079 hrc = setError(VBOX_E_NOT_SUPPORTED,
7080 tr("The VM autostop feature is not supported on this platform"));
7081 else if (vrc == VERR_PATH_NOT_FOUND)
7082 hrc = setError(E_FAIL,
7083 tr("The path to the autostart database is not set"));
7084 else
7085 hrc = setError(E_UNEXPECTED,
7086 tr("%s machine '%s' to the autostop database failed with %Rrc"),
7087 aAutostopType != AutostopType_Disabled ? "Adding" : "Removing",
7088 mUserData->s.strName.c_str(), vrc);
7089 }
7090 return hrc;
7091}
7092
7093HRESULT Machine::getDefaultFrontend(com::Utf8Str &aDefaultFrontend)
7094{
7095 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7096
7097 aDefaultFrontend = mHWData->mDefaultFrontend;
7098
7099 return S_OK;
7100}
7101
7102HRESULT Machine::setDefaultFrontend(const com::Utf8Str &aDefaultFrontend)
7103{
7104 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7105 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
7106 if (SUCCEEDED(hrc))
7107 {
7108 hrc = mHWData.backupEx();
7109 if (SUCCEEDED(hrc))
7110 {
7111 i_setModified(IsModified_MachineData);
7112 mHWData->mDefaultFrontend = aDefaultFrontend;
7113 }
7114 }
7115 return hrc;
7116}
7117
7118HRESULT Machine::getIcon(std::vector<BYTE> &aIcon)
7119{
7120 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7121 size_t cbIcon = mUserData->s.ovIcon.size();
7122 aIcon.resize(cbIcon);
7123 if (cbIcon)
7124 memcpy(&aIcon.front(), &mUserData->s.ovIcon[0], cbIcon);
7125 return S_OK;
7126}
7127
7128HRESULT Machine::setIcon(const std::vector<BYTE> &aIcon)
7129{
7130 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7131 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
7132 if (SUCCEEDED(hrc))
7133 {
7134 i_setModified(IsModified_MachineData);
7135 mUserData.backup();
7136 size_t cbIcon = aIcon.size();
7137 mUserData->s.ovIcon.resize(cbIcon);
7138 if (cbIcon)
7139 memcpy(&mUserData->s.ovIcon[0], &aIcon.front(), cbIcon);
7140 }
7141 return hrc;
7142}
7143
7144HRESULT Machine::getUSBProxyAvailable(BOOL *aUSBProxyAvailable)
7145{
7146#ifdef VBOX_WITH_USB
7147 *aUSBProxyAvailable = true;
7148#else
7149 *aUSBProxyAvailable = false;
7150#endif
7151 return S_OK;
7152}
7153
7154HRESULT Machine::getVMProcessPriority(com::Utf8Str &aVMProcessPriority)
7155{
7156 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7157
7158 aVMProcessPriority = mUserData->s.strVMPriority;
7159
7160 return S_OK;
7161}
7162
7163HRESULT Machine::setVMProcessPriority(const com::Utf8Str &aVMProcessPriority)
7164{
7165 RT_NOREF(aVMProcessPriority);
7166 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7167 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7168 if (SUCCEEDED(hrc))
7169 {
7170 /** @todo r=klaus: currently this is marked as not implemented, as
7171 * the code for setting the priority of the process is not there
7172 * (neither when starting the VM nor at runtime). */
7173 ReturnComNotImplemented();
7174#if 0
7175 hrc = mUserData.backupEx();
7176 if (SUCCEEDED(hrc))
7177 {
7178 i_setModified(IsModified_MachineData);
7179 mUserData->s.strVMPriority = aVMProcessPriority;
7180 }
7181#endif
7182 }
7183 return hrc;
7184}
7185
7186HRESULT Machine::cloneTo(const ComPtr<IMachine> &aTarget, CloneMode_T aMode, const std::vector<CloneOptions_T> &aOptions,
7187 ComPtr<IProgress> &aProgress)
7188{
7189 ComObjPtr<Progress> pP;
7190 Progress *ppP = pP;
7191 IProgress *iP = static_cast<IProgress *>(ppP);
7192 IProgress **pProgress = &iP;
7193
7194 IMachine *pTarget = aTarget;
7195
7196 /* Convert the options. */
7197 RTCList<CloneOptions_T> optList;
7198 if (aOptions.size())
7199 for (size_t i = 0; i < aOptions.size(); ++i)
7200 optList.append(aOptions[i]);
7201
7202 if (optList.contains(CloneOptions_Link))
7203 {
7204 if (!i_isSnapshotMachine())
7205 return setError(E_INVALIDARG,
7206 tr("Linked clone can only be created from a snapshot"));
7207 if (aMode != CloneMode_MachineState)
7208 return setError(E_INVALIDARG,
7209 tr("Linked clone can only be created for a single machine state"));
7210 }
7211 AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_INVALIDARG);
7212
7213 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), aMode, optList);
7214
7215 HRESULT rc = pWorker->start(pProgress);
7216
7217 pP = static_cast<Progress *>(*pProgress);
7218 pP.queryInterfaceTo(aProgress.asOutParam());
7219
7220 return rc;
7221
7222}
7223
7224HRESULT Machine::saveState(ComPtr<IProgress> &aProgress)
7225{
7226 NOREF(aProgress);
7227 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7228
7229 // This check should always fail.
7230 HRESULT rc = i_checkStateDependency(MutableStateDep);
7231 if (FAILED(rc)) return rc;
7232
7233 AssertFailedReturn(E_NOTIMPL);
7234}
7235
7236HRESULT Machine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
7237{
7238 NOREF(aSavedStateFile);
7239 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7240
7241 // This check should always fail.
7242 HRESULT rc = i_checkStateDependency(MutableStateDep);
7243 if (FAILED(rc)) return rc;
7244
7245 AssertFailedReturn(E_NOTIMPL);
7246}
7247
7248HRESULT Machine::discardSavedState(BOOL aFRemoveFile)
7249{
7250 NOREF(aFRemoveFile);
7251 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7252
7253 // This check should always fail.
7254 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
7255 if (FAILED(rc)) return rc;
7256
7257 AssertFailedReturn(E_NOTIMPL);
7258}
7259
7260// public methods for internal purposes
7261/////////////////////////////////////////////////////////////////////////////
7262
7263/**
7264 * Adds the given IsModified_* flag to the dirty flags of the machine.
7265 * This must be called either during i_loadSettings or under the machine write lock.
7266 * @param fl Flag
7267 * @param fAllowStateModification If state modifications are allowed.
7268 */
7269void Machine::i_setModified(uint32_t fl, bool fAllowStateModification /* = true */)
7270{
7271 mData->flModifications |= fl;
7272 if (fAllowStateModification && i_isStateModificationAllowed())
7273 mData->mCurrentStateModified = true;
7274}
7275
7276/**
7277 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
7278 * care of the write locking.
7279 *
7280 * @param fModification The flag to add.
7281 * @param fAllowStateModification If state modifications are allowed.
7282 */
7283void Machine::i_setModifiedLock(uint32_t fModification, bool fAllowStateModification /* = true */)
7284{
7285 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7286 i_setModified(fModification, fAllowStateModification);
7287}
7288
7289/**
7290 * Saves the registry entry of this machine to the given configuration node.
7291 *
7292 * @param data Machine registry data.
7293 *
7294 * @note locks this object for reading.
7295 */
7296HRESULT Machine::i_saveRegistryEntry(settings::MachineRegistryEntry &data)
7297{
7298 AutoLimitedCaller autoCaller(this);
7299 AssertComRCReturnRC(autoCaller.rc());
7300
7301 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7302
7303 data.uuid = mData->mUuid;
7304 data.strSettingsFile = mData->m_strConfigFile;
7305
7306 return S_OK;
7307}
7308
7309/**
7310 * Calculates the absolute path of the given path taking the directory of the
7311 * machine settings file as the current directory.
7312 *
7313 * @param strPath Path to calculate the absolute path for.
7314 * @param aResult Where to put the result (used only on success, can be the
7315 * same Utf8Str instance as passed in @a aPath).
7316 * @return IPRT result.
7317 *
7318 * @note Locks this object for reading.
7319 */
7320int Machine::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
7321{
7322 AutoCaller autoCaller(this);
7323 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7324
7325 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7326
7327 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
7328
7329 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
7330
7331 strSettingsDir.stripFilename();
7332 char folder[RTPATH_MAX];
7333 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
7334 if (RT_SUCCESS(vrc))
7335 aResult = folder;
7336
7337 return vrc;
7338}
7339
7340/**
7341 * Copies strSource to strTarget, making it relative to the machine folder
7342 * if it is a subdirectory thereof, or simply copying it otherwise.
7343 *
7344 * @param strSource Path to evaluate and copy.
7345 * @param strTarget Buffer to receive target path.
7346 *
7347 * @note Locks this object for reading.
7348 */
7349void Machine::i_copyPathRelativeToMachine(const Utf8Str &strSource,
7350 Utf8Str &strTarget)
7351{
7352 AutoCaller autoCaller(this);
7353 AssertComRCReturn(autoCaller.rc(), (void)0);
7354
7355 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7356
7357 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
7358 // use strTarget as a temporary buffer to hold the machine settings dir
7359 strTarget = mData->m_strConfigFileFull;
7360 strTarget.stripFilename();
7361 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
7362 {
7363 // is relative: then append what's left
7364 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
7365 // for empty paths (only possible for subdirs) use "." to avoid
7366 // triggering default settings for not present config attributes.
7367 if (strTarget.isEmpty())
7368 strTarget = ".";
7369 }
7370 else
7371 // is not relative: then overwrite
7372 strTarget = strSource;
7373}
7374
7375/**
7376 * Returns the full path to the machine's log folder in the
7377 * \a aLogFolder argument.
7378 */
7379void Machine::i_getLogFolder(Utf8Str &aLogFolder)
7380{
7381 AutoCaller autoCaller(this);
7382 AssertComRCReturnVoid(autoCaller.rc());
7383
7384 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7385
7386 char szTmp[RTPATH_MAX];
7387 int vrc = RTEnvGetEx(RTENV_DEFAULT, "VBOX_USER_VMLOGDIR", szTmp, sizeof(szTmp), NULL);
7388 if (RT_SUCCESS(vrc))
7389 {
7390 if (szTmp[0] && !mUserData.isNull())
7391 {
7392 char szTmp2[RTPATH_MAX];
7393 vrc = RTPathAbs(szTmp, szTmp2, sizeof(szTmp2));
7394 if (RT_SUCCESS(vrc))
7395 aLogFolder = Utf8StrFmt("%s%c%s",
7396 szTmp2,
7397 RTPATH_DELIMITER,
7398 mUserData->s.strName.c_str()); // path/to/logfolder/vmname
7399 }
7400 else
7401 vrc = VERR_PATH_IS_RELATIVE;
7402 }
7403
7404 if (RT_FAILURE(vrc))
7405 {
7406 // fallback if VBOX_USER_LOGHOME is not set or invalid
7407 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7408 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
7409 aLogFolder.append(RTPATH_DELIMITER);
7410 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
7411 }
7412}
7413
7414/**
7415 * Returns the full path to the machine's log file for an given index.
7416 */
7417Utf8Str Machine::i_getLogFilename(ULONG idx)
7418{
7419 Utf8Str logFolder;
7420 getLogFolder(logFolder);
7421 Assert(logFolder.length());
7422
7423 Utf8Str log;
7424 if (idx == 0)
7425 log = Utf8StrFmt("%s%cVBox.log", logFolder.c_str(), RTPATH_DELIMITER);
7426#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7427 else if (idx == 1)
7428 log = Utf8StrFmt("%s%cVBoxHardening.log", logFolder.c_str(), RTPATH_DELIMITER);
7429 else
7430 log = Utf8StrFmt("%s%cVBox.log.%u", logFolder.c_str(), RTPATH_DELIMITER, idx - 1);
7431#else
7432 else
7433 log = Utf8StrFmt("%s%cVBox.log.%u", logFolder.c_str(), RTPATH_DELIMITER, idx);
7434#endif
7435 return log;
7436}
7437
7438/**
7439 * Returns the full path to the machine's hardened log file.
7440 */
7441Utf8Str Machine::i_getHardeningLogFilename(void)
7442{
7443 Utf8Str strFilename;
7444 getLogFolder(strFilename);
7445 Assert(strFilename.length());
7446 strFilename.append(RTPATH_SLASH_STR "VBoxHardening.log");
7447 return strFilename;
7448}
7449
7450
7451/**
7452 * Composes a unique saved state filename based on the current system time. The filename is
7453 * granular to the second so this will work so long as no more than one snapshot is taken on
7454 * a machine per second.
7455 *
7456 * Before version 4.1, we used this formula for saved state files:
7457 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
7458 * which no longer works because saved state files can now be shared between the saved state of the
7459 * "saved" machine and an online snapshot, and the following would cause problems:
7460 * 1) save machine
7461 * 2) create online snapshot from that machine state --> reusing saved state file
7462 * 3) save machine again --> filename would be reused, breaking the online snapshot
7463 *
7464 * So instead we now use a timestamp.
7465 *
7466 * @param strStateFilePath
7467 */
7468
7469void Machine::i_composeSavedStateFilename(Utf8Str &strStateFilePath)
7470{
7471 AutoCaller autoCaller(this);
7472 AssertComRCReturnVoid(autoCaller.rc());
7473
7474 {
7475 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7476 i_calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
7477 }
7478
7479 RTTIMESPEC ts;
7480 RTTimeNow(&ts);
7481 RTTIME time;
7482 RTTimeExplode(&time, &ts);
7483
7484 strStateFilePath += RTPATH_DELIMITER;
7485 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
7486 time.i32Year, time.u8Month, time.u8MonthDay,
7487 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
7488}
7489
7490/**
7491 * Returns the full path to the default video capture file.
7492 */
7493void Machine::i_getDefaultVideoCaptureFile(Utf8Str &strFile)
7494{
7495 AutoCaller autoCaller(this);
7496 AssertComRCReturnVoid(autoCaller.rc());
7497
7498 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7499
7500 strFile = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7501 strFile.stripSuffix(); // path/to/machinesfolder/vmname/vmname
7502 strFile.append(".webm"); // path/to/machinesfolder/vmname/vmname.webm
7503}
7504
7505/**
7506 * Returns whether at least one USB controller is present for the VM.
7507 */
7508bool Machine::i_isUSBControllerPresent()
7509{
7510 AutoCaller autoCaller(this);
7511 AssertComRCReturn(autoCaller.rc(), false);
7512
7513 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7514
7515 return (mUSBControllers->size() > 0);
7516}
7517
7518/**
7519 * @note Locks this object for writing, calls the client process
7520 * (inside the lock).
7521 */
7522HRESULT Machine::i_launchVMProcess(IInternalSessionControl *aControl,
7523 const Utf8Str &strFrontend,
7524 const Utf8Str &strEnvironment,
7525 ProgressProxy *aProgress)
7526{
7527 LogFlowThisFuncEnter();
7528
7529 AssertReturn(aControl, E_FAIL);
7530 AssertReturn(aProgress, E_FAIL);
7531 AssertReturn(!strFrontend.isEmpty(), E_FAIL);
7532
7533 AutoCaller autoCaller(this);
7534 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7535
7536 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7537
7538 if (!mData->mRegistered)
7539 return setError(E_UNEXPECTED,
7540 tr("The machine '%s' is not registered"),
7541 mUserData->s.strName.c_str());
7542
7543 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
7544
7545 /* The process started when launching a VM with separate UI/VM processes is always
7546 * the UI process, i.e. needs special handling as it won't claim the session. */
7547 bool fSeparate = strFrontend.endsWith("separate", Utf8Str::CaseInsensitive);
7548
7549 if (fSeparate)
7550 {
7551 if (mData->mSession.mState != SessionState_Unlocked && mData->mSession.mName != "headless")
7552 return setError(VBOX_E_INVALID_OBJECT_STATE,
7553 tr("The machine '%s' is in a state which is incompatible with launching a separate UI process"),
7554 mUserData->s.strName.c_str());
7555 }
7556 else
7557 {
7558 if ( mData->mSession.mState == SessionState_Locked
7559 || mData->mSession.mState == SessionState_Spawning
7560 || mData->mSession.mState == SessionState_Unlocking)
7561 return setError(VBOX_E_INVALID_OBJECT_STATE,
7562 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
7563 mUserData->s.strName.c_str());
7564
7565 /* may not be busy */
7566 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
7567 }
7568
7569 /* get the path to the executable */
7570 char szPath[RTPATH_MAX];
7571 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
7572 size_t cchBufLeft = strlen(szPath);
7573 szPath[cchBufLeft++] = RTPATH_DELIMITER;
7574 szPath[cchBufLeft] = 0;
7575 char *pszNamePart = szPath + cchBufLeft;
7576 cchBufLeft = sizeof(szPath) - cchBufLeft;
7577
7578 int vrc = VINF_SUCCESS;
7579 RTPROCESS pid = NIL_RTPROCESS;
7580
7581 RTENV env = RTENV_DEFAULT;
7582
7583 if (!strEnvironment.isEmpty())
7584 {
7585 char *newEnvStr = NULL;
7586
7587 do
7588 {
7589 /* clone the current environment */
7590 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
7591 AssertRCBreakStmt(vrc2, vrc = vrc2);
7592
7593 newEnvStr = RTStrDup(strEnvironment.c_str());
7594 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
7595
7596 /* put new variables to the environment
7597 * (ignore empty variable names here since RTEnv API
7598 * intentionally doesn't do that) */
7599 char *var = newEnvStr;
7600 for (char *p = newEnvStr; *p; ++p)
7601 {
7602 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
7603 {
7604 *p = '\0';
7605 if (*var)
7606 {
7607 char *val = strchr(var, '=');
7608 if (val)
7609 {
7610 *val++ = '\0';
7611 vrc2 = RTEnvSetEx(env, var, val);
7612 }
7613 else
7614 vrc2 = RTEnvUnsetEx(env, var);
7615 if (RT_FAILURE(vrc2))
7616 break;
7617 }
7618 var = p + 1;
7619 }
7620 }
7621 if (RT_SUCCESS(vrc2) && *var)
7622 vrc2 = RTEnvPutEx(env, var);
7623
7624 AssertRCBreakStmt(vrc2, vrc = vrc2);
7625 }
7626 while (0);
7627
7628 if (newEnvStr != NULL)
7629 RTStrFree(newEnvStr);
7630 }
7631
7632 /* Hardening logging */
7633#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7634 Utf8Str strSupHardeningLogArg("--sup-hardening-log=");
7635 {
7636 Utf8Str strHardeningLogFile = i_getHardeningLogFilename();
7637 int vrc2 = RTFileDelete(strHardeningLogFile.c_str());
7638 if (vrc2 == VERR_PATH_NOT_FOUND || vrc2 == VERR_FILE_NOT_FOUND)
7639 {
7640 Utf8Str strStartupLogDir = strHardeningLogFile;
7641 strStartupLogDir.stripFilename();
7642 RTDirCreateFullPath(strStartupLogDir.c_str(), 0755); /** @todo add a variant for creating the path to a
7643 file without stripping the file. */
7644 }
7645 strSupHardeningLogArg.append(strHardeningLogFile);
7646
7647 /* Remove legacy log filename to avoid confusion. */
7648 Utf8Str strOldStartupLogFile;
7649 getLogFolder(strOldStartupLogFile);
7650 strOldStartupLogFile.append(RTPATH_SLASH_STR "VBoxStartup.log");
7651 RTFileDelete(strOldStartupLogFile.c_str());
7652 }
7653 const char *pszSupHardeningLogArg = strSupHardeningLogArg.c_str();
7654#else
7655 const char *pszSupHardeningLogArg = NULL;
7656#endif
7657
7658 Utf8Str strCanonicalName;
7659
7660#ifdef VBOX_WITH_QTGUI
7661 if ( !strFrontend.compare("gui", Utf8Str::CaseInsensitive)
7662 || !strFrontend.compare("GUI/Qt", Utf8Str::CaseInsensitive)
7663 || !strFrontend.compare("separate", Utf8Str::CaseInsensitive)
7664 || !strFrontend.compare("gui/separate", Utf8Str::CaseInsensitive)
7665 || !strFrontend.compare("GUI/Qt/separate", Utf8Str::CaseInsensitive))
7666 {
7667 strCanonicalName = "GUI/Qt";
7668# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
7669 /* Modify the base path so that we don't need to use ".." below. */
7670 RTPathStripTrailingSlash(szPath);
7671 RTPathStripFilename(szPath);
7672 cchBufLeft = strlen(szPath);
7673 pszNamePart = szPath + cchBufLeft;
7674 cchBufLeft = sizeof(szPath) - cchBufLeft;
7675
7676# define OSX_APP_NAME "VirtualBoxVM"
7677# define OSX_APP_PATH_FMT "/Resources/%s.app/Contents/MacOS/VirtualBoxVM"
7678
7679 Utf8Str strAppOverride = i_getExtraData(Utf8Str("VBoxInternal2/VirtualBoxVMAppOverride"));
7680 if ( strAppOverride.contains(".")
7681 || strAppOverride.contains("/")
7682 || strAppOverride.contains("\\")
7683 || strAppOverride.contains(":"))
7684 strAppOverride.setNull();
7685 Utf8Str strAppPath;
7686 if (!strAppOverride.isEmpty())
7687 {
7688 strAppPath = Utf8StrFmt(OSX_APP_PATH_FMT, strAppOverride.c_str());
7689 Utf8Str strFullPath(szPath);
7690 strFullPath.append(strAppPath);
7691 /* there is a race, but people using this deserve the failure */
7692 if (!RTFileExists(strFullPath.c_str()))
7693 strAppOverride.setNull();
7694 }
7695 if (strAppOverride.isEmpty())
7696 strAppPath = Utf8StrFmt(OSX_APP_PATH_FMT, OSX_APP_NAME);
7697 AssertReturn(cchBufLeft > strAppPath.length(), E_UNEXPECTED);
7698 strcpy(pszNamePart, strAppPath.c_str());
7699# else
7700 static const char s_szVirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
7701 Assert(cchBufLeft >= sizeof(s_szVirtualBox_exe));
7702 strcpy(pszNamePart, s_szVirtualBox_exe);
7703# endif
7704
7705 Utf8Str idStr = mData->mUuid.toString();
7706 const char *apszArgs[] =
7707 {
7708 szPath,
7709 "--comment", mUserData->s.strName.c_str(),
7710 "--startvm", idStr.c_str(),
7711 "--no-startvm-errormsgbox",
7712 NULL, /* For "--separate". */
7713 NULL, /* For "--sup-startup-log". */
7714 NULL
7715 };
7716 unsigned iArg = 6;
7717 if (fSeparate)
7718 apszArgs[iArg++] = "--separate";
7719 apszArgs[iArg++] = pszSupHardeningLogArg;
7720
7721 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7722 }
7723#else /* !VBOX_WITH_QTGUI */
7724 if (0)
7725 ;
7726#endif /* VBOX_WITH_QTGUI */
7727
7728 else
7729
7730#ifdef VBOX_WITH_VBOXSDL
7731 if ( !strFrontend.compare("sdl", Utf8Str::CaseInsensitive)
7732 || !strFrontend.compare("GUI/SDL", Utf8Str::CaseInsensitive)
7733 || !strFrontend.compare("sdl/separate", Utf8Str::CaseInsensitive)
7734 || !strFrontend.compare("GUI/SDL/separate", Utf8Str::CaseInsensitive))
7735 {
7736 strCanonicalName = "GUI/SDL";
7737 static const char s_szVBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
7738 Assert(cchBufLeft >= sizeof(s_szVBoxSDL_exe));
7739 strcpy(pszNamePart, s_szVBoxSDL_exe);
7740
7741 Utf8Str idStr = mData->mUuid.toString();
7742 const char *apszArgs[] =
7743 {
7744 szPath,
7745 "--comment", mUserData->s.strName.c_str(),
7746 "--startvm", idStr.c_str(),
7747 NULL, /* For "--separate". */
7748 NULL, /* For "--sup-startup-log". */
7749 NULL
7750 };
7751 unsigned iArg = 5;
7752 if (fSeparate)
7753 apszArgs[iArg++] = "--separate";
7754 apszArgs[iArg++] = pszSupHardeningLogArg;
7755
7756 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7757 }
7758#else /* !VBOX_WITH_VBOXSDL */
7759 if (0)
7760 ;
7761#endif /* !VBOX_WITH_VBOXSDL */
7762
7763 else
7764
7765#ifdef VBOX_WITH_HEADLESS
7766 if ( !strFrontend.compare("headless", Utf8Str::CaseInsensitive)
7767 || !strFrontend.compare("capture", Utf8Str::CaseInsensitive)
7768 || !strFrontend.compare("vrdp", Utf8Str::CaseInsensitive) /* Deprecated. Same as headless. */
7769 )
7770 {
7771 strCanonicalName = "headless";
7772 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
7773 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
7774 * and a VM works even if the server has not been installed.
7775 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
7776 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
7777 * differently in 4.0 and 3.x.
7778 */
7779 static const char s_szVBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
7780 Assert(cchBufLeft >= sizeof(s_szVBoxHeadless_exe));
7781 strcpy(pszNamePart, s_szVBoxHeadless_exe);
7782
7783 Utf8Str idStr = mData->mUuid.toString();
7784 const char *apszArgs[] =
7785 {
7786 szPath,
7787 "--comment", mUserData->s.strName.c_str(),
7788 "--startvm", idStr.c_str(),
7789 "--vrde", "config",
7790 NULL, /* For "--capture". */
7791 NULL, /* For "--sup-startup-log". */
7792 NULL
7793 };
7794 unsigned iArg = 7;
7795 if (!strFrontend.compare("capture", Utf8Str::CaseInsensitive))
7796 apszArgs[iArg++] = "--capture";
7797 apszArgs[iArg++] = pszSupHardeningLogArg;
7798
7799# ifdef RT_OS_WINDOWS
7800 vrc = RTProcCreate(szPath, apszArgs, env, RTPROC_FLAGS_NO_WINDOW, &pid);
7801# else
7802 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7803# endif
7804 }
7805#else /* !VBOX_WITH_HEADLESS */
7806 if (0)
7807 ;
7808#endif /* !VBOX_WITH_HEADLESS */
7809 else
7810 {
7811 RTEnvDestroy(env);
7812 return setError(E_INVALIDARG,
7813 tr("Invalid frontend name: '%s'"),
7814 strFrontend.c_str());
7815 }
7816
7817 RTEnvDestroy(env);
7818
7819 if (RT_FAILURE(vrc))
7820 return setError(VBOX_E_IPRT_ERROR,
7821 tr("Could not launch a process for the machine '%s' (%Rrc)"),
7822 mUserData->s.strName.c_str(), vrc);
7823
7824 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
7825
7826 if (!fSeparate)
7827 {
7828 /*
7829 * Note that we don't release the lock here before calling the client,
7830 * because it doesn't need to call us back if called with a NULL argument.
7831 * Releasing the lock here is dangerous because we didn't prepare the
7832 * launch data yet, but the client we've just started may happen to be
7833 * too fast and call LockMachine() that will fail (because of PID, etc.),
7834 * so that the Machine will never get out of the Spawning session state.
7835 */
7836
7837 /* inform the session that it will be a remote one */
7838 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
7839#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
7840 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write, Bstr::Empty.raw());
7841#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
7842 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write, NULL);
7843#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
7844 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
7845
7846 if (FAILED(rc))
7847 {
7848 /* restore the session state */
7849 mData->mSession.mState = SessionState_Unlocked;
7850 alock.release();
7851 mParent->i_addProcessToReap(pid);
7852 /* The failure may occur w/o any error info (from RPC), so provide one */
7853 return setError(VBOX_E_VM_ERROR,
7854 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
7855 }
7856
7857 /* attach launch data to the machine */
7858 Assert(mData->mSession.mPID == NIL_RTPROCESS);
7859 mData->mSession.mRemoteControls.push_back(aControl);
7860 mData->mSession.mProgress = aProgress;
7861 mData->mSession.mPID = pid;
7862 mData->mSession.mState = SessionState_Spawning;
7863 Assert(strCanonicalName.isNotEmpty());
7864 mData->mSession.mName = strCanonicalName;
7865 }
7866 else
7867 {
7868 /* For separate UI process we declare the launch as completed instantly, as the
7869 * actual headless VM start may or may not come. No point in remembering anything
7870 * yet, as what matters for us is when the headless VM gets started. */
7871 aProgress->i_notifyComplete(S_OK);
7872 }
7873
7874 alock.release();
7875 mParent->i_addProcessToReap(pid);
7876
7877 LogFlowThisFuncLeave();
7878 return S_OK;
7879}
7880
7881/**
7882 * Returns @c true if the given session machine instance has an open direct
7883 * session (and optionally also for direct sessions which are closing) and
7884 * returns the session control machine instance if so.
7885 *
7886 * Note that when the method returns @c false, the arguments remain unchanged.
7887 *
7888 * @param aMachine Session machine object.
7889 * @param aControl Direct session control object (optional).
7890 * @param aRequireVM If true then only allow VM sessions.
7891 * @param aAllowClosing If true then additionally a session which is currently
7892 * being closed will also be allowed.
7893 *
7894 * @note locks this object for reading.
7895 */
7896bool Machine::i_isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7897 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7898 bool aRequireVM /*= false*/,
7899 bool aAllowClosing /*= false*/)
7900{
7901 AutoLimitedCaller autoCaller(this);
7902 AssertComRCReturn(autoCaller.rc(), false);
7903
7904 /* just return false for inaccessible machines */
7905 if (getObjectState().getState() != ObjectState::Ready)
7906 return false;
7907
7908 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7909
7910 if ( ( mData->mSession.mState == SessionState_Locked
7911 && (!aRequireVM || mData->mSession.mLockType == LockType_VM))
7912 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
7913 )
7914 {
7915 AssertReturn(!mData->mSession.mMachine.isNull(), false);
7916
7917 aMachine = mData->mSession.mMachine;
7918
7919 if (aControl != NULL)
7920 *aControl = mData->mSession.mDirectControl;
7921
7922 return true;
7923 }
7924
7925 return false;
7926}
7927
7928/**
7929 * Returns @c true if the given machine has an spawning direct session.
7930 *
7931 * @note locks this object for reading.
7932 */
7933bool Machine::i_isSessionSpawning()
7934{
7935 AutoLimitedCaller autoCaller(this);
7936 AssertComRCReturn(autoCaller.rc(), false);
7937
7938 /* just return false for inaccessible machines */
7939 if (getObjectState().getState() != ObjectState::Ready)
7940 return false;
7941
7942 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7943
7944 if (mData->mSession.mState == SessionState_Spawning)
7945 return true;
7946
7947 return false;
7948}
7949
7950/**
7951 * Called from the client watcher thread to check for unexpected client process
7952 * death during Session_Spawning state (e.g. before it successfully opened a
7953 * direct session).
7954 *
7955 * On Win32 and on OS/2, this method is called only when we've got the
7956 * direct client's process termination notification, so it always returns @c
7957 * true.
7958 *
7959 * On other platforms, this method returns @c true if the client process is
7960 * terminated and @c false if it's still alive.
7961 *
7962 * @note Locks this object for writing.
7963 */
7964bool Machine::i_checkForSpawnFailure()
7965{
7966 AutoCaller autoCaller(this);
7967 if (!autoCaller.isOk())
7968 {
7969 /* nothing to do */
7970 LogFlowThisFunc(("Already uninitialized!\n"));
7971 return true;
7972 }
7973
7974 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7975
7976 if (mData->mSession.mState != SessionState_Spawning)
7977 {
7978 /* nothing to do */
7979 LogFlowThisFunc(("Not spawning any more!\n"));
7980 return true;
7981 }
7982
7983 HRESULT rc = S_OK;
7984
7985 /* PID not yet initialized, skip check. */
7986 if (mData->mSession.mPID == NIL_RTPROCESS)
7987 return false;
7988
7989 RTPROCSTATUS status;
7990 int vrc = RTProcWait(mData->mSession.mPID, RTPROCWAIT_FLAGS_NOBLOCK, &status);
7991
7992 if (vrc != VERR_PROCESS_RUNNING)
7993 {
7994 Utf8Str strExtraInfo;
7995
7996#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7997 /* If the startup logfile exists and is of non-zero length, tell the
7998 user to look there for more details to encourage them to attach it
7999 when reporting startup issues. */
8000 Utf8Str strHardeningLogFile = i_getHardeningLogFilename();
8001 uint64_t cbStartupLogFile = 0;
8002 int vrc2 = RTFileQuerySize(strHardeningLogFile.c_str(), &cbStartupLogFile);
8003 if (RT_SUCCESS(vrc2) && cbStartupLogFile > 0)
8004 strExtraInfo.append(Utf8StrFmt(tr(". More details may be available in '%s'"), strHardeningLogFile.c_str()));
8005#endif
8006
8007 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
8008 rc = setError(E_FAIL,
8009 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d (%#x)%s"),
8010 i_getName().c_str(), status.iStatus, status.iStatus, strExtraInfo.c_str());
8011 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
8012 rc = setError(E_FAIL,
8013 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d%s"),
8014 i_getName().c_str(), status.iStatus, strExtraInfo.c_str());
8015 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
8016 rc = setError(E_FAIL,
8017 tr("The virtual machine '%s' has terminated abnormally (iStatus=%#x)%s"),
8018 i_getName().c_str(), status.iStatus, strExtraInfo.c_str());
8019 else
8020 rc = setError(E_FAIL,
8021 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)%s"),
8022 i_getName().c_str(), vrc, strExtraInfo.c_str());
8023 }
8024
8025 if (FAILED(rc))
8026 {
8027 /* Close the remote session, remove the remote control from the list
8028 * and reset session state to Closed (@note keep the code in sync with
8029 * the relevant part in LockMachine()). */
8030
8031 Assert(mData->mSession.mRemoteControls.size() == 1);
8032 if (mData->mSession.mRemoteControls.size() == 1)
8033 {
8034 ErrorInfoKeeper eik;
8035 mData->mSession.mRemoteControls.front()->Uninitialize();
8036 }
8037
8038 mData->mSession.mRemoteControls.clear();
8039 mData->mSession.mState = SessionState_Unlocked;
8040
8041 /* finalize the progress after setting the state */
8042 if (!mData->mSession.mProgress.isNull())
8043 {
8044 mData->mSession.mProgress->notifyComplete(rc);
8045 mData->mSession.mProgress.setNull();
8046 }
8047
8048 mData->mSession.mPID = NIL_RTPROCESS;
8049
8050 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
8051 return true;
8052 }
8053
8054 return false;
8055}
8056
8057/**
8058 * Checks whether the machine can be registered. If so, commits and saves
8059 * all settings.
8060 *
8061 * @note Must be called from mParent's write lock. Locks this object and
8062 * children for writing.
8063 */
8064HRESULT Machine::i_prepareRegister()
8065{
8066 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
8067
8068 AutoLimitedCaller autoCaller(this);
8069 AssertComRCReturnRC(autoCaller.rc());
8070
8071 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8072
8073 /* wait for state dependents to drop to zero */
8074 i_ensureNoStateDependencies();
8075
8076 if (!mData->mAccessible)
8077 return setError(VBOX_E_INVALID_OBJECT_STATE,
8078 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
8079 mUserData->s.strName.c_str(),
8080 mData->mUuid.toString().c_str());
8081
8082 AssertReturn(getObjectState().getState() == ObjectState::Ready, E_FAIL);
8083
8084 if (mData->mRegistered)
8085 return setError(VBOX_E_INVALID_OBJECT_STATE,
8086 tr("The machine '%s' with UUID {%s} is already registered"),
8087 mUserData->s.strName.c_str(),
8088 mData->mUuid.toString().c_str());
8089
8090 HRESULT rc = S_OK;
8091
8092 // Ensure the settings are saved. If we are going to be registered and
8093 // no config file exists yet, create it by calling i_saveSettings() too.
8094 if ( (mData->flModifications)
8095 || (!mData->pMachineConfigFile->fileExists())
8096 )
8097 {
8098 rc = i_saveSettings(NULL);
8099 // no need to check whether VirtualBox.xml needs saving too since
8100 // we can't have a machine XML file rename pending
8101 if (FAILED(rc)) return rc;
8102 }
8103
8104 /* more config checking goes here */
8105
8106 if (SUCCEEDED(rc))
8107 {
8108 /* we may have had implicit modifications we want to fix on success */
8109 i_commit();
8110
8111 mData->mRegistered = true;
8112 }
8113 else
8114 {
8115 /* we may have had implicit modifications we want to cancel on failure*/
8116 i_rollback(false /* aNotify */);
8117 }
8118
8119 return rc;
8120}
8121
8122/**
8123 * Increases the number of objects dependent on the machine state or on the
8124 * registered state. Guarantees that these two states will not change at least
8125 * until #i_releaseStateDependency() is called.
8126 *
8127 * Depending on the @a aDepType value, additional state checks may be made.
8128 * These checks will set extended error info on failure. See
8129 * #i_checkStateDependency() for more info.
8130 *
8131 * If this method returns a failure, the dependency is not added and the caller
8132 * is not allowed to rely on any particular machine state or registration state
8133 * value and may return the failed result code to the upper level.
8134 *
8135 * @param aDepType Dependency type to add.
8136 * @param aState Current machine state (NULL if not interested).
8137 * @param aRegistered Current registered state (NULL if not interested).
8138 *
8139 * @note Locks this object for writing.
8140 */
8141HRESULT Machine::i_addStateDependency(StateDependency aDepType /* = AnyStateDep */,
8142 MachineState_T *aState /* = NULL */,
8143 BOOL *aRegistered /* = NULL */)
8144{
8145 AutoCaller autoCaller(this);
8146 AssertComRCReturnRC(autoCaller.rc());
8147
8148 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8149
8150 HRESULT rc = i_checkStateDependency(aDepType);
8151 if (FAILED(rc)) return rc;
8152
8153 {
8154 if (mData->mMachineStateChangePending != 0)
8155 {
8156 /* i_ensureNoStateDependencies() is waiting for state dependencies to
8157 * drop to zero so don't add more. It may make sense to wait a bit
8158 * and retry before reporting an error (since the pending state
8159 * transition should be really quick) but let's just assert for
8160 * now to see if it ever happens on practice. */
8161
8162 AssertFailed();
8163
8164 return setError(E_ACCESSDENIED,
8165 tr("Machine state change is in progress. Please retry the operation later."));
8166 }
8167
8168 ++mData->mMachineStateDeps;
8169 Assert(mData->mMachineStateDeps != 0 /* overflow */);
8170 }
8171
8172 if (aState)
8173 *aState = mData->mMachineState;
8174 if (aRegistered)
8175 *aRegistered = mData->mRegistered;
8176
8177 return S_OK;
8178}
8179
8180/**
8181 * Decreases the number of objects dependent on the machine state.
8182 * Must always complete the #i_addStateDependency() call after the state
8183 * dependency is no more necessary.
8184 */
8185void Machine::i_releaseStateDependency()
8186{
8187 AutoCaller autoCaller(this);
8188 AssertComRCReturnVoid(autoCaller.rc());
8189
8190 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8191
8192 /* releaseStateDependency() w/o addStateDependency()? */
8193 AssertReturnVoid(mData->mMachineStateDeps != 0);
8194 -- mData->mMachineStateDeps;
8195
8196 if (mData->mMachineStateDeps == 0)
8197 {
8198 /* inform i_ensureNoStateDependencies() that there are no more deps */
8199 if (mData->mMachineStateChangePending != 0)
8200 {
8201 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
8202 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
8203 }
8204 }
8205}
8206
8207Utf8Str Machine::i_getExtraData(const Utf8Str &strKey)
8208{
8209 /* start with nothing found */
8210 Utf8Str strResult("");
8211
8212 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8213
8214 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
8215 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
8216 // found:
8217 strResult = it->second; // source is a Utf8Str
8218
8219 return strResult;
8220}
8221
8222// protected methods
8223/////////////////////////////////////////////////////////////////////////////
8224
8225/**
8226 * Performs machine state checks based on the @a aDepType value. If a check
8227 * fails, this method will set extended error info, otherwise it will return
8228 * S_OK. It is supposed, that on failure, the caller will immediately return
8229 * the return value of this method to the upper level.
8230 *
8231 * When @a aDepType is AnyStateDep, this method always returns S_OK.
8232 *
8233 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
8234 * current state of this machine object allows to change settings of the
8235 * machine (i.e. the machine is not registered, or registered but not running
8236 * and not saved). It is useful to call this method from Machine setters
8237 * before performing any change.
8238 *
8239 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
8240 * as for MutableStateDep except that if the machine is saved, S_OK is also
8241 * returned. This is useful in setters which allow changing machine
8242 * properties when it is in the saved state.
8243 *
8244 * When @a aDepType is MutableOrRunningStateDep, this method returns S_OK only
8245 * if the current state of this machine object allows to change runtime
8246 * changeable settings of the machine (i.e. the machine is not registered, or
8247 * registered but either running or not running and not saved). It is useful
8248 * to call this method from Machine setters before performing any changes to
8249 * runtime changeable settings.
8250 *
8251 * When @a aDepType is MutableOrSavedOrRunningStateDep, this method behaves
8252 * the same as for MutableOrRunningStateDep except that if the machine is
8253 * saved, S_OK is also returned. This is useful in setters which allow
8254 * changing runtime and saved state changeable machine properties.
8255 *
8256 * @param aDepType Dependency type to check.
8257 *
8258 * @note Non Machine based classes should use #i_addStateDependency() and
8259 * #i_releaseStateDependency() methods or the smart AutoStateDependency
8260 * template.
8261 *
8262 * @note This method must be called from under this object's read or write
8263 * lock.
8264 */
8265HRESULT Machine::i_checkStateDependency(StateDependency aDepType)
8266{
8267 switch (aDepType)
8268 {
8269 case AnyStateDep:
8270 {
8271 break;
8272 }
8273 case MutableStateDep:
8274 {
8275 if ( mData->mRegistered
8276 && ( !i_isSessionMachine()
8277 || ( mData->mMachineState != MachineState_Aborted
8278 && mData->mMachineState != MachineState_Teleported
8279 && mData->mMachineState != MachineState_PoweredOff
8280 )
8281 )
8282 )
8283 return setError(VBOX_E_INVALID_VM_STATE,
8284 tr("The machine is not mutable (state is %s)"),
8285 Global::stringifyMachineState(mData->mMachineState));
8286 break;
8287 }
8288 case MutableOrSavedStateDep:
8289 {
8290 if ( mData->mRegistered
8291 && ( !i_isSessionMachine()
8292 || ( mData->mMachineState != MachineState_Aborted
8293 && mData->mMachineState != MachineState_Teleported
8294 && mData->mMachineState != MachineState_Saved
8295 && mData->mMachineState != MachineState_PoweredOff
8296 )
8297 )
8298 )
8299 return setError(VBOX_E_INVALID_VM_STATE,
8300 tr("The machine is not mutable or saved (state is %s)"),
8301 Global::stringifyMachineState(mData->mMachineState));
8302 break;
8303 }
8304 case MutableOrRunningStateDep:
8305 {
8306 if ( mData->mRegistered
8307 && ( !i_isSessionMachine()
8308 || ( mData->mMachineState != MachineState_Aborted
8309 && mData->mMachineState != MachineState_Teleported
8310 && mData->mMachineState != MachineState_PoweredOff
8311 && !Global::IsOnline(mData->mMachineState)
8312 )
8313 )
8314 )
8315 return setError(VBOX_E_INVALID_VM_STATE,
8316 tr("The machine is not mutable or running (state is %s)"),
8317 Global::stringifyMachineState(mData->mMachineState));
8318 break;
8319 }
8320 case MutableOrSavedOrRunningStateDep:
8321 {
8322 if ( mData->mRegistered
8323 && ( !i_isSessionMachine()
8324 || ( mData->mMachineState != MachineState_Aborted
8325 && mData->mMachineState != MachineState_Teleported
8326 && mData->mMachineState != MachineState_Saved
8327 && mData->mMachineState != MachineState_PoweredOff
8328 && !Global::IsOnline(mData->mMachineState)
8329 )
8330 )
8331 )
8332 return setError(VBOX_E_INVALID_VM_STATE,
8333 tr("The machine is not mutable, saved or running (state is %s)"),
8334 Global::stringifyMachineState(mData->mMachineState));
8335 break;
8336 }
8337 }
8338
8339 return S_OK;
8340}
8341
8342/**
8343 * Helper to initialize all associated child objects and allocate data
8344 * structures.
8345 *
8346 * This method must be called as a part of the object's initialization procedure
8347 * (usually done in the #init() method).
8348 *
8349 * @note Must be called only from #init() or from #i_registeredInit().
8350 */
8351HRESULT Machine::initDataAndChildObjects()
8352{
8353 AutoCaller autoCaller(this);
8354 AssertComRCReturnRC(autoCaller.rc());
8355 AssertComRCReturn( getObjectState().getState() == ObjectState::InInit
8356 || getObjectState().getState() == ObjectState::Limited, E_FAIL);
8357
8358 AssertReturn(!mData->mAccessible, E_FAIL);
8359
8360 /* allocate data structures */
8361 mSSData.allocate();
8362 mUserData.allocate();
8363 mHWData.allocate();
8364 mMediumAttachments.allocate();
8365 mStorageControllers.allocate();
8366 mUSBControllers.allocate();
8367
8368 /* initialize mOSTypeId */
8369 mUserData->s.strOsType = mParent->i_getUnknownOSType()->i_id();
8370
8371/** @todo r=bird: init() methods never fails, right? Why don't we make them
8372 * return void then! */
8373
8374 /* create associated BIOS settings object */
8375 unconst(mBIOSSettings).createObject();
8376 mBIOSSettings->init(this);
8377
8378 /* create an associated VRDE object (default is disabled) */
8379 unconst(mVRDEServer).createObject();
8380 mVRDEServer->init(this);
8381
8382 /* create associated serial port objects */
8383 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8384 {
8385 unconst(mSerialPorts[slot]).createObject();
8386 mSerialPorts[slot]->init(this, slot);
8387 }
8388
8389 /* create associated parallel port objects */
8390 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8391 {
8392 unconst(mParallelPorts[slot]).createObject();
8393 mParallelPorts[slot]->init(this, slot);
8394 }
8395
8396 /* create the audio adapter object (always present, default is disabled) */
8397 unconst(mAudioAdapter).createObject();
8398 mAudioAdapter->init(this);
8399
8400 /* create the USB device filters object (always present) */
8401 unconst(mUSBDeviceFilters).createObject();
8402 mUSBDeviceFilters->init(this);
8403
8404 /* create associated network adapter objects */
8405 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
8406 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8407 {
8408 unconst(mNetworkAdapters[slot]).createObject();
8409 mNetworkAdapters[slot]->init(this, slot);
8410 }
8411
8412 /* create the bandwidth control */
8413 unconst(mBandwidthControl).createObject();
8414 mBandwidthControl->init(this);
8415
8416 return S_OK;
8417}
8418
8419/**
8420 * Helper to uninitialize all associated child objects and to free all data
8421 * structures.
8422 *
8423 * This method must be called as a part of the object's uninitialization
8424 * procedure (usually done in the #uninit() method).
8425 *
8426 * @note Must be called only from #uninit() or from #i_registeredInit().
8427 */
8428void Machine::uninitDataAndChildObjects()
8429{
8430 AutoCaller autoCaller(this);
8431 AssertComRCReturnVoid(autoCaller.rc());
8432 AssertComRCReturnVoid( getObjectState().getState() == ObjectState::InUninit
8433 || getObjectState().getState() == ObjectState::Limited);
8434
8435 /* tell all our other child objects we've been uninitialized */
8436 if (mBandwidthControl)
8437 {
8438 mBandwidthControl->uninit();
8439 unconst(mBandwidthControl).setNull();
8440 }
8441
8442 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8443 {
8444 if (mNetworkAdapters[slot])
8445 {
8446 mNetworkAdapters[slot]->uninit();
8447 unconst(mNetworkAdapters[slot]).setNull();
8448 }
8449 }
8450
8451 if (mUSBDeviceFilters)
8452 {
8453 mUSBDeviceFilters->uninit();
8454 unconst(mUSBDeviceFilters).setNull();
8455 }
8456
8457 if (mAudioAdapter)
8458 {
8459 mAudioAdapter->uninit();
8460 unconst(mAudioAdapter).setNull();
8461 }
8462
8463 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8464 {
8465 if (mParallelPorts[slot])
8466 {
8467 mParallelPorts[slot]->uninit();
8468 unconst(mParallelPorts[slot]).setNull();
8469 }
8470 }
8471
8472 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8473 {
8474 if (mSerialPorts[slot])
8475 {
8476 mSerialPorts[slot]->uninit();
8477 unconst(mSerialPorts[slot]).setNull();
8478 }
8479 }
8480
8481 if (mVRDEServer)
8482 {
8483 mVRDEServer->uninit();
8484 unconst(mVRDEServer).setNull();
8485 }
8486
8487 if (mBIOSSettings)
8488 {
8489 mBIOSSettings->uninit();
8490 unconst(mBIOSSettings).setNull();
8491 }
8492
8493 /* Deassociate media (only when a real Machine or a SnapshotMachine
8494 * instance is uninitialized; SessionMachine instances refer to real
8495 * Machine media). This is necessary for a clean re-initialization of
8496 * the VM after successfully re-checking the accessibility state. Note
8497 * that in case of normal Machine or SnapshotMachine uninitialization (as
8498 * a result of unregistering or deleting the snapshot), outdated media
8499 * attachments will already be uninitialized and deleted, so this
8500 * code will not affect them. */
8501 if ( !mMediumAttachments.isNull()
8502 && !i_isSessionMachine()
8503 )
8504 {
8505 for (MediumAttachmentList::const_iterator
8506 it = mMediumAttachments->begin();
8507 it != mMediumAttachments->end();
8508 ++it)
8509 {
8510 ComObjPtr<Medium> pMedium = (*it)->i_getMedium();
8511 if (pMedium.isNull())
8512 continue;
8513 HRESULT rc = pMedium->i_removeBackReference(mData->mUuid, i_getSnapshotId());
8514 AssertComRC(rc);
8515 }
8516 }
8517
8518 if (!i_isSessionMachine() && !i_isSnapshotMachine())
8519 {
8520 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
8521 if (mData->mFirstSnapshot)
8522 {
8523 // snapshots tree is protected by machine write lock; strictly
8524 // this isn't necessary here since we're deleting the entire
8525 // machine, but otherwise we assert in Snapshot::uninit()
8526 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8527 mData->mFirstSnapshot->uninit();
8528 mData->mFirstSnapshot.setNull();
8529 }
8530
8531 mData->mCurrentSnapshot.setNull();
8532 }
8533
8534 /* free data structures (the essential mData structure is not freed here
8535 * since it may be still in use) */
8536 mMediumAttachments.free();
8537 mStorageControllers.free();
8538 mUSBControllers.free();
8539 mHWData.free();
8540 mUserData.free();
8541 mSSData.free();
8542}
8543
8544/**
8545 * Returns a pointer to the Machine object for this machine that acts like a
8546 * parent for complex machine data objects such as shared folders, etc.
8547 *
8548 * For primary Machine objects and for SnapshotMachine objects, returns this
8549 * object's pointer itself. For SessionMachine objects, returns the peer
8550 * (primary) machine pointer.
8551 */
8552Machine *Machine::i_getMachine()
8553{
8554 if (i_isSessionMachine())
8555 return (Machine*)mPeer;
8556 return this;
8557}
8558
8559/**
8560 * Makes sure that there are no machine state dependents. If necessary, waits
8561 * for the number of dependents to drop to zero.
8562 *
8563 * Make sure this method is called from under this object's write lock to
8564 * guarantee that no new dependents may be added when this method returns
8565 * control to the caller.
8566 *
8567 * @note Locks this object for writing. The lock will be released while waiting
8568 * (if necessary).
8569 *
8570 * @warning To be used only in methods that change the machine state!
8571 */
8572void Machine::i_ensureNoStateDependencies()
8573{
8574 AssertReturnVoid(isWriteLockOnCurrentThread());
8575
8576 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8577
8578 /* Wait for all state dependents if necessary */
8579 if (mData->mMachineStateDeps != 0)
8580 {
8581 /* lazy semaphore creation */
8582 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
8583 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
8584
8585 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
8586 mData->mMachineStateDeps));
8587
8588 ++mData->mMachineStateChangePending;
8589
8590 /* reset the semaphore before waiting, the last dependent will signal
8591 * it */
8592 RTSemEventMultiReset(mData->mMachineStateDepsSem);
8593
8594 alock.release();
8595
8596 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
8597
8598 alock.acquire();
8599
8600 -- mData->mMachineStateChangePending;
8601 }
8602}
8603
8604/**
8605 * Changes the machine state and informs callbacks.
8606 *
8607 * This method is not intended to fail so it either returns S_OK or asserts (and
8608 * returns a failure).
8609 *
8610 * @note Locks this object for writing.
8611 */
8612HRESULT Machine::i_setMachineState(MachineState_T aMachineState)
8613{
8614 LogFlowThisFuncEnter();
8615 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
8616 Assert(aMachineState != MachineState_Null);
8617
8618 AutoCaller autoCaller(this);
8619 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8620
8621 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8622
8623 /* wait for state dependents to drop to zero */
8624 i_ensureNoStateDependencies();
8625
8626 MachineState_T const enmOldState = mData->mMachineState;
8627 if (enmOldState != aMachineState)
8628 {
8629 mData->mMachineState = aMachineState;
8630 RTTimeNow(&mData->mLastStateChange);
8631
8632#ifdef VBOX_WITH_DTRACE_R3_MAIN
8633 VBOXAPI_MACHINE_STATE_CHANGED(this, aMachineState, enmOldState, mData->mUuid.toStringCurly().c_str());
8634#endif
8635 mParent->i_onMachineStateChange(mData->mUuid, aMachineState);
8636 }
8637
8638 LogFlowThisFuncLeave();
8639 return S_OK;
8640}
8641
8642/**
8643 * Searches for a shared folder with the given logical name
8644 * in the collection of shared folders.
8645 *
8646 * @param aName logical name of the shared folder
8647 * @param aSharedFolder where to return the found object
8648 * @param aSetError whether to set the error info if the folder is
8649 * not found
8650 * @return
8651 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
8652 *
8653 * @note
8654 * must be called from under the object's lock!
8655 */
8656HRESULT Machine::i_findSharedFolder(const Utf8Str &aName,
8657 ComObjPtr<SharedFolder> &aSharedFolder,
8658 bool aSetError /* = false */)
8659{
8660 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
8661 for (HWData::SharedFolderList::const_iterator
8662 it = mHWData->mSharedFolders.begin();
8663 it != mHWData->mSharedFolders.end();
8664 ++it)
8665 {
8666 SharedFolder *pSF = *it;
8667 AutoCaller autoCaller(pSF);
8668 if (pSF->i_getName() == aName)
8669 {
8670 aSharedFolder = pSF;
8671 rc = S_OK;
8672 break;
8673 }
8674 }
8675
8676 if (aSetError && FAILED(rc))
8677 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
8678
8679 return rc;
8680}
8681
8682/**
8683 * Initializes all machine instance data from the given settings structures
8684 * from XML. The exception is the machine UUID which needs special handling
8685 * depending on the caller's use case, so the caller needs to set that herself.
8686 *
8687 * This gets called in several contexts during machine initialization:
8688 *
8689 * -- When machine XML exists on disk already and needs to be loaded into memory,
8690 * for example, from #i_registeredInit() to load all registered machines on
8691 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
8692 * attached to the machine should be part of some media registry already.
8693 *
8694 * -- During OVF import, when a machine config has been constructed from an
8695 * OVF file. In this case, puuidRegistry is set to the machine UUID to
8696 * ensure that the media listed as attachments in the config (which have
8697 * been imported from the OVF) receive the correct registry ID.
8698 *
8699 * -- During VM cloning.
8700 *
8701 * @param config Machine settings from XML.
8702 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID
8703 * for each attached medium in the config.
8704 * @return
8705 */
8706HRESULT Machine::i_loadMachineDataFromSettings(const settings::MachineConfigFile &config,
8707 const Guid *puuidRegistry)
8708{
8709 // copy name, description, OS type, teleporter, UTC etc.
8710 mUserData->s = config.machineUserData;
8711
8712 // look up the object by Id to check it is valid
8713 ComObjPtr<GuestOSType> pGuestOSType;
8714 HRESULT rc = mParent->i_findGuestOSType(mUserData->s.strOsType,
8715 pGuestOSType);
8716 if (FAILED(rc)) return rc;
8717 mUserData->s.strOsType = pGuestOSType->i_id();
8718
8719 // stateFile (optional)
8720 if (config.strStateFile.isEmpty())
8721 mSSData->strStateFilePath.setNull();
8722 else
8723 {
8724 Utf8Str stateFilePathFull(config.strStateFile);
8725 int vrc = i_calculateFullPath(stateFilePathFull, stateFilePathFull);
8726 if (RT_FAILURE(vrc))
8727 return setError(E_FAIL,
8728 tr("Invalid saved state file path '%s' (%Rrc)"),
8729 config.strStateFile.c_str(),
8730 vrc);
8731 mSSData->strStateFilePath = stateFilePathFull;
8732 }
8733
8734 // snapshot folder needs special processing so set it again
8735 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
8736 if (FAILED(rc)) return rc;
8737
8738 /* Copy the extra data items (config may or may not be the same as
8739 * mData->pMachineConfigFile) if necessary. When loading the XML files
8740 * from disk they are the same, but not for OVF import. */
8741 if (mData->pMachineConfigFile != &config)
8742 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
8743
8744 /* currentStateModified (optional, default is true) */
8745 mData->mCurrentStateModified = config.fCurrentStateModified;
8746
8747 mData->mLastStateChange = config.timeLastStateChange;
8748
8749 /*
8750 * note: all mUserData members must be assigned prior this point because
8751 * we need to commit changes in order to let mUserData be shared by all
8752 * snapshot machine instances.
8753 */
8754 mUserData.commitCopy();
8755
8756 // machine registry, if present (must be loaded before snapshots)
8757 if (config.canHaveOwnMediaRegistry())
8758 {
8759 // determine machine folder
8760 Utf8Str strMachineFolder = i_getSettingsFileFull();
8761 strMachineFolder.stripFilename();
8762 rc = mParent->initMedia(i_getId(), // media registry ID == machine UUID
8763 config.mediaRegistry,
8764 strMachineFolder);
8765 if (FAILED(rc)) return rc;
8766 }
8767
8768 /* Snapshot node (optional) */
8769 size_t cRootSnapshots;
8770 if ((cRootSnapshots = config.llFirstSnapshot.size()))
8771 {
8772 // there must be only one root snapshot
8773 Assert(cRootSnapshots == 1);
8774
8775 const settings::Snapshot &snap = config.llFirstSnapshot.front();
8776
8777 rc = i_loadSnapshot(snap,
8778 config.uuidCurrentSnapshot,
8779 NULL); // no parent == first snapshot
8780 if (FAILED(rc)) return rc;
8781 }
8782
8783 // hardware data
8784 rc = i_loadHardware(puuidRegistry, NULL, config.hardwareMachine, &config.debugging, &config.autostart);
8785 if (FAILED(rc)) return rc;
8786
8787 /*
8788 * NOTE: the assignment below must be the last thing to do,
8789 * otherwise it will be not possible to change the settings
8790 * somewhere in the code above because all setters will be
8791 * blocked by i_checkStateDependency(MutableStateDep).
8792 */
8793
8794 /* set the machine state to Aborted or Saved when appropriate */
8795 if (config.fAborted)
8796 {
8797 mSSData->strStateFilePath.setNull();
8798
8799 /* no need to use i_setMachineState() during init() */
8800 mData->mMachineState = MachineState_Aborted;
8801 }
8802 else if (!mSSData->strStateFilePath.isEmpty())
8803 {
8804 /* no need to use i_setMachineState() during init() */
8805 mData->mMachineState = MachineState_Saved;
8806 }
8807
8808 // after loading settings, we are no longer different from the XML on disk
8809 mData->flModifications = 0;
8810
8811 return S_OK;
8812}
8813
8814/**
8815 * Recursively loads all snapshots starting from the given.
8816 *
8817 * @param data snapshot settings.
8818 * @param aCurSnapshotId Current snapshot ID from the settings file.
8819 * @param aParentSnapshot Parent snapshot.
8820 */
8821HRESULT Machine::i_loadSnapshot(const settings::Snapshot &data,
8822 const Guid &aCurSnapshotId,
8823 Snapshot *aParentSnapshot)
8824{
8825 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
8826 AssertReturn(!i_isSessionMachine(), E_FAIL);
8827
8828 HRESULT rc = S_OK;
8829
8830 Utf8Str strStateFile;
8831 if (!data.strStateFile.isEmpty())
8832 {
8833 /* optional */
8834 strStateFile = data.strStateFile;
8835 int vrc = i_calculateFullPath(strStateFile, strStateFile);
8836 if (RT_FAILURE(vrc))
8837 return setError(E_FAIL,
8838 tr("Invalid saved state file path '%s' (%Rrc)"),
8839 strStateFile.c_str(),
8840 vrc);
8841 }
8842
8843 /* create a snapshot machine object */
8844 ComObjPtr<SnapshotMachine> pSnapshotMachine;
8845 pSnapshotMachine.createObject();
8846 rc = pSnapshotMachine->initFromSettings(this,
8847 data.hardware,
8848 &data.debugging,
8849 &data.autostart,
8850 data.uuid.ref(),
8851 strStateFile);
8852 if (FAILED(rc)) return rc;
8853
8854 /* create a snapshot object */
8855 ComObjPtr<Snapshot> pSnapshot;
8856 pSnapshot.createObject();
8857 /* initialize the snapshot */
8858 rc = pSnapshot->init(mParent, // VirtualBox object
8859 data.uuid,
8860 data.strName,
8861 data.strDescription,
8862 data.timestamp,
8863 pSnapshotMachine,
8864 aParentSnapshot);
8865 if (FAILED(rc)) return rc;
8866
8867 /* memorize the first snapshot if necessary */
8868 if (!mData->mFirstSnapshot)
8869 mData->mFirstSnapshot = pSnapshot;
8870
8871 /* memorize the current snapshot when appropriate */
8872 if ( !mData->mCurrentSnapshot
8873 && pSnapshot->i_getId() == aCurSnapshotId
8874 )
8875 mData->mCurrentSnapshot = pSnapshot;
8876
8877 // now create the children
8878 for (settings::SnapshotsList::const_iterator
8879 it = data.llChildSnapshots.begin();
8880 it != data.llChildSnapshots.end();
8881 ++it)
8882 {
8883 const settings::Snapshot &childData = *it;
8884 // recurse
8885 rc = i_loadSnapshot(childData,
8886 aCurSnapshotId,
8887 pSnapshot); // parent = the one we created above
8888 if (FAILED(rc)) return rc;
8889 }
8890
8891 return rc;
8892}
8893
8894/**
8895 * Loads settings into mHWData.
8896 *
8897 * @param puuidRegistry Registry ID.
8898 * @param puuidSnapshot Snapshot ID
8899 * @param data Reference to the hardware settings.
8900 * @param pDbg Pointer to the debugging settings.
8901 * @param pAutostart Pointer to the autostart settings.
8902 */
8903HRESULT Machine::i_loadHardware(const Guid *puuidRegistry,
8904 const Guid *puuidSnapshot,
8905 const settings::Hardware &data,
8906 const settings::Debugging *pDbg,
8907 const settings::Autostart *pAutostart)
8908{
8909 AssertReturn(!i_isSessionMachine(), E_FAIL);
8910
8911 HRESULT rc = S_OK;
8912
8913 try
8914 {
8915 ComObjPtr<GuestOSType> pGuestOSType;
8916 rc = mParent->i_findGuestOSType(Bstr(mUserData->s.strOsType).raw(),
8917 pGuestOSType);
8918 if (FAILED(rc))
8919 return rc;
8920
8921 /* The hardware version attribute (optional). */
8922 mHWData->mHWVersion = data.strVersion;
8923 mHWData->mHardwareUUID = data.uuid;
8924
8925 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
8926 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
8927 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
8928 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
8929 mHWData->mHWVirtExUXEnabled = data.fUnrestrictedExecution;
8930 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
8931 mHWData->mPAEEnabled = data.fPAE;
8932 mHWData->mLongMode = data.enmLongMode;
8933 mHWData->mTripleFaultReset = data.fTripleFaultReset;
8934 mHWData->mAPIC = data.fAPIC;
8935 mHWData->mX2APIC = data.fX2APIC;
8936 mHWData->mCPUCount = data.cCPUs;
8937 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
8938 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
8939 mHWData->mCpuIdPortabilityLevel = data.uCpuIdPortabilityLevel;
8940 mHWData->mCpuProfile = data.strCpuProfile;
8941
8942 // cpu
8943 if (mHWData->mCPUHotPlugEnabled)
8944 {
8945 for (settings::CpuList::const_iterator
8946 it = data.llCpus.begin();
8947 it != data.llCpus.end();
8948 ++it)
8949 {
8950 const settings::Cpu &cpu = *it;
8951
8952 mHWData->mCPUAttached[cpu.ulId] = true;
8953 }
8954 }
8955
8956 // cpuid leafs
8957 for (settings::CpuIdLeafsList::const_iterator
8958 it = data.llCpuIdLeafs.begin();
8959 it != data.llCpuIdLeafs.end();
8960 ++it)
8961 {
8962 const settings::CpuIdLeaf &leaf = *it;
8963
8964 switch (leaf.ulId)
8965 {
8966 case 0x0:
8967 case 0x1:
8968 case 0x2:
8969 case 0x3:
8970 case 0x4:
8971 case 0x5:
8972 case 0x6:
8973 case 0x7:
8974 case 0x8:
8975 case 0x9:
8976 case 0xA:
8977 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
8978 break;
8979
8980 case 0x80000000:
8981 case 0x80000001:
8982 case 0x80000002:
8983 case 0x80000003:
8984 case 0x80000004:
8985 case 0x80000005:
8986 case 0x80000006:
8987 case 0x80000007:
8988 case 0x80000008:
8989 case 0x80000009:
8990 case 0x8000000A:
8991 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
8992 break;
8993
8994 default:
8995 /* just ignore */
8996 break;
8997 }
8998 }
8999
9000 mHWData->mMemorySize = data.ulMemorySizeMB;
9001 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
9002
9003 // boot order
9004 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
9005 {
9006 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
9007 if (it == data.mapBootOrder.end())
9008 mHWData->mBootOrder[i] = DeviceType_Null;
9009 else
9010 mHWData->mBootOrder[i] = it->second;
9011 }
9012
9013 mHWData->mGraphicsControllerType = data.graphicsControllerType;
9014 mHWData->mVRAMSize = data.ulVRAMSizeMB;
9015 mHWData->mMonitorCount = data.cMonitors;
9016 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
9017 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
9018 mHWData->mVideoCaptureWidth = data.ulVideoCaptureHorzRes;
9019 mHWData->mVideoCaptureHeight = data.ulVideoCaptureVertRes;
9020 mHWData->mVideoCaptureEnabled = data.fVideoCaptureEnabled;
9021 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->maVideoCaptureScreens); ++i)
9022 mHWData->maVideoCaptureScreens[i] = ASMBitTest(&data.u64VideoCaptureScreens, i);
9023 AssertCompile(RT_ELEMENTS(mHWData->maVideoCaptureScreens) == sizeof(data.u64VideoCaptureScreens) * 8);
9024 mHWData->mVideoCaptureRate = data.ulVideoCaptureRate;
9025 mHWData->mVideoCaptureFPS = data.ulVideoCaptureFPS;
9026 if (!data.strVideoCaptureFile.isEmpty())
9027 i_calculateFullPath(data.strVideoCaptureFile, mHWData->mVideoCaptureFile);
9028 else
9029 mHWData->mVideoCaptureFile.setNull();
9030 mHWData->mFirmwareType = data.firmwareType;
9031 mHWData->mPointingHIDType = data.pointingHIDType;
9032 mHWData->mKeyboardHIDType = data.keyboardHIDType;
9033 mHWData->mChipsetType = data.chipsetType;
9034 mHWData->mParavirtProvider = data.paravirtProvider;
9035 mHWData->mParavirtDebug = data.strParavirtDebug;
9036 mHWData->mEmulatedUSBCardReaderEnabled = data.fEmulatedUSBCardReader;
9037 mHWData->mHPETEnabled = data.fHPETEnabled;
9038
9039 /* VRDEServer */
9040 rc = mVRDEServer->i_loadSettings(data.vrdeSettings);
9041 if (FAILED(rc)) return rc;
9042
9043 /* BIOS */
9044 rc = mBIOSSettings->i_loadSettings(data.biosSettings);
9045 if (FAILED(rc)) return rc;
9046
9047 // Bandwidth control (must come before network adapters)
9048 rc = mBandwidthControl->i_loadSettings(data.ioSettings);
9049 if (FAILED(rc)) return rc;
9050
9051 /* Shared folders */
9052 for (settings::USBControllerList::const_iterator
9053 it = data.usbSettings.llUSBControllers.begin();
9054 it != data.usbSettings.llUSBControllers.end();
9055 ++it)
9056 {
9057 const settings::USBController &settingsCtrl = *it;
9058 ComObjPtr<USBController> newCtrl;
9059
9060 newCtrl.createObject();
9061 newCtrl->init(this, settingsCtrl.strName, settingsCtrl.enmType);
9062 mUSBControllers->push_back(newCtrl);
9063 }
9064
9065 /* USB device filters */
9066 rc = mUSBDeviceFilters->i_loadSettings(data.usbSettings);
9067 if (FAILED(rc)) return rc;
9068
9069 // network adapters (establish array size first and apply defaults, to
9070 // ensure reading the same settings as we saved, since the list skips
9071 // adapters having defaults)
9072 size_t newCount = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
9073 size_t oldCount = mNetworkAdapters.size();
9074 if (newCount > oldCount)
9075 {
9076 mNetworkAdapters.resize(newCount);
9077 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); ++slot)
9078 {
9079 unconst(mNetworkAdapters[slot]).createObject();
9080 mNetworkAdapters[slot]->init(this, (ULONG)slot);
9081 }
9082 }
9083 else if (newCount < oldCount)
9084 mNetworkAdapters.resize(newCount);
9085 for (unsigned i = 0; i < mNetworkAdapters.size(); i++)
9086 mNetworkAdapters[i]->i_applyDefaults(pGuestOSType);
9087 for (settings::NetworkAdaptersList::const_iterator
9088 it = data.llNetworkAdapters.begin();
9089 it != data.llNetworkAdapters.end();
9090 ++it)
9091 {
9092 const settings::NetworkAdapter &nic = *it;
9093
9094 /* slot uniqueness is guaranteed by XML Schema */
9095 AssertBreak(nic.ulSlot < mNetworkAdapters.size());
9096 rc = mNetworkAdapters[nic.ulSlot]->i_loadSettings(mBandwidthControl, nic);
9097 if (FAILED(rc)) return rc;
9098 }
9099
9100 // serial ports (establish defaults first, to ensure reading the same
9101 // settings as we saved, since the list skips ports having defaults)
9102 for (unsigned i = 0; i < RT_ELEMENTS(mSerialPorts); i++)
9103 mSerialPorts[i]->i_applyDefaults(pGuestOSType);
9104 for (settings::SerialPortsList::const_iterator
9105 it = data.llSerialPorts.begin();
9106 it != data.llSerialPorts.end();
9107 ++it)
9108 {
9109 const settings::SerialPort &s = *it;
9110
9111 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
9112 rc = mSerialPorts[s.ulSlot]->i_loadSettings(s);
9113 if (FAILED(rc)) return rc;
9114 }
9115
9116 // parallel ports (establish defaults first, to ensure reading the same
9117 // settings as we saved, since the list skips ports having defaults)
9118 for (unsigned i = 0; i < RT_ELEMENTS(mParallelPorts); i++)
9119 mParallelPorts[i]->i_applyDefaults();
9120 for (settings::ParallelPortsList::const_iterator
9121 it = data.llParallelPorts.begin();
9122 it != data.llParallelPorts.end();
9123 ++it)
9124 {
9125 const settings::ParallelPort &p = *it;
9126
9127 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
9128 rc = mParallelPorts[p.ulSlot]->i_loadSettings(p);
9129 if (FAILED(rc)) return rc;
9130 }
9131
9132 /* AudioAdapter */
9133 rc = mAudioAdapter->i_loadSettings(data.audioAdapter);
9134 if (FAILED(rc)) return rc;
9135
9136 /* storage controllers */
9137 rc = i_loadStorageControllers(data.storage,
9138 puuidRegistry,
9139 puuidSnapshot);
9140 if (FAILED(rc)) return rc;
9141
9142 /* Shared folders */
9143 for (settings::SharedFoldersList::const_iterator
9144 it = data.llSharedFolders.begin();
9145 it != data.llSharedFolders.end();
9146 ++it)
9147 {
9148 const settings::SharedFolder &sf = *it;
9149
9150 ComObjPtr<SharedFolder> sharedFolder;
9151 /* Check for double entries. Not allowed! */
9152 rc = i_findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
9153 if (SUCCEEDED(rc))
9154 return setError(VBOX_E_OBJECT_IN_USE,
9155 tr("Shared folder named '%s' already exists"),
9156 sf.strName.c_str());
9157
9158 /* Create the new shared folder. Don't break on error. This will be
9159 * reported when the machine starts. */
9160 sharedFolder.createObject();
9161 rc = sharedFolder->init(i_getMachine(),
9162 sf.strName,
9163 sf.strHostPath,
9164 RT_BOOL(sf.fWritable),
9165 RT_BOOL(sf.fAutoMount),
9166 false /* fFailOnError */);
9167 if (FAILED(rc)) return rc;
9168 mHWData->mSharedFolders.push_back(sharedFolder);
9169 }
9170
9171 // Clipboard
9172 mHWData->mClipboardMode = data.clipboardMode;
9173
9174 // drag'n'drop
9175 mHWData->mDnDMode = data.dndMode;
9176
9177 // guest settings
9178 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
9179
9180 // IO settings
9181 mHWData->mIOCacheEnabled = data.ioSettings.fIOCacheEnabled;
9182 mHWData->mIOCacheSize = data.ioSettings.ulIOCacheSize;
9183
9184 // Host PCI devices
9185 for (settings::HostPCIDeviceAttachmentList::const_iterator
9186 it = data.pciAttachments.begin();
9187 it != data.pciAttachments.end();
9188 ++it)
9189 {
9190 const settings::HostPCIDeviceAttachment &hpda = *it;
9191 ComObjPtr<PCIDeviceAttachment> pda;
9192
9193 pda.createObject();
9194 pda->i_loadSettings(this, hpda);
9195 mHWData->mPCIDeviceAssignments.push_back(pda);
9196 }
9197
9198 /*
9199 * (The following isn't really real hardware, but it lives in HWData
9200 * for reasons of convenience.)
9201 */
9202
9203#ifdef VBOX_WITH_GUEST_PROPS
9204 /* Guest properties (optional) */
9205
9206 /* Only load transient guest properties for configs which have saved
9207 * state, because there shouldn't be any for powered off VMs. The same
9208 * logic applies for snapshots, as offline snapshots shouldn't have
9209 * any such properties. They confuse the code in various places.
9210 * Note: can't rely on the machine state, as it isn't set yet. */
9211 bool fSkipTransientGuestProperties = mSSData->strStateFilePath.isEmpty();
9212 /* apologies for the hacky unconst() usage, but this needs hacking
9213 * actually inconsistent settings into consistency, otherwise there
9214 * will be some corner cases where the inconsistency survives
9215 * surprisingly long without getting fixed, especially for snapshots
9216 * as there are no config changes. */
9217 settings::GuestPropertiesList &llGuestProperties = unconst(data.llGuestProperties);
9218 for (settings::GuestPropertiesList::iterator
9219 it = llGuestProperties.begin();
9220 it != llGuestProperties.end();
9221 /*nothing*/)
9222 {
9223 const settings::GuestProperty &prop = *it;
9224 uint32_t fFlags = guestProp::NILFLAG;
9225 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
9226 if ( fSkipTransientGuestProperties
9227 && ( fFlags & guestProp::TRANSIENT
9228 || fFlags & guestProp::TRANSRESET))
9229 {
9230 it = llGuestProperties.erase(it);
9231 continue;
9232 }
9233 HWData::GuestProperty property = { prop.strValue, (LONG64) prop.timestamp, fFlags };
9234 mHWData->mGuestProperties[prop.strName] = property;
9235 ++it;
9236 }
9237#endif /* VBOX_WITH_GUEST_PROPS defined */
9238
9239 rc = i_loadDebugging(pDbg);
9240 if (FAILED(rc))
9241 return rc;
9242
9243 mHWData->mAutostart = *pAutostart;
9244
9245 /* default frontend */
9246 mHWData->mDefaultFrontend = data.strDefaultFrontend;
9247 }
9248 catch (std::bad_alloc &)
9249 {
9250 return E_OUTOFMEMORY;
9251 }
9252
9253 AssertComRC(rc);
9254 return rc;
9255}
9256
9257/**
9258 * Called from i_loadHardware() to load the debugging settings of the
9259 * machine.
9260 *
9261 * @param pDbg Pointer to the settings.
9262 */
9263HRESULT Machine::i_loadDebugging(const settings::Debugging *pDbg)
9264{
9265 mHWData->mDebugging = *pDbg;
9266 /* no more processing currently required, this will probably change. */
9267 return S_OK;
9268}
9269
9270/**
9271 * Called from i_loadMachineDataFromSettings() for the storage controller data, including media.
9272 *
9273 * @param data storage settings.
9274 * @param puuidRegistry media registry ID to set media to or NULL;
9275 * see Machine::i_loadMachineDataFromSettings()
9276 * @param puuidSnapshot snapshot ID
9277 * @return
9278 */
9279HRESULT Machine::i_loadStorageControllers(const settings::Storage &data,
9280 const Guid *puuidRegistry,
9281 const Guid *puuidSnapshot)
9282{
9283 AssertReturn(!i_isSessionMachine(), E_FAIL);
9284
9285 HRESULT rc = S_OK;
9286
9287 for (settings::StorageControllersList::const_iterator
9288 it = data.llStorageControllers.begin();
9289 it != data.llStorageControllers.end();
9290 ++it)
9291 {
9292 const settings::StorageController &ctlData = *it;
9293
9294 ComObjPtr<StorageController> pCtl;
9295 /* Try to find one with the name first. */
9296 rc = i_getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
9297 if (SUCCEEDED(rc))
9298 return setError(VBOX_E_OBJECT_IN_USE,
9299 tr("Storage controller named '%s' already exists"),
9300 ctlData.strName.c_str());
9301
9302 pCtl.createObject();
9303 rc = pCtl->init(this,
9304 ctlData.strName,
9305 ctlData.storageBus,
9306 ctlData.ulInstance,
9307 ctlData.fBootable);
9308 if (FAILED(rc)) return rc;
9309
9310 mStorageControllers->push_back(pCtl);
9311
9312 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
9313 if (FAILED(rc)) return rc;
9314
9315 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
9316 if (FAILED(rc)) return rc;
9317
9318 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
9319 if (FAILED(rc)) return rc;
9320
9321 /* Load the attached devices now. */
9322 rc = i_loadStorageDevices(pCtl,
9323 ctlData,
9324 puuidRegistry,
9325 puuidSnapshot);
9326 if (FAILED(rc)) return rc;
9327 }
9328
9329 return S_OK;
9330}
9331
9332/**
9333 * Called from i_loadStorageControllers for a controller's devices.
9334 *
9335 * @param aStorageController
9336 * @param data
9337 * @param puuidRegistry media registry ID to set media to or NULL; see
9338 * Machine::i_loadMachineDataFromSettings()
9339 * @param puuidSnapshot pointer to the snapshot ID if this is a snapshot machine
9340 * @return
9341 */
9342HRESULT Machine::i_loadStorageDevices(StorageController *aStorageController,
9343 const settings::StorageController &data,
9344 const Guid *puuidRegistry,
9345 const Guid *puuidSnapshot)
9346{
9347 HRESULT rc = S_OK;
9348
9349 /* paranoia: detect duplicate attachments */
9350 for (settings::AttachedDevicesList::const_iterator
9351 it = data.llAttachedDevices.begin();
9352 it != data.llAttachedDevices.end();
9353 ++it)
9354 {
9355 const settings::AttachedDevice &ad = *it;
9356
9357 for (settings::AttachedDevicesList::const_iterator it2 = it;
9358 it2 != data.llAttachedDevices.end();
9359 ++it2)
9360 {
9361 if (it == it2)
9362 continue;
9363
9364 const settings::AttachedDevice &ad2 = *it2;
9365
9366 if ( ad.lPort == ad2.lPort
9367 && ad.lDevice == ad2.lDevice)
9368 {
9369 return setError(E_FAIL,
9370 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
9371 aStorageController->i_getName().c_str(),
9372 ad.lPort,
9373 ad.lDevice,
9374 mUserData->s.strName.c_str());
9375 }
9376 }
9377 }
9378
9379 for (settings::AttachedDevicesList::const_iterator
9380 it = data.llAttachedDevices.begin();
9381 it != data.llAttachedDevices.end();
9382 ++it)
9383 {
9384 const settings::AttachedDevice &dev = *it;
9385 ComObjPtr<Medium> medium;
9386
9387 switch (dev.deviceType)
9388 {
9389 case DeviceType_Floppy:
9390 case DeviceType_DVD:
9391 if (dev.strHostDriveSrc.isNotEmpty())
9392 rc = mParent->i_host()->i_findHostDriveByName(dev.deviceType, dev.strHostDriveSrc,
9393 false /* fRefresh */, medium);
9394 else
9395 rc = mParent->i_findRemoveableMedium(dev.deviceType,
9396 dev.uuid,
9397 false /* fRefresh */,
9398 false /* aSetError */,
9399 medium);
9400 if (rc == VBOX_E_OBJECT_NOT_FOUND)
9401 // This is not an error. The host drive or UUID might have vanished, so just go
9402 // ahead without this removeable medium attachment
9403 rc = S_OK;
9404 break;
9405
9406 case DeviceType_HardDisk:
9407 {
9408 /* find a hard disk by UUID */
9409 rc = mParent->i_findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
9410 if (FAILED(rc))
9411 {
9412 if (i_isSnapshotMachine())
9413 {
9414 // wrap another error message around the "cannot find hard disk" set by findHardDisk
9415 // so the user knows that the bad disk is in a snapshot somewhere
9416 com::ErrorInfo info;
9417 return setError(E_FAIL,
9418 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
9419 puuidSnapshot->raw(),
9420 info.getText().raw());
9421 }
9422 else
9423 return rc;
9424 }
9425
9426 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
9427
9428 if (medium->i_getType() == MediumType_Immutable)
9429 {
9430 if (i_isSnapshotMachine())
9431 return setError(E_FAIL,
9432 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9433 "of the virtual machine '%s' ('%s')"),
9434 medium->i_getLocationFull().c_str(),
9435 dev.uuid.raw(),
9436 puuidSnapshot->raw(),
9437 mUserData->s.strName.c_str(),
9438 mData->m_strConfigFileFull.c_str());
9439
9440 return setError(E_FAIL,
9441 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9442 medium->i_getLocationFull().c_str(),
9443 dev.uuid.raw(),
9444 mUserData->s.strName.c_str(),
9445 mData->m_strConfigFileFull.c_str());
9446 }
9447
9448 if (medium->i_getType() == MediumType_MultiAttach)
9449 {
9450 if (i_isSnapshotMachine())
9451 return setError(E_FAIL,
9452 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9453 "of the virtual machine '%s' ('%s')"),
9454 medium->i_getLocationFull().c_str(),
9455 dev.uuid.raw(),
9456 puuidSnapshot->raw(),
9457 mUserData->s.strName.c_str(),
9458 mData->m_strConfigFileFull.c_str());
9459
9460 return setError(E_FAIL,
9461 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9462 medium->i_getLocationFull().c_str(),
9463 dev.uuid.raw(),
9464 mUserData->s.strName.c_str(),
9465 mData->m_strConfigFileFull.c_str());
9466 }
9467
9468 if ( !i_isSnapshotMachine()
9469 && medium->i_getChildren().size() != 0
9470 )
9471 return setError(E_FAIL,
9472 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
9473 "because it has %d differencing child hard disks"),
9474 medium->i_getLocationFull().c_str(),
9475 dev.uuid.raw(),
9476 mUserData->s.strName.c_str(),
9477 mData->m_strConfigFileFull.c_str(),
9478 medium->i_getChildren().size());
9479
9480 if (i_findAttachment(*mMediumAttachments.data(),
9481 medium))
9482 return setError(E_FAIL,
9483 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
9484 medium->i_getLocationFull().c_str(),
9485 dev.uuid.raw(),
9486 mUserData->s.strName.c_str(),
9487 mData->m_strConfigFileFull.c_str());
9488
9489 break;
9490 }
9491
9492 default:
9493 return setError(E_FAIL,
9494 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
9495 medium->i_getLocationFull().c_str(),
9496 mUserData->s.strName.c_str(),
9497 mData->m_strConfigFileFull.c_str());
9498 }
9499
9500 if (FAILED(rc))
9501 break;
9502
9503 /* Bandwidth groups are loaded at this point. */
9504 ComObjPtr<BandwidthGroup> pBwGroup;
9505
9506 if (!dev.strBwGroup.isEmpty())
9507 {
9508 rc = mBandwidthControl->i_getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
9509 if (FAILED(rc))
9510 return setError(E_FAIL,
9511 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
9512 medium->i_getLocationFull().c_str(),
9513 dev.strBwGroup.c_str(),
9514 mUserData->s.strName.c_str(),
9515 mData->m_strConfigFileFull.c_str());
9516 pBwGroup->i_reference();
9517 }
9518
9519 const Utf8Str controllerName = aStorageController->i_getName();
9520 ComObjPtr<MediumAttachment> pAttachment;
9521 pAttachment.createObject();
9522 rc = pAttachment->init(this,
9523 medium,
9524 controllerName,
9525 dev.lPort,
9526 dev.lDevice,
9527 dev.deviceType,
9528 false,
9529 dev.fPassThrough,
9530 dev.fTempEject,
9531 dev.fNonRotational,
9532 dev.fDiscard,
9533 dev.fHotPluggable,
9534 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->i_getName());
9535 if (FAILED(rc)) break;
9536
9537 /* associate the medium with this machine and snapshot */
9538 if (!medium.isNull())
9539 {
9540 AutoCaller medCaller(medium);
9541 if (FAILED(medCaller.rc())) return medCaller.rc();
9542 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
9543
9544 if (i_isSnapshotMachine())
9545 rc = medium->i_addBackReference(mData->mUuid, *puuidSnapshot);
9546 else
9547 rc = medium->i_addBackReference(mData->mUuid);
9548 /* If the medium->addBackReference fails it sets an appropriate
9549 * error message, so no need to do any guesswork here. */
9550
9551 if (puuidRegistry)
9552 // caller wants registry ID to be set on all attached media (OVF import case)
9553 medium->i_addRegistry(*puuidRegistry);
9554 }
9555
9556 if (FAILED(rc))
9557 break;
9558
9559 /* back up mMediumAttachments to let registeredInit() properly rollback
9560 * on failure (= limited accessibility) */
9561 i_setModified(IsModified_Storage);
9562 mMediumAttachments.backup();
9563 mMediumAttachments->push_back(pAttachment);
9564 }
9565
9566 return rc;
9567}
9568
9569/**
9570 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
9571 *
9572 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
9573 * @param aSnapshot where to return the found snapshot
9574 * @param aSetError true to set extended error info on failure
9575 */
9576HRESULT Machine::i_findSnapshotById(const Guid &aId,
9577 ComObjPtr<Snapshot> &aSnapshot,
9578 bool aSetError /* = false */)
9579{
9580 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9581
9582 if (!mData->mFirstSnapshot)
9583 {
9584 if (aSetError)
9585 return setError(E_FAIL, tr("This machine does not have any snapshots"));
9586 return E_FAIL;
9587 }
9588
9589 if (aId.isZero())
9590 aSnapshot = mData->mFirstSnapshot;
9591 else
9592 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(aId.ref());
9593
9594 if (!aSnapshot)
9595 {
9596 if (aSetError)
9597 return setError(E_FAIL,
9598 tr("Could not find a snapshot with UUID {%s}"),
9599 aId.toString().c_str());
9600 return E_FAIL;
9601 }
9602
9603 return S_OK;
9604}
9605
9606/**
9607 * Returns the snapshot with the given name or fails of no such snapshot.
9608 *
9609 * @param strName snapshot name to find
9610 * @param aSnapshot where to return the found snapshot
9611 * @param aSetError true to set extended error info on failure
9612 */
9613HRESULT Machine::i_findSnapshotByName(const Utf8Str &strName,
9614 ComObjPtr<Snapshot> &aSnapshot,
9615 bool aSetError /* = false */)
9616{
9617 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
9618
9619 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9620
9621 if (!mData->mFirstSnapshot)
9622 {
9623 if (aSetError)
9624 return setError(VBOX_E_OBJECT_NOT_FOUND,
9625 tr("This machine does not have any snapshots"));
9626 return VBOX_E_OBJECT_NOT_FOUND;
9627 }
9628
9629 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(strName);
9630
9631 if (!aSnapshot)
9632 {
9633 if (aSetError)
9634 return setError(VBOX_E_OBJECT_NOT_FOUND,
9635 tr("Could not find a snapshot named '%s'"), strName.c_str());
9636 return VBOX_E_OBJECT_NOT_FOUND;
9637 }
9638
9639 return S_OK;
9640}
9641
9642/**
9643 * Returns a storage controller object with the given name.
9644 *
9645 * @param aName storage controller name to find
9646 * @param aStorageController where to return the found storage controller
9647 * @param aSetError true to set extended error info on failure
9648 */
9649HRESULT Machine::i_getStorageControllerByName(const Utf8Str &aName,
9650 ComObjPtr<StorageController> &aStorageController,
9651 bool aSetError /* = false */)
9652{
9653 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9654
9655 for (StorageControllerList::const_iterator
9656 it = mStorageControllers->begin();
9657 it != mStorageControllers->end();
9658 ++it)
9659 {
9660 if ((*it)->i_getName() == aName)
9661 {
9662 aStorageController = (*it);
9663 return S_OK;
9664 }
9665 }
9666
9667 if (aSetError)
9668 return setError(VBOX_E_OBJECT_NOT_FOUND,
9669 tr("Could not find a storage controller named '%s'"),
9670 aName.c_str());
9671 return VBOX_E_OBJECT_NOT_FOUND;
9672}
9673
9674/**
9675 * Returns a USB controller object with the given name.
9676 *
9677 * @param aName USB controller name to find
9678 * @param aUSBController where to return the found USB controller
9679 * @param aSetError true to set extended error info on failure
9680 */
9681HRESULT Machine::i_getUSBControllerByName(const Utf8Str &aName,
9682 ComObjPtr<USBController> &aUSBController,
9683 bool aSetError /* = false */)
9684{
9685 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9686
9687 for (USBControllerList::const_iterator
9688 it = mUSBControllers->begin();
9689 it != mUSBControllers->end();
9690 ++it)
9691 {
9692 if ((*it)->i_getName() == aName)
9693 {
9694 aUSBController = (*it);
9695 return S_OK;
9696 }
9697 }
9698
9699 if (aSetError)
9700 return setError(VBOX_E_OBJECT_NOT_FOUND,
9701 tr("Could not find a storage controller named '%s'"),
9702 aName.c_str());
9703 return VBOX_E_OBJECT_NOT_FOUND;
9704}
9705
9706/**
9707 * Returns the number of USB controller instance of the given type.
9708 *
9709 * @param enmType USB controller type.
9710 */
9711ULONG Machine::i_getUSBControllerCountByType(USBControllerType_T enmType)
9712{
9713 ULONG cCtrls = 0;
9714
9715 for (USBControllerList::const_iterator
9716 it = mUSBControllers->begin();
9717 it != mUSBControllers->end();
9718 ++it)
9719 {
9720 if ((*it)->i_getControllerType() == enmType)
9721 cCtrls++;
9722 }
9723
9724 return cCtrls;
9725}
9726
9727HRESULT Machine::i_getMediumAttachmentsOfController(const Utf8Str &aName,
9728 MediumAttachmentList &atts)
9729{
9730 AutoCaller autoCaller(this);
9731 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9732
9733 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9734
9735 for (MediumAttachmentList::const_iterator
9736 it = mMediumAttachments->begin();
9737 it != mMediumAttachments->end();
9738 ++it)
9739 {
9740 const ComObjPtr<MediumAttachment> &pAtt = *it;
9741 // should never happen, but deal with NULL pointers in the list.
9742 AssertContinue(!pAtt.isNull());
9743
9744 // getControllerName() needs caller+read lock
9745 AutoCaller autoAttCaller(pAtt);
9746 if (FAILED(autoAttCaller.rc()))
9747 {
9748 atts.clear();
9749 return autoAttCaller.rc();
9750 }
9751 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
9752
9753 if (pAtt->i_getControllerName() == aName)
9754 atts.push_back(pAtt);
9755 }
9756
9757 return S_OK;
9758}
9759
9760
9761/**
9762 * Helper for #i_saveSettings. Cares about renaming the settings directory and
9763 * file if the machine name was changed and about creating a new settings file
9764 * if this is a new machine.
9765 *
9766 * @note Must be never called directly but only from #saveSettings().
9767 */
9768HRESULT Machine::i_prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
9769{
9770 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9771
9772 HRESULT rc = S_OK;
9773
9774 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
9775
9776 /// @todo need to handle primary group change, too
9777
9778 /* attempt to rename the settings file if machine name is changed */
9779 if ( mUserData->s.fNameSync
9780 && mUserData.isBackedUp()
9781 && ( mUserData.backedUpData()->s.strName != mUserData->s.strName
9782 || mUserData.backedUpData()->s.llGroups.front() != mUserData->s.llGroups.front())
9783 )
9784 {
9785 bool dirRenamed = false;
9786 bool fileRenamed = false;
9787
9788 Utf8Str configFile, newConfigFile;
9789 Utf8Str configFilePrev, newConfigFilePrev;
9790 Utf8Str configDir, newConfigDir;
9791
9792 do
9793 {
9794 int vrc = VINF_SUCCESS;
9795
9796 Utf8Str name = mUserData.backedUpData()->s.strName;
9797 Utf8Str newName = mUserData->s.strName;
9798 Utf8Str group = mUserData.backedUpData()->s.llGroups.front();
9799 if (group == "/")
9800 group.setNull();
9801 Utf8Str newGroup = mUserData->s.llGroups.front();
9802 if (newGroup == "/")
9803 newGroup.setNull();
9804
9805 configFile = mData->m_strConfigFileFull;
9806
9807 /* first, rename the directory if it matches the group and machine name */
9808 Utf8Str groupPlusName = Utf8StrFmt("%s%c%s",
9809 group.c_str(), RTPATH_DELIMITER, name.c_str());
9810 /** @todo hack, make somehow use of ComposeMachineFilename */
9811 if (mUserData->s.fDirectoryIncludesUUID)
9812 groupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9813 Utf8Str newGroupPlusName = Utf8StrFmt("%s%c%s",
9814 newGroup.c_str(), RTPATH_DELIMITER, newName.c_str());
9815 /** @todo hack, make somehow use of ComposeMachineFilename */
9816 if (mUserData->s.fDirectoryIncludesUUID)
9817 newGroupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9818 configDir = configFile;
9819 configDir.stripFilename();
9820 newConfigDir = configDir;
9821 if ( configDir.length() >= groupPlusName.length()
9822 && !RTPathCompare(configDir.substr(configDir.length() - groupPlusName.length(), groupPlusName.length()).c_str(),
9823 groupPlusName.c_str()))
9824 {
9825 newConfigDir = newConfigDir.substr(0, configDir.length() - groupPlusName.length());
9826 Utf8Str newConfigBaseDir(newConfigDir);
9827 newConfigDir.append(newGroupPlusName);
9828 /* consistency: use \ if appropriate on the platform */
9829 RTPathChangeToDosSlashes(newConfigDir.mutableRaw(), false);
9830 /* new dir and old dir cannot be equal here because of 'if'
9831 * above and because name != newName */
9832 Assert(configDir != newConfigDir);
9833 if (!fSettingsFileIsNew)
9834 {
9835 /* perform real rename only if the machine is not new */
9836 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9837 if ( vrc == VERR_FILE_NOT_FOUND
9838 || vrc == VERR_PATH_NOT_FOUND)
9839 {
9840 /* create the parent directory, then retry renaming */
9841 Utf8Str parent(newConfigDir);
9842 parent.stripFilename();
9843 (void)RTDirCreateFullPath(parent.c_str(), 0700);
9844 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9845 }
9846 if (RT_FAILURE(vrc))
9847 {
9848 rc = setError(E_FAIL,
9849 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
9850 configDir.c_str(),
9851 newConfigDir.c_str(),
9852 vrc);
9853 break;
9854 }
9855 /* delete subdirectories which are no longer needed */
9856 Utf8Str dir(configDir);
9857 dir.stripFilename();
9858 while (dir != newConfigBaseDir && dir != ".")
9859 {
9860 vrc = RTDirRemove(dir.c_str());
9861 if (RT_FAILURE(vrc))
9862 break;
9863 dir.stripFilename();
9864 }
9865 dirRenamed = true;
9866 }
9867 }
9868
9869 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
9870 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
9871
9872 /* then try to rename the settings file itself */
9873 if (newConfigFile != configFile)
9874 {
9875 /* get the path to old settings file in renamed directory */
9876 configFile = Utf8StrFmt("%s%c%s",
9877 newConfigDir.c_str(),
9878 RTPATH_DELIMITER,
9879 RTPathFilename(configFile.c_str()));
9880 if (!fSettingsFileIsNew)
9881 {
9882 /* perform real rename only if the machine is not new */
9883 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
9884 if (RT_FAILURE(vrc))
9885 {
9886 rc = setError(E_FAIL,
9887 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
9888 configFile.c_str(),
9889 newConfigFile.c_str(),
9890 vrc);
9891 break;
9892 }
9893 fileRenamed = true;
9894 configFilePrev = configFile;
9895 configFilePrev += "-prev";
9896 newConfigFilePrev = newConfigFile;
9897 newConfigFilePrev += "-prev";
9898 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
9899 }
9900 }
9901
9902 // update m_strConfigFileFull amd mConfigFile
9903 mData->m_strConfigFileFull = newConfigFile;
9904 // compute the relative path too
9905 mParent->i_copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
9906
9907 // store the old and new so that VirtualBox::i_saveSettings() can update
9908 // the media registry
9909 if ( mData->mRegistered
9910 && (configDir != newConfigDir || configFile != newConfigFile))
9911 {
9912 mParent->i_rememberMachineNameChangeForMedia(configDir, newConfigDir);
9913
9914 if (pfNeedsGlobalSaveSettings)
9915 *pfNeedsGlobalSaveSettings = true;
9916 }
9917
9918 // in the saved state file path, replace the old directory with the new directory
9919 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
9920 {
9921 Utf8Str strStateFileName = mSSData->strStateFilePath.c_str() + configDir.length();
9922 mSSData->strStateFilePath = newConfigDir + strStateFileName;
9923 }
9924
9925 // and do the same thing for the saved state file paths of all the online snapshots
9926 if (mData->mFirstSnapshot)
9927 mData->mFirstSnapshot->i_updateSavedStatePaths(configDir.c_str(),
9928 newConfigDir.c_str());
9929 }
9930 while (0);
9931
9932 if (FAILED(rc))
9933 {
9934 /* silently try to rename everything back */
9935 if (fileRenamed)
9936 {
9937 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
9938 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
9939 }
9940 if (dirRenamed)
9941 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
9942 }
9943
9944 if (FAILED(rc)) return rc;
9945 }
9946
9947 if (fSettingsFileIsNew)
9948 {
9949 /* create a virgin config file */
9950 int vrc = VINF_SUCCESS;
9951
9952 /* ensure the settings directory exists */
9953 Utf8Str path(mData->m_strConfigFileFull);
9954 path.stripFilename();
9955 if (!RTDirExists(path.c_str()))
9956 {
9957 vrc = RTDirCreateFullPath(path.c_str(), 0700);
9958 if (RT_FAILURE(vrc))
9959 {
9960 return setError(E_FAIL,
9961 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
9962 path.c_str(),
9963 vrc);
9964 }
9965 }
9966
9967 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
9968 path = Utf8Str(mData->m_strConfigFileFull);
9969 RTFILE f = NIL_RTFILE;
9970 vrc = RTFileOpen(&f, path.c_str(),
9971 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
9972 if (RT_FAILURE(vrc))
9973 return setError(E_FAIL,
9974 tr("Could not create the settings file '%s' (%Rrc)"),
9975 path.c_str(),
9976 vrc);
9977 RTFileClose(f);
9978 }
9979
9980 return rc;
9981}
9982
9983/**
9984 * Saves and commits machine data, user data and hardware data.
9985 *
9986 * Note that on failure, the data remains uncommitted.
9987 *
9988 * @a aFlags may combine the following flags:
9989 *
9990 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
9991 * Used when saving settings after an operation that makes them 100%
9992 * correspond to the settings from the current snapshot.
9993 * - SaveS_Force: settings will be saved without doing a deep compare of the
9994 * settings structures. This is used when this is called because snapshots
9995 * have changed to avoid the overhead of the deep compare.
9996 *
9997 * @note Must be called from under this object's write lock. Locks children for
9998 * writing.
9999 *
10000 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
10001 * initialized to false and that will be set to true by this function if
10002 * the caller must invoke VirtualBox::i_saveSettings() because the global
10003 * settings have changed. This will happen if a machine rename has been
10004 * saved and the global machine and media registries will therefore need
10005 * updating.
10006 * @param aFlags Flags.
10007 */
10008HRESULT Machine::i_saveSettings(bool *pfNeedsGlobalSaveSettings,
10009 int aFlags /*= 0*/)
10010{
10011 LogFlowThisFuncEnter();
10012
10013 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10014
10015 /* make sure child objects are unable to modify the settings while we are
10016 * saving them */
10017 i_ensureNoStateDependencies();
10018
10019 AssertReturn(!i_isSnapshotMachine(),
10020 E_FAIL);
10021
10022 HRESULT rc = S_OK;
10023 bool fNeedsWrite = false;
10024
10025 /* First, prepare to save settings. It will care about renaming the
10026 * settings directory and file if the machine name was changed and about
10027 * creating a new settings file if this is a new machine. */
10028 rc = i_prepareSaveSettings(pfNeedsGlobalSaveSettings);
10029 if (FAILED(rc)) return rc;
10030
10031 // keep a pointer to the current settings structures
10032 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
10033 settings::MachineConfigFile *pNewConfig = NULL;
10034
10035 try
10036 {
10037 // make a fresh one to have everyone write stuff into
10038 pNewConfig = new settings::MachineConfigFile(NULL);
10039 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
10040
10041 // now go and copy all the settings data from COM to the settings structures
10042 // (this calls i_saveSettings() on all the COM objects in the machine)
10043 i_copyMachineDataToSettings(*pNewConfig);
10044
10045 if (aFlags & SaveS_ResetCurStateModified)
10046 {
10047 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
10048 mData->mCurrentStateModified = FALSE;
10049 fNeedsWrite = true; // always, no need to compare
10050 }
10051 else if (aFlags & SaveS_Force)
10052 {
10053 fNeedsWrite = true; // always, no need to compare
10054 }
10055 else
10056 {
10057 if (!mData->mCurrentStateModified)
10058 {
10059 // do a deep compare of the settings that we just saved with the settings
10060 // previously stored in the config file; this invokes MachineConfigFile::operator==
10061 // which does a deep compare of all the settings, which is expensive but less expensive
10062 // than writing out XML in vain
10063 bool fAnySettingsChanged = !(*pNewConfig == *pOldConfig);
10064
10065 // could still be modified if any settings changed
10066 mData->mCurrentStateModified = fAnySettingsChanged;
10067
10068 fNeedsWrite = fAnySettingsChanged;
10069 }
10070 else
10071 fNeedsWrite = true;
10072 }
10073
10074 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
10075
10076 if (fNeedsWrite)
10077 // now spit it all out!
10078 pNewConfig->write(mData->m_strConfigFileFull);
10079
10080 mData->pMachineConfigFile = pNewConfig;
10081 delete pOldConfig;
10082 i_commit();
10083
10084 // after saving settings, we are no longer different from the XML on disk
10085 mData->flModifications = 0;
10086 }
10087 catch (HRESULT err)
10088 {
10089 // we assume that error info is set by the thrower
10090 rc = err;
10091
10092 // restore old config
10093 delete pNewConfig;
10094 mData->pMachineConfigFile = pOldConfig;
10095 }
10096 catch (...)
10097 {
10098 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10099 }
10100
10101 if (fNeedsWrite)
10102 {
10103 /* Fire the data change event, even on failure (since we've already
10104 * committed all data). This is done only for SessionMachines because
10105 * mutable Machine instances are always not registered (i.e. private
10106 * to the client process that creates them) and thus don't need to
10107 * inform callbacks. */
10108 if (i_isSessionMachine())
10109 mParent->i_onMachineDataChange(mData->mUuid);
10110 }
10111
10112 LogFlowThisFunc(("rc=%08X\n", rc));
10113 LogFlowThisFuncLeave();
10114 return rc;
10115}
10116
10117/**
10118 * Implementation for saving the machine settings into the given
10119 * settings::MachineConfigFile instance. This copies machine extradata
10120 * from the previous machine config file in the instance data, if any.
10121 *
10122 * This gets called from two locations:
10123 *
10124 * -- Machine::i_saveSettings(), during the regular XML writing;
10125 *
10126 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
10127 * exported to OVF and we write the VirtualBox proprietary XML
10128 * into a <vbox:Machine> tag.
10129 *
10130 * This routine fills all the fields in there, including snapshots, *except*
10131 * for the following:
10132 *
10133 * -- fCurrentStateModified. There is some special logic associated with that.
10134 *
10135 * The caller can then call MachineConfigFile::write() or do something else
10136 * with it.
10137 *
10138 * Caller must hold the machine lock!
10139 *
10140 * This throws XML errors and HRESULT, so the caller must have a catch block!
10141 */
10142void Machine::i_copyMachineDataToSettings(settings::MachineConfigFile &config)
10143{
10144 // deep copy extradata, being extra careful with self assignment (the STL
10145 // map assignment on Mac OS X clang based Xcode isn't checking)
10146 if (&config != mData->pMachineConfigFile)
10147 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
10148
10149 config.uuid = mData->mUuid;
10150
10151 // copy name, description, OS type, teleport, UTC etc.
10152 config.machineUserData = mUserData->s;
10153
10154 if ( mData->mMachineState == MachineState_Saved
10155 || mData->mMachineState == MachineState_Restoring
10156 // when doing certain snapshot operations we may or may not have
10157 // a saved state in the current state, so keep everything as is
10158 || ( ( mData->mMachineState == MachineState_Snapshotting
10159 || mData->mMachineState == MachineState_DeletingSnapshot
10160 || mData->mMachineState == MachineState_RestoringSnapshot)
10161 && (!mSSData->strStateFilePath.isEmpty())
10162 )
10163 )
10164 {
10165 Assert(!mSSData->strStateFilePath.isEmpty());
10166 /* try to make the file name relative to the settings file dir */
10167 i_copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
10168 }
10169 else
10170 {
10171 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
10172 config.strStateFile.setNull();
10173 }
10174
10175 if (mData->mCurrentSnapshot)
10176 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->i_getId();
10177 else
10178 config.uuidCurrentSnapshot.clear();
10179
10180 config.timeLastStateChange = mData->mLastStateChange;
10181 config.fAborted = (mData->mMachineState == MachineState_Aborted);
10182 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
10183
10184 HRESULT rc = i_saveHardware(config.hardwareMachine, &config.debugging, &config.autostart);
10185 if (FAILED(rc)) throw rc;
10186
10187 // save machine's media registry if this is VirtualBox 4.0 or later
10188 if (config.canHaveOwnMediaRegistry())
10189 {
10190 // determine machine folder
10191 Utf8Str strMachineFolder = i_getSettingsFileFull();
10192 strMachineFolder.stripFilename();
10193 mParent->i_saveMediaRegistry(config.mediaRegistry,
10194 i_getId(), // only media with registry ID == machine UUID
10195 strMachineFolder);
10196 // this throws HRESULT
10197 }
10198
10199 // save snapshots
10200 rc = i_saveAllSnapshots(config);
10201 if (FAILED(rc)) throw rc;
10202}
10203
10204/**
10205 * Saves all snapshots of the machine into the given machine config file. Called
10206 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
10207 * @param config
10208 * @return
10209 */
10210HRESULT Machine::i_saveAllSnapshots(settings::MachineConfigFile &config)
10211{
10212 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10213
10214 HRESULT rc = S_OK;
10215
10216 try
10217 {
10218 config.llFirstSnapshot.clear();
10219
10220 if (mData->mFirstSnapshot)
10221 {
10222 // the settings use a list for "the first snapshot"
10223 config.llFirstSnapshot.push_back(settings::Snapshot::Empty);
10224
10225 // get reference to the snapshot on the list and work on that
10226 // element straight in the list to avoid excessive copying later
10227 rc = mData->mFirstSnapshot->i_saveSnapshot(config.llFirstSnapshot.back());
10228 if (FAILED(rc)) throw rc;
10229 }
10230
10231// if (mType == IsSessionMachine)
10232// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
10233
10234 }
10235 catch (HRESULT err)
10236 {
10237 /* we assume that error info is set by the thrower */
10238 rc = err;
10239 }
10240 catch (...)
10241 {
10242 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10243 }
10244
10245 return rc;
10246}
10247
10248/**
10249 * Saves the VM hardware configuration. It is assumed that the
10250 * given node is empty.
10251 *
10252 * @param data Reference to the settings object for the hardware config.
10253 * @param pDbg Pointer to the settings object for the debugging config
10254 * which happens to live in mHWData.
10255 * @param pAutostart Pointer to the settings object for the autostart config
10256 * which happens to live in mHWData.
10257 */
10258HRESULT Machine::i_saveHardware(settings::Hardware &data, settings::Debugging *pDbg,
10259 settings::Autostart *pAutostart)
10260{
10261 HRESULT rc = S_OK;
10262
10263 try
10264 {
10265 /* The hardware version attribute (optional).
10266 Automatically upgrade from 1 to current default hardware version
10267 when there is no saved state. (ugly!) */
10268 if ( mHWData->mHWVersion == "1"
10269 && mSSData->strStateFilePath.isEmpty()
10270 )
10271 mHWData->mHWVersion = Utf8StrFmt("%d", SchemaDefs::DefaultHardwareVersion);
10272
10273 data.strVersion = mHWData->mHWVersion;
10274 data.uuid = mHWData->mHardwareUUID;
10275
10276 // CPU
10277 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
10278 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
10279 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
10280 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
10281 data.fUnrestrictedExecution = !!mHWData->mHWVirtExUXEnabled;
10282 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
10283 data.fPAE = !!mHWData->mPAEEnabled;
10284 data.enmLongMode = mHWData->mLongMode;
10285 data.fTripleFaultReset = !!mHWData->mTripleFaultReset;
10286 data.fAPIC = !!mHWData->mAPIC;
10287 data.fX2APIC = !!mHWData->mX2APIC;
10288 data.cCPUs = mHWData->mCPUCount;
10289 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
10290 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
10291 data.uCpuIdPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
10292 data.strCpuProfile = mHWData->mCpuProfile;
10293
10294 data.llCpus.clear();
10295 if (data.fCpuHotPlug)
10296 {
10297 for (unsigned idx = 0; idx < data.cCPUs; ++idx)
10298 {
10299 if (mHWData->mCPUAttached[idx])
10300 {
10301 settings::Cpu cpu;
10302 cpu.ulId = idx;
10303 data.llCpus.push_back(cpu);
10304 }
10305 }
10306 }
10307
10308 /* Standard and Extended CPUID leafs. */
10309 data.llCpuIdLeafs.clear();
10310 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++idx)
10311 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
10312 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
10313 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++idx)
10314 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
10315 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
10316
10317 // memory
10318 data.ulMemorySizeMB = mHWData->mMemorySize;
10319 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
10320
10321 // firmware
10322 data.firmwareType = mHWData->mFirmwareType;
10323
10324 // HID
10325 data.pointingHIDType = mHWData->mPointingHIDType;
10326 data.keyboardHIDType = mHWData->mKeyboardHIDType;
10327
10328 // chipset
10329 data.chipsetType = mHWData->mChipsetType;
10330
10331 // paravirt
10332 data.paravirtProvider = mHWData->mParavirtProvider;
10333 data.strParavirtDebug = mHWData->mParavirtDebug;
10334
10335 // emulated USB card reader
10336 data.fEmulatedUSBCardReader = !!mHWData->mEmulatedUSBCardReaderEnabled;
10337
10338 // HPET
10339 data.fHPETEnabled = !!mHWData->mHPETEnabled;
10340
10341 // boot order
10342 data.mapBootOrder.clear();
10343 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
10344 data.mapBootOrder[i] = mHWData->mBootOrder[i];
10345
10346 // display
10347 data.graphicsControllerType = mHWData->mGraphicsControllerType;
10348 data.ulVRAMSizeMB = mHWData->mVRAMSize;
10349 data.cMonitors = mHWData->mMonitorCount;
10350 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
10351 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
10352 data.ulVideoCaptureHorzRes = mHWData->mVideoCaptureWidth;
10353 data.ulVideoCaptureVertRes = mHWData->mVideoCaptureHeight;
10354 data.ulVideoCaptureRate = mHWData->mVideoCaptureRate;
10355 data.ulVideoCaptureFPS = mHWData->mVideoCaptureFPS;
10356 data.fVideoCaptureEnabled = !!mHWData->mVideoCaptureEnabled;
10357 for (unsigned i = 0; i < sizeof(data.u64VideoCaptureScreens) * 8; ++i)
10358 {
10359 if (mHWData->maVideoCaptureScreens[i])
10360 ASMBitSet(&data.u64VideoCaptureScreens, i);
10361 else
10362 ASMBitClear(&data.u64VideoCaptureScreens, i);
10363 }
10364 /* store relative video capture file if possible */
10365 i_copyPathRelativeToMachine(mHWData->mVideoCaptureFile, data.strVideoCaptureFile);
10366
10367 /* VRDEServer settings (optional) */
10368 rc = mVRDEServer->i_saveSettings(data.vrdeSettings);
10369 if (FAILED(rc)) throw rc;
10370
10371 /* BIOS (required) */
10372 rc = mBIOSSettings->i_saveSettings(data.biosSettings);
10373 if (FAILED(rc)) throw rc;
10374
10375 /* USB Controller (required) */
10376 data.usbSettings.llUSBControllers.clear();
10377 for (USBControllerList::const_iterator
10378 it = mUSBControllers->begin();
10379 it != mUSBControllers->end();
10380 ++it)
10381 {
10382 ComObjPtr<USBController> ctrl = *it;
10383 settings::USBController settingsCtrl;
10384
10385 settingsCtrl.strName = ctrl->i_getName();
10386 settingsCtrl.enmType = ctrl->i_getControllerType();
10387
10388 data.usbSettings.llUSBControllers.push_back(settingsCtrl);
10389 }
10390
10391 /* USB device filters (required) */
10392 rc = mUSBDeviceFilters->i_saveSettings(data.usbSettings);
10393 if (FAILED(rc)) throw rc;
10394
10395 /* Network adapters (required) */
10396 size_t uMaxNICs = RT_MIN(Global::getMaxNetworkAdapters(mHWData->mChipsetType), mNetworkAdapters.size());
10397 data.llNetworkAdapters.clear();
10398 /* Write out only the nominal number of network adapters for this
10399 * chipset type. Since Machine::commit() hasn't been called there
10400 * may be extra NIC settings in the vector. */
10401 for (size_t slot = 0; slot < uMaxNICs; ++slot)
10402 {
10403 settings::NetworkAdapter nic;
10404 nic.ulSlot = (uint32_t)slot;
10405 /* paranoia check... must not be NULL, but must not crash either. */
10406 if (mNetworkAdapters[slot])
10407 {
10408 if (mNetworkAdapters[slot]->i_hasDefaults())
10409 continue;
10410
10411 rc = mNetworkAdapters[slot]->i_saveSettings(nic);
10412 if (FAILED(rc)) throw rc;
10413
10414 data.llNetworkAdapters.push_back(nic);
10415 }
10416 }
10417
10418 /* Serial ports */
10419 data.llSerialPorts.clear();
10420 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
10421 {
10422 if (mSerialPorts[slot]->i_hasDefaults())
10423 continue;
10424
10425 settings::SerialPort s;
10426 s.ulSlot = slot;
10427 rc = mSerialPorts[slot]->i_saveSettings(s);
10428 if (FAILED(rc)) return rc;
10429
10430 data.llSerialPorts.push_back(s);
10431 }
10432
10433 /* Parallel ports */
10434 data.llParallelPorts.clear();
10435 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
10436 {
10437 if (mParallelPorts[slot]->i_hasDefaults())
10438 continue;
10439
10440 settings::ParallelPort p;
10441 p.ulSlot = slot;
10442 rc = mParallelPorts[slot]->i_saveSettings(p);
10443 if (FAILED(rc)) return rc;
10444
10445 data.llParallelPorts.push_back(p);
10446 }
10447
10448 /* Audio adapter */
10449 rc = mAudioAdapter->i_saveSettings(data.audioAdapter);
10450 if (FAILED(rc)) return rc;
10451
10452 rc = i_saveStorageControllers(data.storage);
10453 if (FAILED(rc)) return rc;
10454
10455 /* Shared folders */
10456 data.llSharedFolders.clear();
10457 for (HWData::SharedFolderList::const_iterator
10458 it = mHWData->mSharedFolders.begin();
10459 it != mHWData->mSharedFolders.end();
10460 ++it)
10461 {
10462 SharedFolder *pSF = *it;
10463 AutoCaller sfCaller(pSF);
10464 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
10465 settings::SharedFolder sf;
10466 sf.strName = pSF->i_getName();
10467 sf.strHostPath = pSF->i_getHostPath();
10468 sf.fWritable = !!pSF->i_isWritable();
10469 sf.fAutoMount = !!pSF->i_isAutoMounted();
10470
10471 data.llSharedFolders.push_back(sf);
10472 }
10473
10474 // clipboard
10475 data.clipboardMode = mHWData->mClipboardMode;
10476
10477 // drag'n'drop
10478 data.dndMode = mHWData->mDnDMode;
10479
10480 /* Guest */
10481 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
10482
10483 // IO settings
10484 data.ioSettings.fIOCacheEnabled = !!mHWData->mIOCacheEnabled;
10485 data.ioSettings.ulIOCacheSize = mHWData->mIOCacheSize;
10486
10487 /* BandwidthControl (required) */
10488 rc = mBandwidthControl->i_saveSettings(data.ioSettings);
10489 if (FAILED(rc)) throw rc;
10490
10491 /* Host PCI devices */
10492 data.pciAttachments.clear();
10493 for (HWData::PCIDeviceAssignmentList::const_iterator
10494 it = mHWData->mPCIDeviceAssignments.begin();
10495 it != mHWData->mPCIDeviceAssignments.end();
10496 ++it)
10497 {
10498 ComObjPtr<PCIDeviceAttachment> pda = *it;
10499 settings::HostPCIDeviceAttachment hpda;
10500
10501 rc = pda->i_saveSettings(hpda);
10502 if (FAILED(rc)) throw rc;
10503
10504 data.pciAttachments.push_back(hpda);
10505 }
10506
10507 // guest properties
10508 data.llGuestProperties.clear();
10509#ifdef VBOX_WITH_GUEST_PROPS
10510 for (HWData::GuestPropertyMap::const_iterator
10511 it = mHWData->mGuestProperties.begin();
10512 it != mHWData->mGuestProperties.end();
10513 ++it)
10514 {
10515 HWData::GuestProperty property = it->second;
10516
10517 /* Remove transient guest properties at shutdown unless we
10518 * are saving state. Note that restoring snapshot intentionally
10519 * keeps them, they will be removed if appropriate once the final
10520 * machine state is set (as crashes etc. need to work). */
10521 if ( ( mData->mMachineState == MachineState_PoweredOff
10522 || mData->mMachineState == MachineState_Aborted
10523 || mData->mMachineState == MachineState_Teleported)
10524 && ( property.mFlags & guestProp::TRANSIENT
10525 || property.mFlags & guestProp::TRANSRESET))
10526 continue;
10527 settings::GuestProperty prop;
10528 prop.strName = it->first;
10529 prop.strValue = property.strValue;
10530 prop.timestamp = property.mTimestamp;
10531 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
10532 guestProp::writeFlags(property.mFlags, szFlags);
10533 prop.strFlags = szFlags;
10534
10535 data.llGuestProperties.push_back(prop);
10536 }
10537
10538 /* I presume this doesn't require a backup(). */
10539 mData->mGuestPropertiesModified = FALSE;
10540#endif /* VBOX_WITH_GUEST_PROPS defined */
10541
10542 *pDbg = mHWData->mDebugging;
10543 *pAutostart = mHWData->mAutostart;
10544
10545 data.strDefaultFrontend = mHWData->mDefaultFrontend;
10546 }
10547 catch (std::bad_alloc &)
10548 {
10549 return E_OUTOFMEMORY;
10550 }
10551
10552 AssertComRC(rc);
10553 return rc;
10554}
10555
10556/**
10557 * Saves the storage controller configuration.
10558 *
10559 * @param data storage settings.
10560 */
10561HRESULT Machine::i_saveStorageControllers(settings::Storage &data)
10562{
10563 data.llStorageControllers.clear();
10564
10565 for (StorageControllerList::const_iterator
10566 it = mStorageControllers->begin();
10567 it != mStorageControllers->end();
10568 ++it)
10569 {
10570 HRESULT rc;
10571 ComObjPtr<StorageController> pCtl = *it;
10572
10573 settings::StorageController ctl;
10574 ctl.strName = pCtl->i_getName();
10575 ctl.controllerType = pCtl->i_getControllerType();
10576 ctl.storageBus = pCtl->i_getStorageBus();
10577 ctl.ulInstance = pCtl->i_getInstance();
10578 ctl.fBootable = pCtl->i_getBootable();
10579
10580 /* Save the port count. */
10581 ULONG portCount;
10582 rc = pCtl->COMGETTER(PortCount)(&portCount);
10583 ComAssertComRCRet(rc, rc);
10584 ctl.ulPortCount = portCount;
10585
10586 /* Save fUseHostIOCache */
10587 BOOL fUseHostIOCache;
10588 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
10589 ComAssertComRCRet(rc, rc);
10590 ctl.fUseHostIOCache = !!fUseHostIOCache;
10591
10592 /* save the devices now. */
10593 rc = i_saveStorageDevices(pCtl, ctl);
10594 ComAssertComRCRet(rc, rc);
10595
10596 data.llStorageControllers.push_back(ctl);
10597 }
10598
10599 return S_OK;
10600}
10601
10602/**
10603 * Saves the hard disk configuration.
10604 */
10605HRESULT Machine::i_saveStorageDevices(ComObjPtr<StorageController> aStorageController,
10606 settings::StorageController &data)
10607{
10608 MediumAttachmentList atts;
10609
10610 HRESULT rc = i_getMediumAttachmentsOfController(aStorageController->i_getName(), atts);
10611 if (FAILED(rc)) return rc;
10612
10613 data.llAttachedDevices.clear();
10614 for (MediumAttachmentList::const_iterator
10615 it = atts.begin();
10616 it != atts.end();
10617 ++it)
10618 {
10619 settings::AttachedDevice dev;
10620 IMediumAttachment *iA = *it;
10621 MediumAttachment *pAttach = static_cast<MediumAttachment *>(iA);
10622 Medium *pMedium = pAttach->i_getMedium();
10623
10624 dev.deviceType = pAttach->i_getType();
10625 dev.lPort = pAttach->i_getPort();
10626 dev.lDevice = pAttach->i_getDevice();
10627 dev.fPassThrough = pAttach->i_getPassthrough();
10628 dev.fHotPluggable = pAttach->i_getHotPluggable();
10629 if (pMedium)
10630 {
10631 if (pMedium->i_isHostDrive())
10632 dev.strHostDriveSrc = pMedium->i_getLocationFull();
10633 else
10634 dev.uuid = pMedium->i_getId();
10635 dev.fTempEject = pAttach->i_getTempEject();
10636 dev.fNonRotational = pAttach->i_getNonRotational();
10637 dev.fDiscard = pAttach->i_getDiscard();
10638 }
10639
10640 dev.strBwGroup = pAttach->i_getBandwidthGroup();
10641
10642 data.llAttachedDevices.push_back(dev);
10643 }
10644
10645 return S_OK;
10646}
10647
10648/**
10649 * Saves machine state settings as defined by aFlags
10650 * (SaveSTS_* values).
10651 *
10652 * @param aFlags Combination of SaveSTS_* flags.
10653 *
10654 * @note Locks objects for writing.
10655 */
10656HRESULT Machine::i_saveStateSettings(int aFlags)
10657{
10658 if (aFlags == 0)
10659 return S_OK;
10660
10661 AutoCaller autoCaller(this);
10662 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10663
10664 /* This object's write lock is also necessary to serialize file access
10665 * (prevent concurrent reads and writes) */
10666 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10667
10668 HRESULT rc = S_OK;
10669
10670 Assert(mData->pMachineConfigFile);
10671
10672 try
10673 {
10674 if (aFlags & SaveSTS_CurStateModified)
10675 mData->pMachineConfigFile->fCurrentStateModified = true;
10676
10677 if (aFlags & SaveSTS_StateFilePath)
10678 {
10679 if (!mSSData->strStateFilePath.isEmpty())
10680 /* try to make the file name relative to the settings file dir */
10681 i_copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
10682 else
10683 mData->pMachineConfigFile->strStateFile.setNull();
10684 }
10685
10686 if (aFlags & SaveSTS_StateTimeStamp)
10687 {
10688 Assert( mData->mMachineState != MachineState_Aborted
10689 || mSSData->strStateFilePath.isEmpty());
10690
10691 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
10692
10693 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
10694/// @todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
10695 }
10696
10697 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
10698 }
10699 catch (...)
10700 {
10701 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10702 }
10703
10704 return rc;
10705}
10706
10707/**
10708 * Ensures that the given medium is added to a media registry. If this machine
10709 * was created with 4.0 or later, then the machine registry is used. Otherwise
10710 * the global VirtualBox media registry is used.
10711 *
10712 * Caller must NOT hold machine lock, media tree or any medium locks!
10713 *
10714 * @param pMedium
10715 */
10716void Machine::i_addMediumToRegistry(ComObjPtr<Medium> &pMedium)
10717{
10718 /* Paranoia checks: do not hold machine or media tree locks. */
10719 AssertReturnVoid(!isWriteLockOnCurrentThread());
10720 AssertReturnVoid(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
10721
10722 ComObjPtr<Medium> pBase;
10723 {
10724 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10725 pBase = pMedium->i_getBase();
10726 }
10727
10728 /* Paranoia checks: do not hold medium locks. */
10729 AssertReturnVoid(!pMedium->isWriteLockOnCurrentThread());
10730 AssertReturnVoid(!pBase->isWriteLockOnCurrentThread());
10731
10732 // decide which medium registry to use now that the medium is attached:
10733 Guid uuid;
10734 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
10735 // machine XML is VirtualBox 4.0 or higher:
10736 uuid = i_getId(); // machine UUID
10737 else
10738 uuid = mParent->i_getGlobalRegistryId(); // VirtualBox global registry UUID
10739
10740 if (pMedium->i_addRegistry(uuid))
10741 mParent->i_markRegistryModified(uuid);
10742
10743 /* For more complex hard disk structures it can happen that the base
10744 * medium isn't yet associated with any medium registry. Do that now. */
10745 if (pMedium != pBase)
10746 {
10747 /* Tree lock needed by Medium::addRegistry when recursing. */
10748 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10749 if (pBase->i_addRegistryRecursive(uuid))
10750 {
10751 treeLock.release();
10752 mParent->i_markRegistryModified(uuid);
10753 }
10754 }
10755}
10756
10757/**
10758 * Creates differencing hard disks for all normal hard disks attached to this
10759 * machine and a new set of attachments to refer to created disks.
10760 *
10761 * Used when taking a snapshot or when deleting the current state. Gets called
10762 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
10763 *
10764 * This method assumes that mMediumAttachments contains the original hard disk
10765 * attachments it needs to create diffs for. On success, these attachments will
10766 * be replaced with the created diffs.
10767 *
10768 * Attachments with non-normal hard disks are left as is.
10769 *
10770 * If @a aOnline is @c false then the original hard disks that require implicit
10771 * diffs will be locked for reading. Otherwise it is assumed that they are
10772 * already locked for writing (when the VM was started). Note that in the latter
10773 * case it is responsibility of the caller to lock the newly created diffs for
10774 * writing if this method succeeds.
10775 *
10776 * @param aProgress Progress object to run (must contain at least as
10777 * many operations left as the number of hard disks
10778 * attached).
10779 * @param aWeight Weight of this operation.
10780 * @param aOnline Whether the VM was online prior to this operation.
10781 *
10782 * @note The progress object is not marked as completed, neither on success nor
10783 * on failure. This is a responsibility of the caller.
10784 *
10785 * @note Locks this object and the media tree for writing.
10786 */
10787HRESULT Machine::i_createImplicitDiffs(IProgress *aProgress,
10788 ULONG aWeight,
10789 bool aOnline)
10790{
10791 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10792
10793 AutoCaller autoCaller(this);
10794 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10795
10796 AutoMultiWriteLock2 alock(this->lockHandle(),
10797 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10798
10799 /* must be in a protective state because we release the lock below */
10800 AssertReturn( mData->mMachineState == MachineState_Snapshotting
10801 || mData->mMachineState == MachineState_OnlineSnapshotting
10802 || mData->mMachineState == MachineState_LiveSnapshotting
10803 || mData->mMachineState == MachineState_RestoringSnapshot
10804 || mData->mMachineState == MachineState_DeletingSnapshot
10805 , E_FAIL);
10806
10807 HRESULT rc = S_OK;
10808
10809 // use appropriate locked media map (online or offline)
10810 MediumLockListMap lockedMediaOffline;
10811 MediumLockListMap *lockedMediaMap;
10812 if (aOnline)
10813 lockedMediaMap = &mData->mSession.mLockedMedia;
10814 else
10815 lockedMediaMap = &lockedMediaOffline;
10816
10817 try
10818 {
10819 if (!aOnline)
10820 {
10821 /* lock all attached hard disks early to detect "in use"
10822 * situations before creating actual diffs */
10823 for (MediumAttachmentList::const_iterator
10824 it = mMediumAttachments->begin();
10825 it != mMediumAttachments->end();
10826 ++it)
10827 {
10828 MediumAttachment *pAtt = *it;
10829 if (pAtt->i_getType() == DeviceType_HardDisk)
10830 {
10831 Medium *pMedium = pAtt->i_getMedium();
10832 Assert(pMedium);
10833
10834 MediumLockList *pMediumLockList(new MediumLockList());
10835 alock.release();
10836 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
10837 NULL /* pToLockWrite */,
10838 false /* fMediumLockWriteAll */,
10839 NULL,
10840 *pMediumLockList);
10841 alock.acquire();
10842 if (FAILED(rc))
10843 {
10844 delete pMediumLockList;
10845 throw rc;
10846 }
10847 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10848 if (FAILED(rc))
10849 {
10850 throw setError(rc,
10851 tr("Collecting locking information for all attached media failed"));
10852 }
10853 }
10854 }
10855
10856 /* Now lock all media. If this fails, nothing is locked. */
10857 alock.release();
10858 rc = lockedMediaMap->Lock();
10859 alock.acquire();
10860 if (FAILED(rc))
10861 {
10862 throw setError(rc,
10863 tr("Locking of attached media failed"));
10864 }
10865 }
10866
10867 /* remember the current list (note that we don't use backup() since
10868 * mMediumAttachments may be already backed up) */
10869 MediumAttachmentList atts = *mMediumAttachments.data();
10870
10871 /* start from scratch */
10872 mMediumAttachments->clear();
10873
10874 /* go through remembered attachments and create diffs for normal hard
10875 * disks and attach them */
10876 for (MediumAttachmentList::const_iterator
10877 it = atts.begin();
10878 it != atts.end();
10879 ++it)
10880 {
10881 MediumAttachment *pAtt = *it;
10882
10883 DeviceType_T devType = pAtt->i_getType();
10884 Medium *pMedium = pAtt->i_getMedium();
10885
10886 if ( devType != DeviceType_HardDisk
10887 || pMedium == NULL
10888 || pMedium->i_getType() != MediumType_Normal)
10889 {
10890 /* copy the attachment as is */
10891
10892 /** @todo the progress object created in SessionMachine::TakeSnaphot
10893 * only expects operations for hard disks. Later other
10894 * device types need to show up in the progress as well. */
10895 if (devType == DeviceType_HardDisk)
10896 {
10897 if (pMedium == NULL)
10898 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
10899 aWeight); // weight
10900 else
10901 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
10902 pMedium->i_getBase()->i_getName().c_str()).raw(),
10903 aWeight); // weight
10904 }
10905
10906 mMediumAttachments->push_back(pAtt);
10907 continue;
10908 }
10909
10910 /* need a diff */
10911 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
10912 pMedium->i_getBase()->i_getName().c_str()).raw(),
10913 aWeight); // weight
10914
10915 Utf8Str strFullSnapshotFolder;
10916 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10917
10918 ComObjPtr<Medium> diff;
10919 diff.createObject();
10920 // store the diff in the same registry as the parent
10921 // (this cannot fail here because we can't create implicit diffs for
10922 // unregistered images)
10923 Guid uuidRegistryParent;
10924 bool fInRegistry = pMedium->i_getFirstRegistryMachineId(uuidRegistryParent);
10925 Assert(fInRegistry); NOREF(fInRegistry);
10926 rc = diff->init(mParent,
10927 pMedium->i_getPreferredDiffFormat(),
10928 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
10929 uuidRegistryParent,
10930 DeviceType_HardDisk);
10931 if (FAILED(rc)) throw rc;
10932
10933 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
10934 * the push_back? Looks like we're going to release medium with the
10935 * wrong kind of lock (general issue with if we fail anywhere at all)
10936 * and an orphaned VDI in the snapshots folder. */
10937
10938 /* update the appropriate lock list */
10939 MediumLockList *pMediumLockList;
10940 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
10941 AssertComRCThrowRC(rc);
10942 if (aOnline)
10943 {
10944 alock.release();
10945 /* The currently attached medium will be read-only, change
10946 * the lock type to read. */
10947 rc = pMediumLockList->Update(pMedium, false);
10948 alock.acquire();
10949 AssertComRCThrowRC(rc);
10950 }
10951
10952 /* release the locks before the potentially lengthy operation */
10953 alock.release();
10954 rc = pMedium->i_createDiffStorage(diff,
10955 pMedium->i_getPreferredDiffVariant(),
10956 pMediumLockList,
10957 NULL /* aProgress */,
10958 true /* aWait */);
10959 alock.acquire();
10960 if (FAILED(rc)) throw rc;
10961
10962 /* actual lock list update is done in Machine::i_commitMedia */
10963
10964 rc = diff->i_addBackReference(mData->mUuid);
10965 AssertComRCThrowRC(rc);
10966
10967 /* add a new attachment */
10968 ComObjPtr<MediumAttachment> attachment;
10969 attachment.createObject();
10970 rc = attachment->init(this,
10971 diff,
10972 pAtt->i_getControllerName(),
10973 pAtt->i_getPort(),
10974 pAtt->i_getDevice(),
10975 DeviceType_HardDisk,
10976 true /* aImplicit */,
10977 false /* aPassthrough */,
10978 false /* aTempEject */,
10979 pAtt->i_getNonRotational(),
10980 pAtt->i_getDiscard(),
10981 pAtt->i_getHotPluggable(),
10982 pAtt->i_getBandwidthGroup());
10983 if (FAILED(rc)) throw rc;
10984
10985 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
10986 AssertComRCThrowRC(rc);
10987 mMediumAttachments->push_back(attachment);
10988 }
10989 }
10990 catch (HRESULT aRC) { rc = aRC; }
10991
10992 /* unlock all hard disks we locked when there is no VM */
10993 if (!aOnline)
10994 {
10995 ErrorInfoKeeper eik;
10996
10997 HRESULT rc1 = lockedMediaMap->Clear();
10998 AssertComRC(rc1);
10999 }
11000
11001 return rc;
11002}
11003
11004/**
11005 * Deletes implicit differencing hard disks created either by
11006 * #i_createImplicitDiffs() or by #attachDevice() and rolls back
11007 * mMediumAttachments.
11008 *
11009 * Note that to delete hard disks created by #attachDevice() this method is
11010 * called from #i_rollbackMedia() when the changes are rolled back.
11011 *
11012 * @note Locks this object and the media tree for writing.
11013 */
11014HRESULT Machine::i_deleteImplicitDiffs(bool aOnline)
11015{
11016 LogFlowThisFunc(("aOnline=%d\n", aOnline));
11017
11018 AutoCaller autoCaller(this);
11019 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11020
11021 AutoMultiWriteLock2 alock(this->lockHandle(),
11022 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
11023
11024 /* We absolutely must have backed up state. */
11025 AssertReturn(mMediumAttachments.isBackedUp(), E_FAIL);
11026
11027 /* Check if there are any implicitly created diff images. */
11028 bool fImplicitDiffs = false;
11029 for (MediumAttachmentList::const_iterator
11030 it = mMediumAttachments->begin();
11031 it != mMediumAttachments->end();
11032 ++it)
11033 {
11034 const ComObjPtr<MediumAttachment> &pAtt = *it;
11035 if (pAtt->i_isImplicit())
11036 {
11037 fImplicitDiffs = true;
11038 break;
11039 }
11040 }
11041 /* If there is nothing to do, leave early. This saves lots of image locking
11042 * effort. It also avoids a MachineStateChanged event without real reason.
11043 * This is important e.g. when loading a VM config, because there should be
11044 * no events. Otherwise API clients can become thoroughly confused for
11045 * inaccessible VMs (the code for loading VM configs uses this method for
11046 * cleanup if the config makes no sense), as they take such events as an
11047 * indication that the VM is alive, and they would force the VM config to
11048 * be reread, leading to an endless loop. */
11049 if (!fImplicitDiffs)
11050 return S_OK;
11051
11052 HRESULT rc = S_OK;
11053 MachineState_T oldState = mData->mMachineState;
11054
11055 /* will release the lock before the potentially lengthy operation,
11056 * so protect with the special state (unless already protected) */
11057 if ( oldState != MachineState_Snapshotting
11058 && oldState != MachineState_OnlineSnapshotting
11059 && oldState != MachineState_LiveSnapshotting
11060 && oldState != MachineState_RestoringSnapshot
11061 && oldState != MachineState_DeletingSnapshot
11062 && oldState != MachineState_DeletingSnapshotOnline
11063 && oldState != MachineState_DeletingSnapshotPaused
11064 )
11065 i_setMachineState(MachineState_SettingUp);
11066
11067 // use appropriate locked media map (online or offline)
11068 MediumLockListMap lockedMediaOffline;
11069 MediumLockListMap *lockedMediaMap;
11070 if (aOnline)
11071 lockedMediaMap = &mData->mSession.mLockedMedia;
11072 else
11073 lockedMediaMap = &lockedMediaOffline;
11074
11075 try
11076 {
11077 if (!aOnline)
11078 {
11079 /* lock all attached hard disks early to detect "in use"
11080 * situations before deleting actual diffs */
11081 for (MediumAttachmentList::const_iterator
11082 it = mMediumAttachments->begin();
11083 it != mMediumAttachments->end();
11084 ++it)
11085 {
11086 MediumAttachment *pAtt = *it;
11087 if (pAtt->i_getType() == DeviceType_HardDisk)
11088 {
11089 Medium *pMedium = pAtt->i_getMedium();
11090 Assert(pMedium);
11091
11092 MediumLockList *pMediumLockList(new MediumLockList());
11093 alock.release();
11094 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
11095 NULL /* pToLockWrite */,
11096 false /* fMediumLockWriteAll */,
11097 NULL,
11098 *pMediumLockList);
11099 alock.acquire();
11100
11101 if (FAILED(rc))
11102 {
11103 delete pMediumLockList;
11104 throw rc;
11105 }
11106
11107 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
11108 if (FAILED(rc))
11109 throw rc;
11110 }
11111 }
11112
11113 if (FAILED(rc))
11114 throw rc;
11115 } // end of offline
11116
11117 /* Lock lists are now up to date and include implicitly created media */
11118
11119 /* Go through remembered attachments and delete all implicitly created
11120 * diffs and fix up the attachment information */
11121 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
11122 MediumAttachmentList implicitAtts;
11123 for (MediumAttachmentList::const_iterator
11124 it = mMediumAttachments->begin();
11125 it != mMediumAttachments->end();
11126 ++it)
11127 {
11128 ComObjPtr<MediumAttachment> pAtt = *it;
11129 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11130 if (pMedium.isNull())
11131 continue;
11132
11133 // Implicit attachments go on the list for deletion and back references are removed.
11134 if (pAtt->i_isImplicit())
11135 {
11136 /* Deassociate and mark for deletion */
11137 LogFlowThisFunc(("Detaching '%s', pending deletion\n", pAtt->i_getLogName()));
11138 rc = pMedium->i_removeBackReference(mData->mUuid);
11139 if (FAILED(rc))
11140 throw rc;
11141 implicitAtts.push_back(pAtt);
11142 continue;
11143 }
11144
11145 /* Was this medium attached before? */
11146 if (!i_findAttachment(oldAtts, pMedium))
11147 {
11148 /* no: de-associate */
11149 LogFlowThisFunc(("Detaching '%s', no deletion\n", pAtt->i_getLogName()));
11150 rc = pMedium->i_removeBackReference(mData->mUuid);
11151 if (FAILED(rc))
11152 throw rc;
11153 continue;
11154 }
11155 LogFlowThisFunc(("Not detaching '%s'\n", pAtt->i_getLogName()));
11156 }
11157
11158 /* If there are implicit attachments to delete, throw away the lock
11159 * map contents (which will unlock all media) since the medium
11160 * attachments will be rolled back. Below we need to completely
11161 * recreate the lock map anyway since it is infinitely complex to
11162 * do this incrementally (would need reconstructing each attachment
11163 * change, which would be extremely hairy). */
11164 if (implicitAtts.size() != 0)
11165 {
11166 ErrorInfoKeeper eik;
11167
11168 HRESULT rc1 = lockedMediaMap->Clear();
11169 AssertComRC(rc1);
11170 }
11171
11172 /* rollback hard disk changes */
11173 mMediumAttachments.rollback();
11174
11175 MultiResult mrc(S_OK);
11176
11177 // Delete unused implicit diffs.
11178 if (implicitAtts.size() != 0)
11179 {
11180 alock.release();
11181
11182 for (MediumAttachmentList::const_iterator
11183 it = implicitAtts.begin();
11184 it != implicitAtts.end();
11185 ++it)
11186 {
11187 // Remove medium associated with this attachment.
11188 ComObjPtr<MediumAttachment> pAtt = *it;
11189 Assert(pAtt);
11190 LogFlowThisFunc(("Deleting '%s'\n", pAtt->i_getLogName()));
11191 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11192 Assert(pMedium);
11193
11194 rc = pMedium->i_deleteStorage(NULL /*aProgress*/, true /*aWait*/);
11195 // continue on delete failure, just collect error messages
11196 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, pAtt->i_getLogName(),
11197 pMedium->i_getLocationFull().c_str() ));
11198 mrc = rc;
11199 }
11200 // Clear the list of deleted implicit attachments now, while not
11201 // holding the lock, as it will ultimately trigger Medium::uninit()
11202 // calls which assume that the media tree lock isn't held.
11203 implicitAtts.clear();
11204
11205 alock.acquire();
11206
11207 /* if there is a VM recreate media lock map as mentioned above,
11208 * otherwise it is a waste of time and we leave things unlocked */
11209 if (aOnline)
11210 {
11211 const ComObjPtr<SessionMachine> pMachine = mData->mSession.mMachine;
11212 /* must never be NULL, but better safe than sorry */
11213 if (!pMachine.isNull())
11214 {
11215 alock.release();
11216 rc = mData->mSession.mMachine->i_lockMedia();
11217 alock.acquire();
11218 if (FAILED(rc))
11219 throw rc;
11220 }
11221 }
11222 }
11223 }
11224 catch (HRESULT aRC) {rc = aRC;}
11225
11226 if (mData->mMachineState == MachineState_SettingUp)
11227 i_setMachineState(oldState);
11228
11229 /* unlock all hard disks we locked when there is no VM */
11230 if (!aOnline)
11231 {
11232 ErrorInfoKeeper eik;
11233
11234 HRESULT rc1 = lockedMediaMap->Clear();
11235 AssertComRC(rc1);
11236 }
11237
11238 return rc;
11239}
11240
11241
11242/**
11243 * Looks through the given list of media attachments for one with the given parameters
11244 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11245 * can be searched as well if needed.
11246 *
11247 * @param ll
11248 * @param aControllerName
11249 * @param aControllerPort
11250 * @param aDevice
11251 * @return
11252 */
11253MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11254 const Utf8Str &aControllerName,
11255 LONG aControllerPort,
11256 LONG aDevice)
11257{
11258 for (MediumAttachmentList::const_iterator
11259 it = ll.begin();
11260 it != ll.end();
11261 ++it)
11262 {
11263 MediumAttachment *pAttach = *it;
11264 if (pAttach->i_matches(aControllerName, aControllerPort, aDevice))
11265 return pAttach;
11266 }
11267
11268 return NULL;
11269}
11270
11271/**
11272 * Looks through the given list of media attachments for one with the given parameters
11273 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11274 * can be searched as well if needed.
11275 *
11276 * @param ll
11277 * @param pMedium
11278 * @return
11279 */
11280MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11281 ComObjPtr<Medium> pMedium)
11282{
11283 for (MediumAttachmentList::const_iterator
11284 it = ll.begin();
11285 it != ll.end();
11286 ++it)
11287 {
11288 MediumAttachment *pAttach = *it;
11289 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11290 if (pMediumThis == pMedium)
11291 return pAttach;
11292 }
11293
11294 return NULL;
11295}
11296
11297/**
11298 * Looks through the given list of media attachments for one with the given parameters
11299 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11300 * can be searched as well if needed.
11301 *
11302 * @param ll
11303 * @param id
11304 * @return
11305 */
11306MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11307 Guid &id)
11308{
11309 for (MediumAttachmentList::const_iterator
11310 it = ll.begin();
11311 it != ll.end();
11312 ++it)
11313 {
11314 MediumAttachment *pAttach = *it;
11315 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11316 if (pMediumThis->i_getId() == id)
11317 return pAttach;
11318 }
11319
11320 return NULL;
11321}
11322
11323/**
11324 * Main implementation for Machine::DetachDevice. This also gets called
11325 * from Machine::prepareUnregister() so it has been taken out for simplicity.
11326 *
11327 * @param pAttach Medium attachment to detach.
11328 * @param writeLock Machine write lock which the caller must have locked once.
11329 * This may be released temporarily in here.
11330 * @param pSnapshot If NULL, then the detachment is for the current machine.
11331 * Otherwise this is for a SnapshotMachine, and this must be
11332 * its snapshot.
11333 * @return
11334 */
11335HRESULT Machine::i_detachDevice(MediumAttachment *pAttach,
11336 AutoWriteLock &writeLock,
11337 Snapshot *pSnapshot)
11338{
11339 ComObjPtr<Medium> oldmedium = pAttach->i_getMedium();
11340 DeviceType_T mediumType = pAttach->i_getType();
11341
11342 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->i_getLocationFull().c_str() : "NULL"));
11343
11344 if (pAttach->i_isImplicit())
11345 {
11346 /* attempt to implicitly delete the implicitly created diff */
11347
11348 /// @todo move the implicit flag from MediumAttachment to Medium
11349 /// and forbid any hard disk operation when it is implicit. Or maybe
11350 /// a special media state for it to make it even more simple.
11351
11352 Assert(mMediumAttachments.isBackedUp());
11353
11354 /* will release the lock before the potentially lengthy operation, so
11355 * protect with the special state */
11356 MachineState_T oldState = mData->mMachineState;
11357 i_setMachineState(MachineState_SettingUp);
11358
11359 writeLock.release();
11360
11361 HRESULT rc = oldmedium->i_deleteStorage(NULL /*aProgress*/,
11362 true /*aWait*/);
11363
11364 writeLock.acquire();
11365
11366 i_setMachineState(oldState);
11367
11368 if (FAILED(rc)) return rc;
11369 }
11370
11371 i_setModified(IsModified_Storage);
11372 mMediumAttachments.backup();
11373 mMediumAttachments->remove(pAttach);
11374
11375 if (!oldmedium.isNull())
11376 {
11377 // if this is from a snapshot, do not defer detachment to i_commitMedia()
11378 if (pSnapshot)
11379 oldmedium->i_removeBackReference(mData->mUuid, pSnapshot->i_getId());
11380 // else if non-hard disk media, do not defer detachment to i_commitMedia() either
11381 else if (mediumType != DeviceType_HardDisk)
11382 oldmedium->i_removeBackReference(mData->mUuid);
11383 }
11384
11385 return S_OK;
11386}
11387
11388/**
11389 * Goes thru all media of the given list and
11390 *
11391 * 1) calls i_detachDevice() on each of them for this machine and
11392 * 2) adds all Medium objects found in the process to the given list,
11393 * depending on cleanupMode.
11394 *
11395 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
11396 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
11397 * media to the list.
11398 *
11399 * This gets called from Machine::Unregister, both for the actual Machine and
11400 * the SnapshotMachine objects that might be found in the snapshots.
11401 *
11402 * Requires caller and locking. The machine lock must be passed in because it
11403 * will be passed on to i_detachDevice which needs it for temporary unlocking.
11404 *
11405 * @param writeLock Machine lock from top-level caller; this gets passed to
11406 * i_detachDevice.
11407 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot
11408 * object if called for a SnapshotMachine.
11409 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get
11410 * added to llMedia; if Full, then all media get added;
11411 * otherwise no media get added.
11412 * @param llMedia Caller's list to receive Medium objects which got detached so
11413 * caller can close() them, depending on cleanupMode.
11414 * @return
11415 */
11416HRESULT Machine::i_detachAllMedia(AutoWriteLock &writeLock,
11417 Snapshot *pSnapshot,
11418 CleanupMode_T cleanupMode,
11419 MediaList &llMedia)
11420{
11421 Assert(isWriteLockOnCurrentThread());
11422
11423 HRESULT rc;
11424
11425 // make a temporary list because i_detachDevice invalidates iterators into
11426 // mMediumAttachments
11427 MediumAttachmentList llAttachments2 = *mMediumAttachments.data();
11428
11429 for (MediumAttachmentList::iterator
11430 it = llAttachments2.begin();
11431 it != llAttachments2.end();
11432 ++it)
11433 {
11434 ComObjPtr<MediumAttachment> &pAttach = *it;
11435 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
11436
11437 if (!pMedium.isNull())
11438 {
11439 AutoCaller mac(pMedium);
11440 if (FAILED(mac.rc())) return mac.rc();
11441 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
11442 DeviceType_T devType = pMedium->i_getDeviceType();
11443 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
11444 && devType == DeviceType_HardDisk)
11445 || (cleanupMode == CleanupMode_Full)
11446 )
11447 {
11448 llMedia.push_back(pMedium);
11449 ComObjPtr<Medium> pParent = pMedium->i_getParent();
11450 /* Not allowed to keep this lock as below we need the parent
11451 * medium lock, and the lock order is parent to child. */
11452 lock.release();
11453 /*
11454 * Search for medias which are not attached to any machine, but
11455 * in the chain to an attached disk. Mediums are only consided
11456 * if they are:
11457 * - have only one child
11458 * - no references to any machines
11459 * - are of normal medium type
11460 */
11461 while (!pParent.isNull())
11462 {
11463 AutoCaller mac1(pParent);
11464 if (FAILED(mac1.rc())) return mac1.rc();
11465 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
11466 if (pParent->i_getChildren().size() == 1)
11467 {
11468 if ( pParent->i_getMachineBackRefCount() == 0
11469 && pParent->i_getType() == MediumType_Normal
11470 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
11471 llMedia.push_back(pParent);
11472 }
11473 else
11474 break;
11475 pParent = pParent->i_getParent();
11476 }
11477 }
11478 }
11479
11480 // real machine: then we need to use the proper method
11481 rc = i_detachDevice(pAttach, writeLock, pSnapshot);
11482
11483 if (FAILED(rc))
11484 return rc;
11485 }
11486
11487 return S_OK;
11488}
11489
11490/**
11491 * Perform deferred hard disk detachments.
11492 *
11493 * Does nothing if the hard disk attachment data (mMediumAttachments) is not
11494 * changed (not backed up).
11495 *
11496 * If @a aOnline is @c true then this method will also unlock the old hard
11497 * disks for which the new implicit diffs were created and will lock these new
11498 * diffs for writing.
11499 *
11500 * @param aOnline Whether the VM was online prior to this operation.
11501 *
11502 * @note Locks this object for writing!
11503 */
11504void Machine::i_commitMedia(bool aOnline /*= false*/)
11505{
11506 AutoCaller autoCaller(this);
11507 AssertComRCReturnVoid(autoCaller.rc());
11508
11509 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11510
11511 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
11512
11513 HRESULT rc = S_OK;
11514
11515 /* no attach/detach operations -- nothing to do */
11516 if (!mMediumAttachments.isBackedUp())
11517 return;
11518
11519 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
11520 bool fMediaNeedsLocking = false;
11521
11522 /* enumerate new attachments */
11523 for (MediumAttachmentList::const_iterator
11524 it = mMediumAttachments->begin();
11525 it != mMediumAttachments->end();
11526 ++it)
11527 {
11528 MediumAttachment *pAttach = *it;
11529
11530 pAttach->i_commit();
11531
11532 Medium *pMedium = pAttach->i_getMedium();
11533 bool fImplicit = pAttach->i_isImplicit();
11534
11535 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
11536 (pMedium) ? pMedium->i_getName().c_str() : "NULL",
11537 fImplicit));
11538
11539 /** @todo convert all this Machine-based voodoo to MediumAttachment
11540 * based commit logic. */
11541 if (fImplicit)
11542 {
11543 /* convert implicit attachment to normal */
11544 pAttach->i_setImplicit(false);
11545
11546 if ( aOnline
11547 && pMedium
11548 && pAttach->i_getType() == DeviceType_HardDisk
11549 )
11550 {
11551 /* update the appropriate lock list */
11552 MediumLockList *pMediumLockList;
11553 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11554 AssertComRC(rc);
11555 if (pMediumLockList)
11556 {
11557 /* unlock if there's a need to change the locking */
11558 if (!fMediaNeedsLocking)
11559 {
11560 rc = mData->mSession.mLockedMedia.Unlock();
11561 AssertComRC(rc);
11562 fMediaNeedsLocking = true;
11563 }
11564 rc = pMediumLockList->Update(pMedium->i_getParent(), false);
11565 AssertComRC(rc);
11566 rc = pMediumLockList->Append(pMedium, true);
11567 AssertComRC(rc);
11568 }
11569 }
11570
11571 continue;
11572 }
11573
11574 if (pMedium)
11575 {
11576 /* was this medium attached before? */
11577 for (MediumAttachmentList::iterator
11578 oldIt = oldAtts.begin();
11579 oldIt != oldAtts.end();
11580 ++oldIt)
11581 {
11582 MediumAttachment *pOldAttach = *oldIt;
11583 if (pOldAttach->i_getMedium() == pMedium)
11584 {
11585 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->i_getName().c_str()));
11586
11587 /* yes: remove from old to avoid de-association */
11588 oldAtts.erase(oldIt);
11589 break;
11590 }
11591 }
11592 }
11593 }
11594
11595 /* enumerate remaining old attachments and de-associate from the
11596 * current machine state */
11597 for (MediumAttachmentList::const_iterator
11598 it = oldAtts.begin();
11599 it != oldAtts.end();
11600 ++it)
11601 {
11602 MediumAttachment *pAttach = *it;
11603 Medium *pMedium = pAttach->i_getMedium();
11604
11605 /* Detach only hard disks, since DVD/floppy media is detached
11606 * instantly in MountMedium. */
11607 if (pAttach->i_getType() == DeviceType_HardDisk && pMedium)
11608 {
11609 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->i_getName().c_str()));
11610
11611 /* now de-associate from the current machine state */
11612 rc = pMedium->i_removeBackReference(mData->mUuid);
11613 AssertComRC(rc);
11614
11615 if (aOnline)
11616 {
11617 /* unlock since medium is not used anymore */
11618 MediumLockList *pMediumLockList;
11619 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11620 if (RT_UNLIKELY(rc == VBOX_E_INVALID_OBJECT_STATE))
11621 {
11622 /* this happens for online snapshots, there the attachment
11623 * is changing, but only to a diff image created under
11624 * the old one, so there is no separate lock list */
11625 Assert(!pMediumLockList);
11626 }
11627 else
11628 {
11629 AssertComRC(rc);
11630 if (pMediumLockList)
11631 {
11632 rc = mData->mSession.mLockedMedia.Remove(pAttach);
11633 AssertComRC(rc);
11634 }
11635 }
11636 }
11637 }
11638 }
11639
11640 /* take media locks again so that the locking state is consistent */
11641 if (fMediaNeedsLocking)
11642 {
11643 Assert(aOnline);
11644 rc = mData->mSession.mLockedMedia.Lock();
11645 AssertComRC(rc);
11646 }
11647
11648 /* commit the hard disk changes */
11649 mMediumAttachments.commit();
11650
11651 if (i_isSessionMachine())
11652 {
11653 /*
11654 * Update the parent machine to point to the new owner.
11655 * This is necessary because the stored parent will point to the
11656 * session machine otherwise and cause crashes or errors later
11657 * when the session machine gets invalid.
11658 */
11659 /** @todo Change the MediumAttachment class to behave like any other
11660 * class in this regard by creating peer MediumAttachment
11661 * objects for session machines and share the data with the peer
11662 * machine.
11663 */
11664 for (MediumAttachmentList::const_iterator
11665 it = mMediumAttachments->begin();
11666 it != mMediumAttachments->end();
11667 ++it)
11668 (*it)->i_updateParentMachine(mPeer);
11669
11670 /* attach new data to the primary machine and reshare it */
11671 mPeer->mMediumAttachments.attach(mMediumAttachments);
11672 }
11673
11674 return;
11675}
11676
11677/**
11678 * Perform deferred deletion of implicitly created diffs.
11679 *
11680 * Does nothing if the hard disk attachment data (mMediumAttachments) is not
11681 * changed (not backed up).
11682 *
11683 * @note Locks this object for writing!
11684 */
11685void Machine::i_rollbackMedia()
11686{
11687 AutoCaller autoCaller(this);
11688 AssertComRCReturnVoid(autoCaller.rc());
11689
11690 // AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11691 LogFlowThisFunc(("Entering rollbackMedia\n"));
11692
11693 HRESULT rc = S_OK;
11694
11695 /* no attach/detach operations -- nothing to do */
11696 if (!mMediumAttachments.isBackedUp())
11697 return;
11698
11699 /* enumerate new attachments */
11700 for (MediumAttachmentList::const_iterator
11701 it = mMediumAttachments->begin();
11702 it != mMediumAttachments->end();
11703 ++it)
11704 {
11705 MediumAttachment *pAttach = *it;
11706 /* Fix up the backrefs for DVD/floppy media. */
11707 if (pAttach->i_getType() != DeviceType_HardDisk)
11708 {
11709 Medium *pMedium = pAttach->i_getMedium();
11710 if (pMedium)
11711 {
11712 rc = pMedium->i_removeBackReference(mData->mUuid);
11713 AssertComRC(rc);
11714 }
11715 }
11716
11717 (*it)->i_rollback();
11718
11719 pAttach = *it;
11720 /* Fix up the backrefs for DVD/floppy media. */
11721 if (pAttach->i_getType() != DeviceType_HardDisk)
11722 {
11723 Medium *pMedium = pAttach->i_getMedium();
11724 if (pMedium)
11725 {
11726 rc = pMedium->i_addBackReference(mData->mUuid);
11727 AssertComRC(rc);
11728 }
11729 }
11730 }
11731
11732 /** @todo convert all this Machine-based voodoo to MediumAttachment
11733 * based rollback logic. */
11734 i_deleteImplicitDiffs(Global::IsOnline(mData->mMachineState));
11735
11736 return;
11737}
11738
11739/**
11740 * Returns true if the settings file is located in the directory named exactly
11741 * as the machine; this means, among other things, that the machine directory
11742 * should be auto-renamed.
11743 *
11744 * @param aSettingsDir if not NULL, the full machine settings file directory
11745 * name will be assigned there.
11746 *
11747 * @note Doesn't lock anything.
11748 * @note Not thread safe (must be called from this object's lock).
11749 */
11750bool Machine::i_isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
11751{
11752 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11753 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
11754 if (aSettingsDir)
11755 *aSettingsDir = strMachineDirName;
11756 strMachineDirName.stripPath(); // vmname
11757 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11758 strConfigFileOnly.stripPath() // vmname.vbox
11759 .stripSuffix(); // vmname
11760 /** @todo hack, make somehow use of ComposeMachineFilename */
11761 if (mUserData->s.fDirectoryIncludesUUID)
11762 strConfigFileOnly += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
11763
11764 AssertReturn(!strMachineDirName.isEmpty(), false);
11765 AssertReturn(!strConfigFileOnly.isEmpty(), false);
11766
11767 return strMachineDirName == strConfigFileOnly;
11768}
11769
11770/**
11771 * Discards all changes to machine settings.
11772 *
11773 * @param aNotify Whether to notify the direct session about changes or not.
11774 *
11775 * @note Locks objects for writing!
11776 */
11777void Machine::i_rollback(bool aNotify)
11778{
11779 AutoCaller autoCaller(this);
11780 AssertComRCReturn(autoCaller.rc(), (void)0);
11781
11782 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11783
11784 if (!mStorageControllers.isNull())
11785 {
11786 if (mStorageControllers.isBackedUp())
11787 {
11788 /* unitialize all new devices (absent in the backed up list). */
11789 StorageControllerList *backedList = mStorageControllers.backedUpData();
11790 for (StorageControllerList::const_iterator
11791 it = mStorageControllers->begin();
11792 it != mStorageControllers->end();
11793 ++it)
11794 {
11795 if ( std::find(backedList->begin(), backedList->end(), *it)
11796 == backedList->end()
11797 )
11798 {
11799 (*it)->uninit();
11800 }
11801 }
11802
11803 /* restore the list */
11804 mStorageControllers.rollback();
11805 }
11806
11807 /* rollback any changes to devices after restoring the list */
11808 if (mData->flModifications & IsModified_Storage)
11809 {
11810 for (StorageControllerList::const_iterator
11811 it = mStorageControllers->begin();
11812 it != mStorageControllers->end();
11813 ++it)
11814 {
11815 (*it)->i_rollback();
11816 }
11817 }
11818 }
11819
11820 if (!mUSBControllers.isNull())
11821 {
11822 if (mUSBControllers.isBackedUp())
11823 {
11824 /* unitialize all new devices (absent in the backed up list). */
11825 USBControllerList *backedList = mUSBControllers.backedUpData();
11826 for (USBControllerList::const_iterator
11827 it = mUSBControllers->begin();
11828 it != mUSBControllers->end();
11829 ++it)
11830 {
11831 if ( std::find(backedList->begin(), backedList->end(), *it)
11832 == backedList->end()
11833 )
11834 {
11835 (*it)->uninit();
11836 }
11837 }
11838
11839 /* restore the list */
11840 mUSBControllers.rollback();
11841 }
11842
11843 /* rollback any changes to devices after restoring the list */
11844 if (mData->flModifications & IsModified_USB)
11845 {
11846 for (USBControllerList::const_iterator
11847 it = mUSBControllers->begin();
11848 it != mUSBControllers->end();
11849 ++it)
11850 {
11851 (*it)->i_rollback();
11852 }
11853 }
11854 }
11855
11856 mUserData.rollback();
11857
11858 mHWData.rollback();
11859
11860 if (mData->flModifications & IsModified_Storage)
11861 i_rollbackMedia();
11862
11863 if (mBIOSSettings)
11864 mBIOSSettings->i_rollback();
11865
11866 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
11867 mVRDEServer->i_rollback();
11868
11869 if (mAudioAdapter)
11870 mAudioAdapter->i_rollback();
11871
11872 if (mUSBDeviceFilters && (mData->flModifications & IsModified_USB))
11873 mUSBDeviceFilters->i_rollback();
11874
11875 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
11876 mBandwidthControl->i_rollback();
11877
11878 if (!mHWData.isNull())
11879 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
11880 NetworkAdapterVector networkAdapters(mNetworkAdapters.size());
11881 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
11882 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
11883
11884 if (mData->flModifications & IsModified_NetworkAdapters)
11885 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
11886 if ( mNetworkAdapters[slot]
11887 && mNetworkAdapters[slot]->i_isModified())
11888 {
11889 mNetworkAdapters[slot]->i_rollback();
11890 networkAdapters[slot] = mNetworkAdapters[slot];
11891 }
11892
11893 if (mData->flModifications & IsModified_SerialPorts)
11894 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
11895 if ( mSerialPorts[slot]
11896 && mSerialPorts[slot]->i_isModified())
11897 {
11898 mSerialPorts[slot]->i_rollback();
11899 serialPorts[slot] = mSerialPorts[slot];
11900 }
11901
11902 if (mData->flModifications & IsModified_ParallelPorts)
11903 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
11904 if ( mParallelPorts[slot]
11905 && mParallelPorts[slot]->i_isModified())
11906 {
11907 mParallelPorts[slot]->i_rollback();
11908 parallelPorts[slot] = mParallelPorts[slot];
11909 }
11910
11911 if (aNotify)
11912 {
11913 /* inform the direct session about changes */
11914
11915 ComObjPtr<Machine> that = this;
11916 uint32_t flModifications = mData->flModifications;
11917 alock.release();
11918
11919 if (flModifications & IsModified_SharedFolders)
11920 that->i_onSharedFolderChange();
11921
11922 if (flModifications & IsModified_VRDEServer)
11923 that->i_onVRDEServerChange(/* aRestart */ TRUE);
11924 if (flModifications & IsModified_USB)
11925 that->i_onUSBControllerChange();
11926
11927 for (ULONG slot = 0; slot < networkAdapters.size(); ++slot)
11928 if (networkAdapters[slot])
11929 that->i_onNetworkAdapterChange(networkAdapters[slot], FALSE);
11930 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); ++slot)
11931 if (serialPorts[slot])
11932 that->i_onSerialPortChange(serialPorts[slot]);
11933 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); ++slot)
11934 if (parallelPorts[slot])
11935 that->i_onParallelPortChange(parallelPorts[slot]);
11936
11937 if (flModifications & IsModified_Storage)
11938 that->i_onStorageControllerChange();
11939
11940#if 0
11941 if (flModifications & IsModified_BandwidthControl)
11942 that->onBandwidthControlChange();
11943#endif
11944 }
11945}
11946
11947/**
11948 * Commits all the changes to machine settings.
11949 *
11950 * Note that this operation is supposed to never fail.
11951 *
11952 * @note Locks this object and children for writing.
11953 */
11954void Machine::i_commit()
11955{
11956 AutoCaller autoCaller(this);
11957 AssertComRCReturnVoid(autoCaller.rc());
11958
11959 AutoCaller peerCaller(mPeer);
11960 AssertComRCReturnVoid(peerCaller.rc());
11961
11962 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
11963
11964 /*
11965 * use safe commit to ensure Snapshot machines (that share mUserData)
11966 * will still refer to a valid memory location
11967 */
11968 mUserData.commitCopy();
11969
11970 mHWData.commit();
11971
11972 if (mMediumAttachments.isBackedUp())
11973 i_commitMedia(Global::IsOnline(mData->mMachineState));
11974
11975 mBIOSSettings->i_commit();
11976 mVRDEServer->i_commit();
11977 mAudioAdapter->i_commit();
11978 mUSBDeviceFilters->i_commit();
11979 mBandwidthControl->i_commit();
11980
11981 /* Since mNetworkAdapters is a list which might have been changed (resized)
11982 * without using the Backupable<> template we need to handle the copying
11983 * of the list entries manually, including the creation of peers for the
11984 * new objects. */
11985 bool commitNetworkAdapters = false;
11986 size_t newSize = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
11987 if (mPeer)
11988 {
11989 /* commit everything, even the ones which will go away */
11990 for (size_t slot = 0; slot < mNetworkAdapters.size(); slot++)
11991 mNetworkAdapters[slot]->i_commit();
11992 /* copy over the new entries, creating a peer and uninit the original */
11993 mPeer->mNetworkAdapters.resize(RT_MAX(newSize, mPeer->mNetworkAdapters.size()));
11994 for (size_t slot = 0; slot < newSize; slot++)
11995 {
11996 /* look if this adapter has a peer device */
11997 ComObjPtr<NetworkAdapter> peer = mNetworkAdapters[slot]->i_getPeer();
11998 if (!peer)
11999 {
12000 /* no peer means the adapter is a newly created one;
12001 * create a peer owning data this data share it with */
12002 peer.createObject();
12003 peer->init(mPeer, mNetworkAdapters[slot], true /* aReshare */);
12004 }
12005 mPeer->mNetworkAdapters[slot] = peer;
12006 }
12007 /* uninit any no longer needed network adapters */
12008 for (size_t slot = newSize; slot < mNetworkAdapters.size(); ++slot)
12009 mNetworkAdapters[slot]->uninit();
12010 for (size_t slot = newSize; slot < mPeer->mNetworkAdapters.size(); ++slot)
12011 {
12012 if (mPeer->mNetworkAdapters[slot])
12013 mPeer->mNetworkAdapters[slot]->uninit();
12014 }
12015 /* Keep the original network adapter count until this point, so that
12016 * discarding a chipset type change will not lose settings. */
12017 mNetworkAdapters.resize(newSize);
12018 mPeer->mNetworkAdapters.resize(newSize);
12019 }
12020 else
12021 {
12022 /* we have no peer (our parent is the newly created machine);
12023 * just commit changes to the network adapters */
12024 commitNetworkAdapters = true;
12025 }
12026 if (commitNetworkAdapters)
12027 for (size_t slot = 0; slot < mNetworkAdapters.size(); ++slot)
12028 mNetworkAdapters[slot]->i_commit();
12029
12030 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12031 mSerialPorts[slot]->i_commit();
12032 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12033 mParallelPorts[slot]->i_commit();
12034
12035 bool commitStorageControllers = false;
12036
12037 if (mStorageControllers.isBackedUp())
12038 {
12039 mStorageControllers.commit();
12040
12041 if (mPeer)
12042 {
12043 /* Commit all changes to new controllers (this will reshare data with
12044 * peers for those who have peers) */
12045 StorageControllerList *newList = new StorageControllerList();
12046 for (StorageControllerList::const_iterator
12047 it = mStorageControllers->begin();
12048 it != mStorageControllers->end();
12049 ++it)
12050 {
12051 (*it)->i_commit();
12052
12053 /* look if this controller has a peer device */
12054 ComObjPtr<StorageController> peer = (*it)->i_getPeer();
12055 if (!peer)
12056 {
12057 /* no peer means the device is a newly created one;
12058 * create a peer owning data this device share it with */
12059 peer.createObject();
12060 peer->init(mPeer, *it, true /* aReshare */);
12061 }
12062 else
12063 {
12064 /* remove peer from the old list */
12065 mPeer->mStorageControllers->remove(peer);
12066 }
12067 /* and add it to the new list */
12068 newList->push_back(peer);
12069 }
12070
12071 /* uninit old peer's controllers that are left */
12072 for (StorageControllerList::const_iterator
12073 it = mPeer->mStorageControllers->begin();
12074 it != mPeer->mStorageControllers->end();
12075 ++it)
12076 {
12077 (*it)->uninit();
12078 }
12079
12080 /* attach new list of controllers to our peer */
12081 mPeer->mStorageControllers.attach(newList);
12082 }
12083 else
12084 {
12085 /* we have no peer (our parent is the newly created machine);
12086 * just commit changes to devices */
12087 commitStorageControllers = true;
12088 }
12089 }
12090 else
12091 {
12092 /* the list of controllers itself is not changed,
12093 * just commit changes to controllers themselves */
12094 commitStorageControllers = true;
12095 }
12096
12097 if (commitStorageControllers)
12098 {
12099 for (StorageControllerList::const_iterator
12100 it = mStorageControllers->begin();
12101 it != mStorageControllers->end();
12102 ++it)
12103 {
12104 (*it)->i_commit();
12105 }
12106 }
12107
12108 bool commitUSBControllers = false;
12109
12110 if (mUSBControllers.isBackedUp())
12111 {
12112 mUSBControllers.commit();
12113
12114 if (mPeer)
12115 {
12116 /* Commit all changes to new controllers (this will reshare data with
12117 * peers for those who have peers) */
12118 USBControllerList *newList = new USBControllerList();
12119 for (USBControllerList::const_iterator
12120 it = mUSBControllers->begin();
12121 it != mUSBControllers->end();
12122 ++it)
12123 {
12124 (*it)->i_commit();
12125
12126 /* look if this controller has a peer device */
12127 ComObjPtr<USBController> peer = (*it)->i_getPeer();
12128 if (!peer)
12129 {
12130 /* no peer means the device is a newly created one;
12131 * create a peer owning data this device share it with */
12132 peer.createObject();
12133 peer->init(mPeer, *it, true /* aReshare */);
12134 }
12135 else
12136 {
12137 /* remove peer from the old list */
12138 mPeer->mUSBControllers->remove(peer);
12139 }
12140 /* and add it to the new list */
12141 newList->push_back(peer);
12142 }
12143
12144 /* uninit old peer's controllers that are left */
12145 for (USBControllerList::const_iterator
12146 it = mPeer->mUSBControllers->begin();
12147 it != mPeer->mUSBControllers->end();
12148 ++it)
12149 {
12150 (*it)->uninit();
12151 }
12152
12153 /* attach new list of controllers to our peer */
12154 mPeer->mUSBControllers.attach(newList);
12155 }
12156 else
12157 {
12158 /* we have no peer (our parent is the newly created machine);
12159 * just commit changes to devices */
12160 commitUSBControllers = true;
12161 }
12162 }
12163 else
12164 {
12165 /* the list of controllers itself is not changed,
12166 * just commit changes to controllers themselves */
12167 commitUSBControllers = true;
12168 }
12169
12170 if (commitUSBControllers)
12171 {
12172 for (USBControllerList::const_iterator
12173 it = mUSBControllers->begin();
12174 it != mUSBControllers->end();
12175 ++it)
12176 {
12177 (*it)->i_commit();
12178 }
12179 }
12180
12181 if (i_isSessionMachine())
12182 {
12183 /* attach new data to the primary machine and reshare it */
12184 mPeer->mUserData.attach(mUserData);
12185 mPeer->mHWData.attach(mHWData);
12186 /* mmMediumAttachments is reshared by fixupMedia */
12187 // mPeer->mMediumAttachments.attach(mMediumAttachments);
12188 Assert(mPeer->mMediumAttachments.data() == mMediumAttachments.data());
12189 }
12190}
12191
12192/**
12193 * Copies all the hardware data from the given machine.
12194 *
12195 * Currently, only called when the VM is being restored from a snapshot. In
12196 * particular, this implies that the VM is not running during this method's
12197 * call.
12198 *
12199 * @note This method must be called from under this object's lock.
12200 *
12201 * @note This method doesn't call #i_commit(), so all data remains backed up and
12202 * unsaved.
12203 */
12204void Machine::i_copyFrom(Machine *aThat)
12205{
12206 AssertReturnVoid(!i_isSnapshotMachine());
12207 AssertReturnVoid(aThat->i_isSnapshotMachine());
12208
12209 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
12210
12211 mHWData.assignCopy(aThat->mHWData);
12212
12213 // create copies of all shared folders (mHWData after attaching a copy
12214 // contains just references to original objects)
12215 for (HWData::SharedFolderList::iterator
12216 it = mHWData->mSharedFolders.begin();
12217 it != mHWData->mSharedFolders.end();
12218 ++it)
12219 {
12220 ComObjPtr<SharedFolder> folder;
12221 folder.createObject();
12222 HRESULT rc = folder->initCopy(i_getMachine(), *it);
12223 AssertComRC(rc);
12224 *it = folder;
12225 }
12226
12227 mBIOSSettings->i_copyFrom(aThat->mBIOSSettings);
12228 mVRDEServer->i_copyFrom(aThat->mVRDEServer);
12229 mAudioAdapter->i_copyFrom(aThat->mAudioAdapter);
12230 mUSBDeviceFilters->i_copyFrom(aThat->mUSBDeviceFilters);
12231 mBandwidthControl->i_copyFrom(aThat->mBandwidthControl);
12232
12233 /* create private copies of all controllers */
12234 mStorageControllers.backup();
12235 mStorageControllers->clear();
12236 for (StorageControllerList::const_iterator
12237 it = aThat->mStorageControllers->begin();
12238 it != aThat->mStorageControllers->end();
12239 ++it)
12240 {
12241 ComObjPtr<StorageController> ctrl;
12242 ctrl.createObject();
12243 ctrl->initCopy(this, *it);
12244 mStorageControllers->push_back(ctrl);
12245 }
12246
12247 /* create private copies of all USB controllers */
12248 mUSBControllers.backup();
12249 mUSBControllers->clear();
12250 for (USBControllerList::const_iterator
12251 it = aThat->mUSBControllers->begin();
12252 it != aThat->mUSBControllers->end();
12253 ++it)
12254 {
12255 ComObjPtr<USBController> ctrl;
12256 ctrl.createObject();
12257 ctrl->initCopy(this, *it);
12258 mUSBControllers->push_back(ctrl);
12259 }
12260
12261 mNetworkAdapters.resize(aThat->mNetworkAdapters.size());
12262 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12263 {
12264 if (mNetworkAdapters[slot].isNotNull())
12265 mNetworkAdapters[slot]->i_copyFrom(aThat->mNetworkAdapters[slot]);
12266 else
12267 {
12268 unconst(mNetworkAdapters[slot]).createObject();
12269 mNetworkAdapters[slot]->initCopy(this, aThat->mNetworkAdapters[slot]);
12270 }
12271 }
12272 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12273 mSerialPorts[slot]->i_copyFrom(aThat->mSerialPorts[slot]);
12274 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12275 mParallelPorts[slot]->i_copyFrom(aThat->mParallelPorts[slot]);
12276}
12277
12278/**
12279 * Returns whether the given storage controller is hotplug capable.
12280 *
12281 * @returns true if the controller supports hotplugging
12282 * false otherwise.
12283 * @param enmCtrlType The controller type to check for.
12284 */
12285bool Machine::i_isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
12286{
12287 ComPtr<ISystemProperties> systemProperties;
12288 HRESULT rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
12289 if (FAILED(rc))
12290 return false;
12291
12292 BOOL aHotplugCapable = FALSE;
12293 systemProperties->GetStorageControllerHotplugCapable(enmCtrlType, &aHotplugCapable);
12294
12295 return RT_BOOL(aHotplugCapable);
12296}
12297
12298#ifdef VBOX_WITH_RESOURCE_USAGE_API
12299
12300void Machine::i_getDiskList(MediaList &list)
12301{
12302 for (MediumAttachmentList::const_iterator
12303 it = mMediumAttachments->begin();
12304 it != mMediumAttachments->end();
12305 ++it)
12306 {
12307 MediumAttachment *pAttach = *it;
12308 /* just in case */
12309 AssertContinue(pAttach);
12310
12311 AutoCaller localAutoCallerA(pAttach);
12312 if (FAILED(localAutoCallerA.rc())) continue;
12313
12314 AutoReadLock local_alockA(pAttach COMMA_LOCKVAL_SRC_POS);
12315
12316 if (pAttach->i_getType() == DeviceType_HardDisk)
12317 list.push_back(pAttach->i_getMedium());
12318 }
12319}
12320
12321void Machine::i_registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
12322{
12323 AssertReturnVoid(isWriteLockOnCurrentThread());
12324 AssertPtrReturnVoid(aCollector);
12325
12326 pm::CollectorHAL *hal = aCollector->getHAL();
12327 /* Create sub metrics */
12328 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
12329 "Percentage of processor time spent in user mode by the VM process.");
12330 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
12331 "Percentage of processor time spent in kernel mode by the VM process.");
12332 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
12333 "Size of resident portion of VM process in memory.");
12334 pm::SubMetric *diskUsageUsed = new pm::SubMetric("Disk/Usage/Used",
12335 "Actual size of all VM disks combined.");
12336 pm::SubMetric *machineNetRx = new pm::SubMetric("Net/Rate/Rx",
12337 "Network receive rate.");
12338 pm::SubMetric *machineNetTx = new pm::SubMetric("Net/Rate/Tx",
12339 "Network transmit rate.");
12340 /* Create and register base metrics */
12341 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
12342 cpuLoadUser, cpuLoadKernel);
12343 aCollector->registerBaseMetric(cpuLoad);
12344 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
12345 ramUsageUsed);
12346 aCollector->registerBaseMetric(ramUsage);
12347 MediaList disks;
12348 i_getDiskList(disks);
12349 pm::BaseMetric *diskUsage = new pm::MachineDiskUsage(hal, aMachine, disks,
12350 diskUsageUsed);
12351 aCollector->registerBaseMetric(diskUsage);
12352
12353 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
12354 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12355 new pm::AggregateAvg()));
12356 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12357 new pm::AggregateMin()));
12358 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12359 new pm::AggregateMax()));
12360 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
12361 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12362 new pm::AggregateAvg()));
12363 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12364 new pm::AggregateMin()));
12365 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12366 new pm::AggregateMax()));
12367
12368 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
12369 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12370 new pm::AggregateAvg()));
12371 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12372 new pm::AggregateMin()));
12373 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12374 new pm::AggregateMax()));
12375
12376 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed, 0));
12377 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12378 new pm::AggregateAvg()));
12379 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12380 new pm::AggregateMin()));
12381 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12382 new pm::AggregateMax()));
12383
12384
12385 /* Guest metrics collector */
12386 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
12387 aCollector->registerGuest(mCollectorGuest);
12388 Log7Func(("{%p}: mCollectorGuest=%p\n", this, mCollectorGuest));
12389
12390 /* Create sub metrics */
12391 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
12392 "Percentage of processor time spent in user mode as seen by the guest.");
12393 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
12394 "Percentage of processor time spent in kernel mode as seen by the guest.");
12395 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
12396 "Percentage of processor time spent idling as seen by the guest.");
12397
12398 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
12399 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
12400 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
12401 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
12402 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
12403 pm::SubMetric *guestMemCache = new pm::SubMetric(
12404 "Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
12405
12406 pm::SubMetric *guestPagedTotal = new pm::SubMetric(
12407 "Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
12408
12409 /* Create and register base metrics */
12410 pm::BaseMetric *machineNetRate = new pm::MachineNetRate(mCollectorGuest, aMachine,
12411 machineNetRx, machineNetTx);
12412 aCollector->registerBaseMetric(machineNetRate);
12413
12414 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
12415 guestLoadUser, guestLoadKernel, guestLoadIdle);
12416 aCollector->registerBaseMetric(guestCpuLoad);
12417
12418 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
12419 guestMemTotal, guestMemFree,
12420 guestMemBalloon, guestMemShared,
12421 guestMemCache, guestPagedTotal);
12422 aCollector->registerBaseMetric(guestCpuMem);
12423
12424 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, 0));
12425 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateAvg()));
12426 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMin()));
12427 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMax()));
12428
12429 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, 0));
12430 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateAvg()));
12431 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMin()));
12432 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMax()));
12433
12434 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
12435 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
12436 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
12437 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
12438
12439 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
12440 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
12441 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
12442 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
12443
12444 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
12445 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
12446 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
12447 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
12448
12449 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
12450 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
12451 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
12452 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
12453
12454 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
12455 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
12456 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
12457 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
12458
12459 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
12460 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
12461 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
12462 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
12463
12464 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
12465 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
12466 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
12467 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
12468
12469 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
12470 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
12471 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
12472 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
12473
12474 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
12475 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
12476 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
12477 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
12478}
12479
12480void Machine::i_unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
12481{
12482 AssertReturnVoid(isWriteLockOnCurrentThread());
12483
12484 if (aCollector)
12485 {
12486 aCollector->unregisterMetricsFor(aMachine);
12487 aCollector->unregisterBaseMetricsFor(aMachine);
12488 }
12489}
12490
12491#endif /* VBOX_WITH_RESOURCE_USAGE_API */
12492
12493
12494////////////////////////////////////////////////////////////////////////////////
12495
12496DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
12497
12498HRESULT SessionMachine::FinalConstruct()
12499{
12500 LogFlowThisFunc(("\n"));
12501
12502 mClientToken = NULL;
12503
12504 return BaseFinalConstruct();
12505}
12506
12507void SessionMachine::FinalRelease()
12508{
12509 LogFlowThisFunc(("\n"));
12510
12511 Assert(!mClientToken);
12512 /* paranoia, should not hang around any more */
12513 if (mClientToken)
12514 {
12515 delete mClientToken;
12516 mClientToken = NULL;
12517 }
12518
12519 uninit(Uninit::Unexpected);
12520
12521 BaseFinalRelease();
12522}
12523
12524/**
12525 * @note Must be called only by Machine::LockMachine() from its own write lock.
12526 */
12527HRESULT SessionMachine::init(Machine *aMachine)
12528{
12529 LogFlowThisFuncEnter();
12530 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
12531
12532 AssertReturn(aMachine, E_INVALIDARG);
12533
12534 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
12535
12536 /* Enclose the state transition NotReady->InInit->Ready */
12537 AutoInitSpan autoInitSpan(this);
12538 AssertReturn(autoInitSpan.isOk(), E_FAIL);
12539
12540 HRESULT rc = S_OK;
12541
12542 RT_ZERO(mAuthLibCtx);
12543
12544 /* create the machine client token */
12545 try
12546 {
12547 mClientToken = new ClientToken(aMachine, this);
12548 if (!mClientToken->isReady())
12549 {
12550 delete mClientToken;
12551 mClientToken = NULL;
12552 rc = E_FAIL;
12553 }
12554 }
12555 catch (std::bad_alloc &)
12556 {
12557 rc = E_OUTOFMEMORY;
12558 }
12559 if (FAILED(rc))
12560 return rc;
12561
12562 /* memorize the peer Machine */
12563 unconst(mPeer) = aMachine;
12564 /* share the parent pointer */
12565 unconst(mParent) = aMachine->mParent;
12566
12567 /* take the pointers to data to share */
12568 mData.share(aMachine->mData);
12569 mSSData.share(aMachine->mSSData);
12570
12571 mUserData.share(aMachine->mUserData);
12572 mHWData.share(aMachine->mHWData);
12573 mMediumAttachments.share(aMachine->mMediumAttachments);
12574
12575 mStorageControllers.allocate();
12576 for (StorageControllerList::const_iterator
12577 it = aMachine->mStorageControllers->begin();
12578 it != aMachine->mStorageControllers->end();
12579 ++it)
12580 {
12581 ComObjPtr<StorageController> ctl;
12582 ctl.createObject();
12583 ctl->init(this, *it);
12584 mStorageControllers->push_back(ctl);
12585 }
12586
12587 mUSBControllers.allocate();
12588 for (USBControllerList::const_iterator
12589 it = aMachine->mUSBControllers->begin();
12590 it != aMachine->mUSBControllers->end();
12591 ++it)
12592 {
12593 ComObjPtr<USBController> ctl;
12594 ctl.createObject();
12595 ctl->init(this, *it);
12596 mUSBControllers->push_back(ctl);
12597 }
12598
12599 unconst(mBIOSSettings).createObject();
12600 mBIOSSettings->init(this, aMachine->mBIOSSettings);
12601 /* create another VRDEServer object that will be mutable */
12602 unconst(mVRDEServer).createObject();
12603 mVRDEServer->init(this, aMachine->mVRDEServer);
12604 /* create another audio adapter object that will be mutable */
12605 unconst(mAudioAdapter).createObject();
12606 mAudioAdapter->init(this, aMachine->mAudioAdapter);
12607 /* create a list of serial ports that will be mutable */
12608 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12609 {
12610 unconst(mSerialPorts[slot]).createObject();
12611 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
12612 }
12613 /* create a list of parallel ports that will be mutable */
12614 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12615 {
12616 unconst(mParallelPorts[slot]).createObject();
12617 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
12618 }
12619
12620 /* create another USB device filters object that will be mutable */
12621 unconst(mUSBDeviceFilters).createObject();
12622 mUSBDeviceFilters->init(this, aMachine->mUSBDeviceFilters);
12623
12624 /* create a list of network adapters that will be mutable */
12625 mNetworkAdapters.resize(aMachine->mNetworkAdapters.size());
12626 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12627 {
12628 unconst(mNetworkAdapters[slot]).createObject();
12629 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
12630 }
12631
12632 /* create another bandwidth control object that will be mutable */
12633 unconst(mBandwidthControl).createObject();
12634 mBandwidthControl->init(this, aMachine->mBandwidthControl);
12635
12636 /* default is to delete saved state on Saved -> PoweredOff transition */
12637 mRemoveSavedState = true;
12638
12639 /* Confirm a successful initialization when it's the case */
12640 autoInitSpan.setSucceeded();
12641
12642 miNATNetworksStarted = 0;
12643
12644 LogFlowThisFuncLeave();
12645 return rc;
12646}
12647
12648/**
12649 * Uninitializes this session object. If the reason is other than
12650 * Uninit::Unexpected, then this method MUST be called from #i_checkForDeath()
12651 * or the client watcher code.
12652 *
12653 * @param aReason uninitialization reason
12654 *
12655 * @note Locks mParent + this object for writing.
12656 */
12657void SessionMachine::uninit(Uninit::Reason aReason)
12658{
12659 LogFlowThisFuncEnter();
12660 LogFlowThisFunc(("reason=%d\n", aReason));
12661
12662 /*
12663 * Strongly reference ourselves to prevent this object deletion after
12664 * mData->mSession.mMachine.setNull() below (which can release the last
12665 * reference and call the destructor). Important: this must be done before
12666 * accessing any members (and before AutoUninitSpan that does it as well).
12667 * This self reference will be released as the very last step on return.
12668 */
12669 ComObjPtr<SessionMachine> selfRef;
12670 if (aReason != Uninit::Unexpected)
12671 selfRef = this;
12672
12673 /* Enclose the state transition Ready->InUninit->NotReady */
12674 AutoUninitSpan autoUninitSpan(this);
12675 if (autoUninitSpan.uninitDone())
12676 {
12677 LogFlowThisFunc(("Already uninitialized\n"));
12678 LogFlowThisFuncLeave();
12679 return;
12680 }
12681
12682 if (autoUninitSpan.initFailed())
12683 {
12684 /* We've been called by init() because it's failed. It's not really
12685 * necessary (nor it's safe) to perform the regular uninit sequence
12686 * below, the following is enough.
12687 */
12688 LogFlowThisFunc(("Initialization failed.\n"));
12689 /* destroy the machine client token */
12690 if (mClientToken)
12691 {
12692 delete mClientToken;
12693 mClientToken = NULL;
12694 }
12695 uninitDataAndChildObjects();
12696 mData.free();
12697 unconst(mParent) = NULL;
12698 unconst(mPeer) = NULL;
12699 LogFlowThisFuncLeave();
12700 return;
12701 }
12702
12703 MachineState_T lastState;
12704 {
12705 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
12706 lastState = mData->mMachineState;
12707 }
12708 NOREF(lastState);
12709
12710#ifdef VBOX_WITH_USB
12711 // release all captured USB devices, but do this before requesting the locks below
12712 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
12713 {
12714 /* Console::captureUSBDevices() is called in the VM process only after
12715 * setting the machine state to Starting or Restoring.
12716 * Console::detachAllUSBDevices() will be called upon successful
12717 * termination. So, we need to release USB devices only if there was
12718 * an abnormal termination of a running VM.
12719 *
12720 * This is identical to SessionMachine::DetachAllUSBDevices except
12721 * for the aAbnormal argument. */
12722 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
12723 AssertComRC(rc);
12724 NOREF(rc);
12725
12726 USBProxyService *service = mParent->i_host()->i_usbProxyService();
12727 if (service)
12728 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
12729 }
12730#endif /* VBOX_WITH_USB */
12731
12732 // we need to lock this object in uninit() because the lock is shared
12733 // with mPeer (as well as data we modify below). mParent lock is needed
12734 // by several calls to it.
12735 AutoMultiWriteLock2 multilock(mParent, this COMMA_LOCKVAL_SRC_POS);
12736
12737#ifdef VBOX_WITH_RESOURCE_USAGE_API
12738 /*
12739 * It is safe to call Machine::i_unregisterMetrics() here because
12740 * PerformanceCollector::samplerCallback no longer accesses guest methods
12741 * holding the lock.
12742 */
12743 i_unregisterMetrics(mParent->i_performanceCollector(), mPeer);
12744 /* The guest must be unregistered after its metrics (@bugref{5949}). */
12745 Log7Func(("{%p}: mCollectorGuest=%p\n", this, mCollectorGuest));
12746 if (mCollectorGuest)
12747 {
12748 mParent->i_performanceCollector()->unregisterGuest(mCollectorGuest);
12749 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
12750 mCollectorGuest = NULL;
12751 }
12752#endif
12753
12754 if (aReason == Uninit::Abnormal)
12755 {
12756 Log1WarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n", Global::IsOnlineOrTransient(lastState)));
12757
12758 /* reset the state to Aborted */
12759 if (mData->mMachineState != MachineState_Aborted)
12760 i_setMachineState(MachineState_Aborted);
12761 }
12762
12763 // any machine settings modified?
12764 if (mData->flModifications)
12765 {
12766 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
12767 i_rollback(false /* aNotify */);
12768 }
12769
12770 mData->mSession.mPID = NIL_RTPROCESS;
12771
12772 if (aReason == Uninit::Unexpected)
12773 {
12774 /* Uninitialization didn't come from #i_checkForDeath(), so tell the
12775 * client watcher thread to update the set of machines that have open
12776 * sessions. */
12777 mParent->i_updateClientWatcher();
12778 }
12779
12780 /* uninitialize all remote controls */
12781 if (mData->mSession.mRemoteControls.size())
12782 {
12783 LogFlowThisFunc(("Closing remote sessions (%d):\n",
12784 mData->mSession.mRemoteControls.size()));
12785
12786 /* Always restart a the beginning, since the iterator is invalidated
12787 * by using erase(). */
12788 for (Data::Session::RemoteControlList::iterator
12789 it = mData->mSession.mRemoteControls.begin();
12790 it != mData->mSession.mRemoteControls.end();
12791 it = mData->mSession.mRemoteControls.begin())
12792 {
12793 ComPtr<IInternalSessionControl> pControl = *it;
12794 mData->mSession.mRemoteControls.erase(it);
12795 multilock.release();
12796 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
12797 HRESULT rc = pControl->Uninitialize();
12798 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
12799 if (FAILED(rc))
12800 Log1WarningThisFunc(("Forgot to close the remote session?\n"));
12801 multilock.acquire();
12802 }
12803 mData->mSession.mRemoteControls.clear();
12804 }
12805
12806 /* Remove all references to the NAT network service. The service will stop
12807 * if all references (also from other VMs) are removed. */
12808 for (; miNATNetworksStarted > 0; miNATNetworksStarted--)
12809 {
12810 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12811 {
12812 BOOL enabled;
12813 HRESULT hrc = mNetworkAdapters[slot]->COMGETTER(Enabled)(&enabled);
12814 if ( FAILED(hrc)
12815 || !enabled)
12816 continue;
12817
12818 NetworkAttachmentType_T type;
12819 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
12820 if ( SUCCEEDED(hrc)
12821 && type == NetworkAttachmentType_NATNetwork)
12822 {
12823 Bstr name;
12824 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
12825 if (SUCCEEDED(hrc))
12826 {
12827 multilock.release();
12828 Utf8Str strName(name);
12829 LogRel(("VM '%s' stops using NAT network '%s'\n",
12830 mUserData->s.strName.c_str(), strName.c_str()));
12831 mParent->i_natNetworkRefDec(strName);
12832 multilock.acquire();
12833 }
12834 }
12835 }
12836 }
12837
12838 /*
12839 * An expected uninitialization can come only from #i_checkForDeath().
12840 * Otherwise it means that something's gone really wrong (for example,
12841 * the Session implementation has released the VirtualBox reference
12842 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
12843 * etc). However, it's also possible, that the client releases the IPC
12844 * semaphore correctly (i.e. before it releases the VirtualBox reference),
12845 * but the VirtualBox release event comes first to the server process.
12846 * This case is practically possible, so we should not assert on an
12847 * unexpected uninit, just log a warning.
12848 */
12849
12850 if (aReason == Uninit::Unexpected)
12851 Log1WarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
12852
12853 if (aReason != Uninit::Normal)
12854 {
12855 mData->mSession.mDirectControl.setNull();
12856 }
12857 else
12858 {
12859 /* this must be null here (see #OnSessionEnd()) */
12860 Assert(mData->mSession.mDirectControl.isNull());
12861 Assert(mData->mSession.mState == SessionState_Unlocking);
12862 Assert(!mData->mSession.mProgress.isNull());
12863 }
12864 if (mData->mSession.mProgress)
12865 {
12866 if (aReason == Uninit::Normal)
12867 mData->mSession.mProgress->i_notifyComplete(S_OK);
12868 else
12869 mData->mSession.mProgress->i_notifyComplete(E_FAIL,
12870 COM_IIDOF(ISession),
12871 getComponentName(),
12872 tr("The VM session was aborted"));
12873 mData->mSession.mProgress.setNull();
12874 }
12875
12876 if (mConsoleTaskData.mProgress)
12877 {
12878 Assert(aReason == Uninit::Abnormal);
12879 mConsoleTaskData.mProgress->i_notifyComplete(E_FAIL,
12880 COM_IIDOF(ISession),
12881 getComponentName(),
12882 tr("The VM session was aborted"));
12883 mConsoleTaskData.mProgress.setNull();
12884 }
12885
12886 /* remove the association between the peer machine and this session machine */
12887 Assert( (SessionMachine*)mData->mSession.mMachine == this
12888 || aReason == Uninit::Unexpected);
12889
12890 /* reset the rest of session data */
12891 mData->mSession.mLockType = LockType_Null;
12892 mData->mSession.mMachine.setNull();
12893 mData->mSession.mState = SessionState_Unlocked;
12894 mData->mSession.mName.setNull();
12895
12896 /* destroy the machine client token before leaving the exclusive lock */
12897 if (mClientToken)
12898 {
12899 delete mClientToken;
12900 mClientToken = NULL;
12901 }
12902
12903 /* fire an event */
12904 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
12905
12906 uninitDataAndChildObjects();
12907
12908 /* free the essential data structure last */
12909 mData.free();
12910
12911 /* release the exclusive lock before setting the below two to NULL */
12912 multilock.release();
12913
12914 unconst(mParent) = NULL;
12915 unconst(mPeer) = NULL;
12916
12917 AuthLibUnload(&mAuthLibCtx);
12918
12919 LogFlowThisFuncLeave();
12920}
12921
12922// util::Lockable interface
12923////////////////////////////////////////////////////////////////////////////////
12924
12925/**
12926 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
12927 * with the primary Machine instance (mPeer).
12928 */
12929RWLockHandle *SessionMachine::lockHandle() const
12930{
12931 AssertReturn(mPeer != NULL, NULL);
12932 return mPeer->lockHandle();
12933}
12934
12935// IInternalMachineControl methods
12936////////////////////////////////////////////////////////////////////////////////
12937
12938/**
12939 * Passes collected guest statistics to performance collector object
12940 */
12941HRESULT SessionMachine::reportVmStatistics(ULONG aValidStats, ULONG aCpuUser,
12942 ULONG aCpuKernel, ULONG aCpuIdle,
12943 ULONG aMemTotal, ULONG aMemFree,
12944 ULONG aMemBalloon, ULONG aMemShared,
12945 ULONG aMemCache, ULONG aPageTotal,
12946 ULONG aAllocVMM, ULONG aFreeVMM,
12947 ULONG aBalloonedVMM, ULONG aSharedVMM,
12948 ULONG aVmNetRx, ULONG aVmNetTx)
12949{
12950#ifdef VBOX_WITH_RESOURCE_USAGE_API
12951 if (mCollectorGuest)
12952 mCollectorGuest->updateStats(aValidStats, aCpuUser, aCpuKernel, aCpuIdle,
12953 aMemTotal, aMemFree, aMemBalloon, aMemShared,
12954 aMemCache, aPageTotal, aAllocVMM, aFreeVMM,
12955 aBalloonedVMM, aSharedVMM, aVmNetRx, aVmNetTx);
12956
12957 return S_OK;
12958#else
12959 NOREF(aValidStats);
12960 NOREF(aCpuUser);
12961 NOREF(aCpuKernel);
12962 NOREF(aCpuIdle);
12963 NOREF(aMemTotal);
12964 NOREF(aMemFree);
12965 NOREF(aMemBalloon);
12966 NOREF(aMemShared);
12967 NOREF(aMemCache);
12968 NOREF(aPageTotal);
12969 NOREF(aAllocVMM);
12970 NOREF(aFreeVMM);
12971 NOREF(aBalloonedVMM);
12972 NOREF(aSharedVMM);
12973 NOREF(aVmNetRx);
12974 NOREF(aVmNetTx);
12975 return E_NOTIMPL;
12976#endif
12977}
12978
12979////////////////////////////////////////////////////////////////////////////////
12980//
12981// SessionMachine task records
12982//
12983////////////////////////////////////////////////////////////////////////////////
12984
12985/**
12986 * Task record for saving the machine state.
12987 */
12988class SessionMachine::SaveStateTask
12989 : public Machine::Task
12990{
12991public:
12992 SaveStateTask(SessionMachine *m,
12993 Progress *p,
12994 const Utf8Str &t,
12995 Reason_T enmReason,
12996 const Utf8Str &strStateFilePath)
12997 : Task(m, p, t),
12998 m_enmReason(enmReason),
12999 m_strStateFilePath(strStateFilePath)
13000 {}
13001
13002private:
13003 void handler()
13004 {
13005 ((SessionMachine *)(Machine *)m_pMachine)->i_saveStateHandler(*this);
13006 }
13007
13008 Reason_T m_enmReason;
13009 Utf8Str m_strStateFilePath;
13010
13011 friend class SessionMachine;
13012};
13013
13014/**
13015 * Task thread implementation for SessionMachine::SaveState(), called from
13016 * SessionMachine::taskHandler().
13017 *
13018 * @note Locks this object for writing.
13019 *
13020 * @param task
13021 * @return
13022 */
13023void SessionMachine::i_saveStateHandler(SaveStateTask &task)
13024{
13025 LogFlowThisFuncEnter();
13026
13027 AutoCaller autoCaller(this);
13028 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
13029 if (FAILED(autoCaller.rc()))
13030 {
13031 /* we might have been uninitialized because the session was accidentally
13032 * closed by the client, so don't assert */
13033 HRESULT rc = setError(E_FAIL,
13034 tr("The session has been accidentally closed"));
13035 task.m_pProgress->i_notifyComplete(rc);
13036 LogFlowThisFuncLeave();
13037 return;
13038 }
13039
13040 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13041
13042 HRESULT rc = S_OK;
13043
13044 try
13045 {
13046 ComPtr<IInternalSessionControl> directControl;
13047 if (mData->mSession.mLockType == LockType_VM)
13048 directControl = mData->mSession.mDirectControl;
13049 if (directControl.isNull())
13050 throw setError(VBOX_E_INVALID_VM_STATE,
13051 tr("Trying to save state without a running VM"));
13052 alock.release();
13053 BOOL fSuspendedBySave;
13054 rc = directControl->SaveStateWithReason(task.m_enmReason, task.m_pProgress, Bstr(task.m_strStateFilePath).raw(), task.m_machineStateBackup != MachineState_Paused, &fSuspendedBySave);
13055 Assert(!fSuspendedBySave);
13056 alock.acquire();
13057
13058 AssertStmt( (SUCCEEDED(rc) && mData->mMachineState == MachineState_Saved)
13059 || (FAILED(rc) && mData->mMachineState == MachineState_Saving),
13060 throw E_FAIL);
13061
13062 if (SUCCEEDED(rc))
13063 {
13064 mSSData->strStateFilePath = task.m_strStateFilePath;
13065
13066 /* save all VM settings */
13067 rc = i_saveSettings(NULL);
13068 // no need to check whether VirtualBox.xml needs saving also since
13069 // we can't have a name change pending at this point
13070 }
13071 else
13072 {
13073 // On failure, set the state to the state we had at the beginning.
13074 i_setMachineState(task.m_machineStateBackup);
13075 i_updateMachineStateOnClient();
13076
13077 // Delete the saved state file (might have been already created).
13078 // No need to check whether this is shared with a snapshot here
13079 // because we certainly created a fresh saved state file here.
13080 RTFileDelete(task.m_strStateFilePath.c_str());
13081 }
13082 }
13083 catch (HRESULT aRC) { rc = aRC; }
13084
13085 task.m_pProgress->i_notifyComplete(rc);
13086
13087 LogFlowThisFuncLeave();
13088}
13089
13090/**
13091 * @note Locks this object for writing.
13092 */
13093HRESULT SessionMachine::saveState(ComPtr<IProgress> &aProgress)
13094{
13095 return i_saveStateWithReason(Reason_Unspecified, aProgress);
13096}
13097
13098HRESULT SessionMachine::i_saveStateWithReason(Reason_T aReason, ComPtr<IProgress> &aProgress)
13099{
13100 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13101
13102 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
13103 if (FAILED(rc)) return rc;
13104
13105 if ( mData->mMachineState != MachineState_Running
13106 && mData->mMachineState != MachineState_Paused
13107 )
13108 return setError(VBOX_E_INVALID_VM_STATE,
13109 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
13110 Global::stringifyMachineState(mData->mMachineState));
13111
13112 ComObjPtr<Progress> pProgress;
13113 pProgress.createObject();
13114 rc = pProgress->init(i_getVirtualBox(),
13115 static_cast<IMachine *>(this) /* aInitiator */,
13116 tr("Saving the execution state of the virtual machine"),
13117 FALSE /* aCancelable */);
13118 if (FAILED(rc))
13119 return rc;
13120
13121 Utf8Str strStateFilePath;
13122 i_composeSavedStateFilename(strStateFilePath);
13123
13124 /* create and start the task on a separate thread (note that it will not
13125 * start working until we release alock) */
13126 SaveStateTask *pTask = new SaveStateTask(this, pProgress, "SaveState", aReason, strStateFilePath);
13127 rc = pTask->createThread();
13128 if (FAILED(rc))
13129 return rc;
13130
13131 /* set the state to Saving (expected by Session::SaveStateWithReason()) */
13132 i_setMachineState(MachineState_Saving);
13133 i_updateMachineStateOnClient();
13134
13135 pProgress.queryInterfaceTo(aProgress.asOutParam());
13136
13137 return S_OK;
13138}
13139
13140/**
13141 * @note Locks this object for writing.
13142 */
13143HRESULT SessionMachine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
13144{
13145 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13146
13147 HRESULT rc = i_checkStateDependency(MutableStateDep);
13148 if (FAILED(rc)) return rc;
13149
13150 if ( mData->mMachineState != MachineState_PoweredOff
13151 && mData->mMachineState != MachineState_Teleported
13152 && mData->mMachineState != MachineState_Aborted
13153 )
13154 return setError(VBOX_E_INVALID_VM_STATE,
13155 tr("Cannot adopt the saved machine state as the machine is not in Powered Off, Teleported or Aborted state (machine state: %s)"),
13156 Global::stringifyMachineState(mData->mMachineState));
13157
13158 com::Utf8Str stateFilePathFull;
13159 int vrc = i_calculateFullPath(aSavedStateFile, stateFilePathFull);
13160 if (RT_FAILURE(vrc))
13161 return setError(VBOX_E_FILE_ERROR,
13162 tr("Invalid saved state file path '%s' (%Rrc)"),
13163 aSavedStateFile.c_str(),
13164 vrc);
13165
13166 mSSData->strStateFilePath = stateFilePathFull;
13167
13168 /* The below i_setMachineState() will detect the state transition and will
13169 * update the settings file */
13170
13171 return i_setMachineState(MachineState_Saved);
13172}
13173
13174/**
13175 * @note Locks this object for writing.
13176 */
13177HRESULT SessionMachine::discardSavedState(BOOL aFRemoveFile)
13178{
13179 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13180
13181 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
13182 if (FAILED(rc)) return rc;
13183
13184 if (mData->mMachineState != MachineState_Saved)
13185 return setError(VBOX_E_INVALID_VM_STATE,
13186 tr("Cannot delete the machine state as the machine is not in the saved state (machine state: %s)"),
13187 Global::stringifyMachineState(mData->mMachineState));
13188
13189 mRemoveSavedState = RT_BOOL(aFRemoveFile);
13190
13191 /*
13192 * Saved -> PoweredOff transition will be detected in the SessionMachine
13193 * and properly handled.
13194 */
13195 rc = i_setMachineState(MachineState_PoweredOff);
13196 return rc;
13197}
13198
13199
13200/**
13201 * @note Locks the same as #i_setMachineState() does.
13202 */
13203HRESULT SessionMachine::updateState(MachineState_T aState)
13204{
13205 return i_setMachineState(aState);
13206}
13207
13208/**
13209 * @note Locks this object for writing.
13210 */
13211HRESULT SessionMachine::beginPowerUp(const ComPtr<IProgress> &aProgress)
13212{
13213 IProgress *pProgress(aProgress);
13214
13215 LogFlowThisFunc(("aProgress=%p\n", pProgress));
13216
13217 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13218
13219 if (mData->mSession.mState != SessionState_Locked)
13220 return VBOX_E_INVALID_OBJECT_STATE;
13221
13222 if (!mData->mSession.mProgress.isNull())
13223 mData->mSession.mProgress->setOtherProgressObject(pProgress);
13224
13225 /* If we didn't reference the NAT network service yet, add a reference to
13226 * force a start */
13227 if (miNATNetworksStarted < 1)
13228 {
13229 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
13230 {
13231 BOOL enabled;
13232 HRESULT hrc = mNetworkAdapters[slot]->COMGETTER(Enabled)(&enabled);
13233 if ( FAILED(hrc)
13234 || !enabled)
13235 continue;
13236
13237 NetworkAttachmentType_T type;
13238 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
13239 if ( SUCCEEDED(hrc)
13240 && type == NetworkAttachmentType_NATNetwork)
13241 {
13242 Bstr name;
13243 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
13244 if (SUCCEEDED(hrc))
13245 {
13246 Utf8Str strName(name);
13247 LogRel(("VM '%s' starts using NAT network '%s'\n",
13248 mUserData->s.strName.c_str(), strName.c_str()));
13249 mPeer->lockHandle()->unlockWrite();
13250 mParent->i_natNetworkRefInc(strName);
13251#ifdef RT_LOCK_STRICT
13252 mPeer->lockHandle()->lockWrite(RT_SRC_POS);
13253#else
13254 mPeer->lockHandle()->lockWrite();
13255#endif
13256 }
13257 }
13258 }
13259 miNATNetworksStarted++;
13260 }
13261
13262 LogFlowThisFunc(("returns S_OK.\n"));
13263 return S_OK;
13264}
13265
13266/**
13267 * @note Locks this object for writing.
13268 */
13269HRESULT SessionMachine::endPowerUp(LONG aResult)
13270{
13271 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13272
13273 if (mData->mSession.mState != SessionState_Locked)
13274 return VBOX_E_INVALID_OBJECT_STATE;
13275
13276 /* Finalize the LaunchVMProcess progress object. */
13277 if (mData->mSession.mProgress)
13278 {
13279 mData->mSession.mProgress->notifyComplete((HRESULT)aResult);
13280 mData->mSession.mProgress.setNull();
13281 }
13282
13283 if (SUCCEEDED((HRESULT)aResult))
13284 {
13285#ifdef VBOX_WITH_RESOURCE_USAGE_API
13286 /* The VM has been powered up successfully, so it makes sense
13287 * now to offer the performance metrics for a running machine
13288 * object. Doing it earlier wouldn't be safe. */
13289 i_registerMetrics(mParent->i_performanceCollector(), mPeer,
13290 mData->mSession.mPID);
13291#endif /* VBOX_WITH_RESOURCE_USAGE_API */
13292 }
13293
13294 return S_OK;
13295}
13296
13297/**
13298 * @note Locks this object for writing.
13299 */
13300HRESULT SessionMachine::beginPoweringDown(ComPtr<IProgress> &aProgress)
13301{
13302 LogFlowThisFuncEnter();
13303
13304 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13305
13306 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
13307 E_FAIL);
13308
13309 /* create a progress object to track operation completion */
13310 ComObjPtr<Progress> pProgress;
13311 pProgress.createObject();
13312 pProgress->init(i_getVirtualBox(),
13313 static_cast<IMachine *>(this) /* aInitiator */,
13314 tr("Stopping the virtual machine"),
13315 FALSE /* aCancelable */);
13316
13317 /* fill in the console task data */
13318 mConsoleTaskData.mLastState = mData->mMachineState;
13319 mConsoleTaskData.mProgress = pProgress;
13320
13321 /* set the state to Stopping (this is expected by Console::PowerDown()) */
13322 i_setMachineState(MachineState_Stopping);
13323
13324 pProgress.queryInterfaceTo(aProgress.asOutParam());
13325
13326 return S_OK;
13327}
13328
13329/**
13330 * @note Locks this object for writing.
13331 */
13332HRESULT SessionMachine::endPoweringDown(LONG aResult,
13333 const com::Utf8Str &aErrMsg)
13334{
13335 LogFlowThisFuncEnter();
13336
13337 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13338
13339 AssertReturn( ( (SUCCEEDED(aResult) && mData->mMachineState == MachineState_PoweredOff)
13340 || (FAILED(aResult) && mData->mMachineState == MachineState_Stopping))
13341 && mConsoleTaskData.mLastState != MachineState_Null,
13342 E_FAIL);
13343
13344 /*
13345 * On failure, set the state to the state we had when BeginPoweringDown()
13346 * was called (this is expected by Console::PowerDown() and the associated
13347 * task). On success the VM process already changed the state to
13348 * MachineState_PoweredOff, so no need to do anything.
13349 */
13350 if (FAILED(aResult))
13351 i_setMachineState(mConsoleTaskData.mLastState);
13352
13353 /* notify the progress object about operation completion */
13354 Assert(mConsoleTaskData.mProgress);
13355 if (SUCCEEDED(aResult))
13356 mConsoleTaskData.mProgress->i_notifyComplete(S_OK);
13357 else
13358 {
13359 if (aErrMsg.length())
13360 mConsoleTaskData.mProgress->i_notifyComplete(aResult,
13361 COM_IIDOF(ISession),
13362 getComponentName(),
13363 aErrMsg.c_str());
13364 else
13365 mConsoleTaskData.mProgress->i_notifyComplete(aResult);
13366 }
13367
13368 /* clear out the temporary saved state data */
13369 mConsoleTaskData.mLastState = MachineState_Null;
13370 mConsoleTaskData.mProgress.setNull();
13371
13372 LogFlowThisFuncLeave();
13373 return S_OK;
13374}
13375
13376
13377/**
13378 * Goes through the USB filters of the given machine to see if the given
13379 * device matches any filter or not.
13380 *
13381 * @note Locks the same as USBController::hasMatchingFilter() does.
13382 */
13383HRESULT SessionMachine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
13384 BOOL *aMatched,
13385 ULONG *aMaskedInterfaces)
13386{
13387 LogFlowThisFunc(("\n"));
13388
13389#ifdef VBOX_WITH_USB
13390 *aMatched = mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedInterfaces);
13391#else
13392 NOREF(aDevice);
13393 NOREF(aMaskedInterfaces);
13394 *aMatched = FALSE;
13395#endif
13396
13397 return S_OK;
13398}
13399
13400/**
13401 * @note Locks the same as Host::captureUSBDevice() does.
13402 */
13403HRESULT SessionMachine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
13404{
13405 LogFlowThisFunc(("\n"));
13406
13407#ifdef VBOX_WITH_USB
13408 /* if captureDeviceForVM() fails, it must have set extended error info */
13409 clearError();
13410 MultiResult rc = mParent->i_host()->i_checkUSBProxyService();
13411 if (FAILED(rc)) return rc;
13412
13413 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13414 AssertReturn(service, E_FAIL);
13415 return service->captureDeviceForVM(this, aId.ref(), aCaptureFilename);
13416#else
13417 NOREF(aId);
13418 return E_NOTIMPL;
13419#endif
13420}
13421
13422/**
13423 * @note Locks the same as Host::detachUSBDevice() does.
13424 */
13425HRESULT SessionMachine::detachUSBDevice(const com::Guid &aId,
13426 BOOL aDone)
13427{
13428 LogFlowThisFunc(("\n"));
13429
13430#ifdef VBOX_WITH_USB
13431 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13432 AssertReturn(service, E_FAIL);
13433 return service->detachDeviceFromVM(this, aId.ref(), !!aDone);
13434#else
13435 NOREF(aId);
13436 NOREF(aDone);
13437 return E_NOTIMPL;
13438#endif
13439}
13440
13441/**
13442 * Inserts all machine filters to the USB proxy service and then calls
13443 * Host::autoCaptureUSBDevices().
13444 *
13445 * Called by Console from the VM process upon VM startup.
13446 *
13447 * @note Locks what called methods lock.
13448 */
13449HRESULT SessionMachine::autoCaptureUSBDevices()
13450{
13451 LogFlowThisFunc(("\n"));
13452
13453#ifdef VBOX_WITH_USB
13454 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(true /* aInsertFilters */);
13455 AssertComRC(rc);
13456 NOREF(rc);
13457
13458 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13459 AssertReturn(service, E_FAIL);
13460 return service->autoCaptureDevicesForVM(this);
13461#else
13462 return S_OK;
13463#endif
13464}
13465
13466/**
13467 * Removes all machine filters from the USB proxy service and then calls
13468 * Host::detachAllUSBDevices().
13469 *
13470 * Called by Console from the VM process upon normal VM termination or by
13471 * SessionMachine::uninit() upon abnormal VM termination (from under the
13472 * Machine/SessionMachine lock).
13473 *
13474 * @note Locks what called methods lock.
13475 */
13476HRESULT SessionMachine::detachAllUSBDevices(BOOL aDone)
13477{
13478 LogFlowThisFunc(("\n"));
13479
13480#ifdef VBOX_WITH_USB
13481 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
13482 AssertComRC(rc);
13483 NOREF(rc);
13484
13485 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13486 AssertReturn(service, E_FAIL);
13487 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
13488#else
13489 NOREF(aDone);
13490 return S_OK;
13491#endif
13492}
13493
13494/**
13495 * @note Locks this object for writing.
13496 */
13497HRESULT SessionMachine::onSessionEnd(const ComPtr<ISession> &aSession,
13498 ComPtr<IProgress> &aProgress)
13499{
13500 LogFlowThisFuncEnter();
13501
13502 LogFlowThisFunc(("callerstate=%d\n", getObjectState().getState()));
13503 /*
13504 * We don't assert below because it might happen that a non-direct session
13505 * informs us it is closed right after we've been uninitialized -- it's ok.
13506 */
13507
13508 /* get IInternalSessionControl interface */
13509 ComPtr<IInternalSessionControl> control(aSession);
13510
13511 ComAssertRet(!control.isNull(), E_INVALIDARG);
13512
13513 /* Creating a Progress object requires the VirtualBox lock, and
13514 * thus locking it here is required by the lock order rules. */
13515 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
13516
13517 if (control == mData->mSession.mDirectControl)
13518 {
13519 /* The direct session is being normally closed by the client process
13520 * ----------------------------------------------------------------- */
13521
13522 /* go to the closing state (essential for all open*Session() calls and
13523 * for #i_checkForDeath()) */
13524 Assert(mData->mSession.mState == SessionState_Locked);
13525 mData->mSession.mState = SessionState_Unlocking;
13526
13527 /* set direct control to NULL to release the remote instance */
13528 mData->mSession.mDirectControl.setNull();
13529 LogFlowThisFunc(("Direct control is set to NULL\n"));
13530
13531 if (mData->mSession.mProgress)
13532 {
13533 /* finalize the progress, someone might wait if a frontend
13534 * closes the session before powering on the VM. */
13535 mData->mSession.mProgress->notifyComplete(E_FAIL,
13536 COM_IIDOF(ISession),
13537 getComponentName(),
13538 tr("The VM session was closed before any attempt to power it on"));
13539 mData->mSession.mProgress.setNull();
13540 }
13541
13542 /* Create the progress object the client will use to wait until
13543 * #i_checkForDeath() is called to uninitialize this session object after
13544 * it releases the IPC semaphore.
13545 * Note! Because we're "reusing" mProgress here, this must be a proxy
13546 * object just like for LaunchVMProcess. */
13547 Assert(mData->mSession.mProgress.isNull());
13548 ComObjPtr<ProgressProxy> progress;
13549 progress.createObject();
13550 ComPtr<IUnknown> pPeer(mPeer);
13551 progress->init(mParent, pPeer,
13552 Bstr(tr("Closing session")).raw(),
13553 FALSE /* aCancelable */);
13554 progress.queryInterfaceTo(aProgress.asOutParam());
13555 mData->mSession.mProgress = progress;
13556 }
13557 else
13558 {
13559 /* the remote session is being normally closed */
13560 bool found = false;
13561 for (Data::Session::RemoteControlList::iterator
13562 it = mData->mSession.mRemoteControls.begin();
13563 it != mData->mSession.mRemoteControls.end();
13564 ++it)
13565 {
13566 if (control == *it)
13567 {
13568 found = true;
13569 // This MUST be erase(it), not remove(*it) as the latter
13570 // triggers a very nasty use after free due to the place where
13571 // the value "lives".
13572 mData->mSession.mRemoteControls.erase(it);
13573 break;
13574 }
13575 }
13576 ComAssertMsgRet(found, ("The session is not found in the session list!"),
13577 E_INVALIDARG);
13578 }
13579
13580 /* signal the client watcher thread, because the client is going away */
13581 mParent->i_updateClientWatcher();
13582
13583 LogFlowThisFuncLeave();
13584 return S_OK;
13585}
13586
13587HRESULT SessionMachine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
13588 std::vector<com::Utf8Str> &aValues,
13589 std::vector<LONG64> &aTimestamps,
13590 std::vector<com::Utf8Str> &aFlags)
13591{
13592 LogFlowThisFunc(("\n"));
13593
13594#ifdef VBOX_WITH_GUEST_PROPS
13595 using namespace guestProp;
13596
13597 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13598
13599 size_t cEntries = mHWData->mGuestProperties.size();
13600 aNames.resize(cEntries);
13601 aValues.resize(cEntries);
13602 aTimestamps.resize(cEntries);
13603 aFlags.resize(cEntries);
13604
13605 size_t i = 0;
13606 for (HWData::GuestPropertyMap::const_iterator
13607 it = mHWData->mGuestProperties.begin();
13608 it != mHWData->mGuestProperties.end();
13609 ++it, ++i)
13610 {
13611 char szFlags[MAX_FLAGS_LEN + 1];
13612 aNames[i] = it->first;
13613 aValues[i] = it->second.strValue;
13614 aTimestamps[i] = it->second.mTimestamp;
13615
13616 /* If it is NULL, keep it NULL. */
13617 if (it->second.mFlags)
13618 {
13619 writeFlags(it->second.mFlags, szFlags);
13620 aFlags[i] = szFlags;
13621 }
13622 else
13623 aFlags[i] = "";
13624 }
13625 return S_OK;
13626#else
13627 ReturnComNotImplemented();
13628#endif
13629}
13630
13631HRESULT SessionMachine::pushGuestProperty(const com::Utf8Str &aName,
13632 const com::Utf8Str &aValue,
13633 LONG64 aTimestamp,
13634 const com::Utf8Str &aFlags)
13635{
13636 LogFlowThisFunc(("\n"));
13637
13638#ifdef VBOX_WITH_GUEST_PROPS
13639 using namespace guestProp;
13640
13641 try
13642 {
13643 /*
13644 * Convert input up front.
13645 */
13646 uint32_t fFlags = NILFLAG;
13647 if (aFlags.length())
13648 {
13649 int vrc = validateFlags(aFlags.c_str(), &fFlags);
13650 AssertRCReturn(vrc, E_INVALIDARG);
13651 }
13652
13653 /*
13654 * Now grab the object lock, validate the state and do the update.
13655 */
13656
13657 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13658
13659 if (!Global::IsOnline(mData->mMachineState))
13660 {
13661 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
13662 VBOX_E_INVALID_VM_STATE);
13663 }
13664
13665 i_setModified(IsModified_MachineData);
13666 mHWData.backup();
13667
13668 bool fDelete = !aValue.length();
13669 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
13670 if (it != mHWData->mGuestProperties.end())
13671 {
13672 if (!fDelete)
13673 {
13674 it->second.strValue = aValue;
13675 it->second.mTimestamp = aTimestamp;
13676 it->second.mFlags = fFlags;
13677 }
13678 else
13679 mHWData->mGuestProperties.erase(it);
13680
13681 mData->mGuestPropertiesModified = TRUE;
13682 }
13683 else if (!fDelete)
13684 {
13685 HWData::GuestProperty prop;
13686 prop.strValue = aValue;
13687 prop.mTimestamp = aTimestamp;
13688 prop.mFlags = fFlags;
13689
13690 mHWData->mGuestProperties[aName] = prop;
13691 mData->mGuestPropertiesModified = TRUE;
13692 }
13693
13694 alock.release();
13695
13696 mParent->i_onGuestPropertyChange(mData->mUuid,
13697 Bstr(aName).raw(),
13698 Bstr(aValue).raw(),
13699 Bstr(aFlags).raw());
13700 }
13701 catch (...)
13702 {
13703 return VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
13704 }
13705 return S_OK;
13706#else
13707 ReturnComNotImplemented();
13708#endif
13709}
13710
13711
13712HRESULT SessionMachine::lockMedia()
13713{
13714 AutoMultiWriteLock2 alock(this->lockHandle(),
13715 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13716
13717 AssertReturn( mData->mMachineState == MachineState_Starting
13718 || mData->mMachineState == MachineState_Restoring
13719 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
13720
13721 clearError();
13722 alock.release();
13723 return i_lockMedia();
13724}
13725
13726HRESULT SessionMachine::unlockMedia()
13727{
13728 HRESULT hrc = i_unlockMedia();
13729 return hrc;
13730}
13731
13732HRESULT SessionMachine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
13733 ComPtr<IMediumAttachment> &aNewAttachment)
13734{
13735 // request the host lock first, since might be calling Host methods for getting host drives;
13736 // next, protect the media tree all the while we're in here, as well as our member variables
13737 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
13738 this->lockHandle(),
13739 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13740
13741 IMediumAttachment *iAttach = aAttachment;
13742 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(iAttach);
13743
13744 Utf8Str ctrlName;
13745 LONG lPort;
13746 LONG lDevice;
13747 bool fTempEject;
13748 {
13749 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13750
13751 /* Need to query the details first, as the IMediumAttachment reference
13752 * might be to the original settings, which we are going to change. */
13753 ctrlName = pAttach->i_getControllerName();
13754 lPort = pAttach->i_getPort();
13755 lDevice = pAttach->i_getDevice();
13756 fTempEject = pAttach->i_getTempEject();
13757 }
13758
13759 if (!fTempEject)
13760 {
13761 /* Remember previously mounted medium. The medium before taking the
13762 * backup is not necessarily the same thing. */
13763 ComObjPtr<Medium> oldmedium;
13764 oldmedium = pAttach->i_getMedium();
13765
13766 i_setModified(IsModified_Storage);
13767 mMediumAttachments.backup();
13768
13769 // The backup operation makes the pAttach reference point to the
13770 // old settings. Re-get the correct reference.
13771 pAttach = i_findAttachment(*mMediumAttachments.data(),
13772 ctrlName,
13773 lPort,
13774 lDevice);
13775
13776 {
13777 AutoCaller autoAttachCaller(this);
13778 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
13779
13780 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13781 if (!oldmedium.isNull())
13782 oldmedium->i_removeBackReference(mData->mUuid);
13783
13784 pAttach->i_updateMedium(NULL);
13785 pAttach->i_updateEjected();
13786 }
13787
13788 i_setModified(IsModified_Storage);
13789 }
13790 else
13791 {
13792 {
13793 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13794 pAttach->i_updateEjected();
13795 }
13796 }
13797
13798 pAttach.queryInterfaceTo(aNewAttachment.asOutParam());
13799
13800 return S_OK;
13801}
13802
13803HRESULT SessionMachine::authenticateExternal(const std::vector<com::Utf8Str> &aAuthParams,
13804 com::Utf8Str &aResult)
13805{
13806 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13807
13808 HRESULT hr = S_OK;
13809
13810 if (!mAuthLibCtx.hAuthLibrary)
13811 {
13812 /* Load the external authentication library. */
13813 Bstr authLibrary;
13814 mVRDEServer->COMGETTER(AuthLibrary)(authLibrary.asOutParam());
13815
13816 Utf8Str filename = authLibrary;
13817
13818 int rc = AuthLibLoad(&mAuthLibCtx, filename.c_str());
13819 if (RT_FAILURE(rc))
13820 {
13821 hr = setError(E_FAIL,
13822 tr("Could not load the external authentication library '%s' (%Rrc)"),
13823 filename.c_str(), rc);
13824 }
13825 }
13826
13827 /* The auth library might need the machine lock. */
13828 alock.release();
13829
13830 if (FAILED(hr))
13831 return hr;
13832
13833 if (aAuthParams[0] == "VRDEAUTH" && aAuthParams.size() == 7)
13834 {
13835 enum VRDEAuthParams
13836 {
13837 parmUuid = 1,
13838 parmGuestJudgement,
13839 parmUser,
13840 parmPassword,
13841 parmDomain,
13842 parmClientId
13843 };
13844
13845 AuthResult result = AuthResultAccessDenied;
13846
13847 Guid uuid(aAuthParams[parmUuid]);
13848 AuthGuestJudgement guestJudgement = (AuthGuestJudgement)aAuthParams[parmGuestJudgement].toUInt32();
13849 uint32_t u32ClientId = aAuthParams[parmClientId].toUInt32();
13850
13851 result = AuthLibAuthenticate(&mAuthLibCtx,
13852 uuid.raw(), guestJudgement,
13853 aAuthParams[parmUser].c_str(),
13854 aAuthParams[parmPassword].c_str(),
13855 aAuthParams[parmDomain].c_str(),
13856 u32ClientId);
13857
13858 /* Hack: aAuthParams[parmPassword] is const but the code believes in writable memory. */
13859 size_t cbPassword = aAuthParams[parmPassword].length();
13860 if (cbPassword)
13861 {
13862 RTMemWipeThoroughly((void *)aAuthParams[parmPassword].c_str(), cbPassword, 10 /* cPasses */);
13863 memset((void *)aAuthParams[parmPassword].c_str(), 'x', cbPassword);
13864 }
13865
13866 if (result == AuthResultAccessGranted)
13867 aResult = "granted";
13868 else
13869 aResult = "denied";
13870
13871 LogRel(("AUTH: VRDE authentification for user '%s' result '%s'\n",
13872 aAuthParams[parmUser].c_str(), aResult.c_str()));
13873 }
13874 else if (aAuthParams[0] == "VRDEAUTHDISCONNECT" && aAuthParams.size() == 3)
13875 {
13876 enum VRDEAuthDisconnectParams
13877 {
13878 parmUuid = 1,
13879 parmClientId
13880 };
13881
13882 Guid uuid(aAuthParams[parmUuid]);
13883 uint32_t u32ClientId = 0;
13884 AuthLibDisconnect(&mAuthLibCtx, uuid.raw(), u32ClientId);
13885 }
13886 else
13887 {
13888 hr = E_INVALIDARG;
13889 }
13890
13891 return hr;
13892}
13893
13894// public methods only for internal purposes
13895/////////////////////////////////////////////////////////////////////////////
13896
13897#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
13898/**
13899 * Called from the client watcher thread to check for expected or unexpected
13900 * death of the client process that has a direct session to this machine.
13901 *
13902 * On Win32 and on OS/2, this method is called only when we've got the
13903 * mutex (i.e. the client has either died or terminated normally) so it always
13904 * returns @c true (the client is terminated, the session machine is
13905 * uninitialized).
13906 *
13907 * On other platforms, the method returns @c true if the client process has
13908 * terminated normally or abnormally and the session machine was uninitialized,
13909 * and @c false if the client process is still alive.
13910 *
13911 * @note Locks this object for writing.
13912 */
13913bool SessionMachine::i_checkForDeath()
13914{
13915 Uninit::Reason reason;
13916 bool terminated = false;
13917
13918 /* Enclose autoCaller with a block because calling uninit() from under it
13919 * will deadlock. */
13920 {
13921 AutoCaller autoCaller(this);
13922 if (!autoCaller.isOk())
13923 {
13924 /* return true if not ready, to cause the client watcher to exclude
13925 * the corresponding session from watching */
13926 LogFlowThisFunc(("Already uninitialized!\n"));
13927 return true;
13928 }
13929
13930 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13931
13932 /* Determine the reason of death: if the session state is Closing here,
13933 * everything is fine. Otherwise it means that the client did not call
13934 * OnSessionEnd() before it released the IPC semaphore. This may happen
13935 * either because the client process has abnormally terminated, or
13936 * because it simply forgot to call ISession::Close() before exiting. We
13937 * threat the latter also as an abnormal termination (see
13938 * Session::uninit() for details). */
13939 reason = mData->mSession.mState == SessionState_Unlocking ?
13940 Uninit::Normal :
13941 Uninit::Abnormal;
13942
13943 if (mClientToken)
13944 terminated = mClientToken->release();
13945 } /* AutoCaller block */
13946
13947 if (terminated)
13948 uninit(reason);
13949
13950 return terminated;
13951}
13952
13953void SessionMachine::i_getTokenId(Utf8Str &strTokenId)
13954{
13955 LogFlowThisFunc(("\n"));
13956
13957 strTokenId.setNull();
13958
13959 AutoCaller autoCaller(this);
13960 AssertComRCReturnVoid(autoCaller.rc());
13961
13962 Assert(mClientToken);
13963 if (mClientToken)
13964 mClientToken->getId(strTokenId);
13965}
13966#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
13967IToken *SessionMachine::i_getToken()
13968{
13969 LogFlowThisFunc(("\n"));
13970
13971 AutoCaller autoCaller(this);
13972 AssertComRCReturn(autoCaller.rc(), NULL);
13973
13974 Assert(mClientToken);
13975 if (mClientToken)
13976 return mClientToken->getToken();
13977 else
13978 return NULL;
13979}
13980#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
13981
13982Machine::ClientToken *SessionMachine::i_getClientToken()
13983{
13984 LogFlowThisFunc(("\n"));
13985
13986 AutoCaller autoCaller(this);
13987 AssertComRCReturn(autoCaller.rc(), NULL);
13988
13989 return mClientToken;
13990}
13991
13992
13993/**
13994 * @note Locks this object for reading.
13995 */
13996HRESULT SessionMachine::i_onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
13997{
13998 LogFlowThisFunc(("\n"));
13999
14000 AutoCaller autoCaller(this);
14001 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14002
14003 ComPtr<IInternalSessionControl> directControl;
14004 {
14005 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14006 if (mData->mSession.mLockType == LockType_VM)
14007 directControl = mData->mSession.mDirectControl;
14008 }
14009
14010 /* ignore notifications sent after #OnSessionEnd() is called */
14011 if (!directControl)
14012 return S_OK;
14013
14014 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
14015}
14016
14017/**
14018 * @note Locks this object for reading.
14019 */
14020HRESULT SessionMachine::i_onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
14021 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort,
14022 IN_BSTR aGuestIp, LONG aGuestPort)
14023{
14024 LogFlowThisFunc(("\n"));
14025
14026 AutoCaller autoCaller(this);
14027 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14028
14029 ComPtr<IInternalSessionControl> directControl;
14030 {
14031 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14032 if (mData->mSession.mLockType == LockType_VM)
14033 directControl = mData->mSession.mDirectControl;
14034 }
14035
14036 /* ignore notifications sent after #OnSessionEnd() is called */
14037 if (!directControl)
14038 return S_OK;
14039 /*
14040 * instead acting like callback we ask IVirtualBox deliver corresponding event
14041 */
14042
14043 mParent->i_onNatRedirectChange(i_getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp,
14044 (uint16_t)aHostPort, aGuestIp, (uint16_t)aGuestPort);
14045 return S_OK;
14046}
14047
14048/**
14049 * @note Locks this object for reading.
14050 */
14051HRESULT SessionMachine::i_onSerialPortChange(ISerialPort *serialPort)
14052{
14053 LogFlowThisFunc(("\n"));
14054
14055 AutoCaller autoCaller(this);
14056 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14057
14058 ComPtr<IInternalSessionControl> directControl;
14059 {
14060 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14061 if (mData->mSession.mLockType == LockType_VM)
14062 directControl = mData->mSession.mDirectControl;
14063 }
14064
14065 /* ignore notifications sent after #OnSessionEnd() is called */
14066 if (!directControl)
14067 return S_OK;
14068
14069 return directControl->OnSerialPortChange(serialPort);
14070}
14071
14072/**
14073 * @note Locks this object for reading.
14074 */
14075HRESULT SessionMachine::i_onParallelPortChange(IParallelPort *parallelPort)
14076{
14077 LogFlowThisFunc(("\n"));
14078
14079 AutoCaller autoCaller(this);
14080 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14081
14082 ComPtr<IInternalSessionControl> directControl;
14083 {
14084 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14085 if (mData->mSession.mLockType == LockType_VM)
14086 directControl = mData->mSession.mDirectControl;
14087 }
14088
14089 /* ignore notifications sent after #OnSessionEnd() is called */
14090 if (!directControl)
14091 return S_OK;
14092
14093 return directControl->OnParallelPortChange(parallelPort);
14094}
14095
14096/**
14097 * @note Locks this object for reading.
14098 */
14099HRESULT SessionMachine::i_onStorageControllerChange()
14100{
14101 LogFlowThisFunc(("\n"));
14102
14103 AutoCaller autoCaller(this);
14104 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14105
14106 ComPtr<IInternalSessionControl> directControl;
14107 {
14108 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14109 if (mData->mSession.mLockType == LockType_VM)
14110 directControl = mData->mSession.mDirectControl;
14111 }
14112
14113 /* ignore notifications sent after #OnSessionEnd() is called */
14114 if (!directControl)
14115 return S_OK;
14116
14117 return directControl->OnStorageControllerChange();
14118}
14119
14120/**
14121 * @note Locks this object for reading.
14122 */
14123HRESULT SessionMachine::i_onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
14124{
14125 LogFlowThisFunc(("\n"));
14126
14127 AutoCaller autoCaller(this);
14128 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14129
14130 ComPtr<IInternalSessionControl> directControl;
14131 {
14132 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14133 if (mData->mSession.mLockType == LockType_VM)
14134 directControl = mData->mSession.mDirectControl;
14135 }
14136
14137 /* ignore notifications sent after #OnSessionEnd() is called */
14138 if (!directControl)
14139 return S_OK;
14140
14141 return directControl->OnMediumChange(aAttachment, aForce);
14142}
14143
14144/**
14145 * @note Locks this object for reading.
14146 */
14147HRESULT SessionMachine::i_onCPUChange(ULONG aCPU, BOOL aRemove)
14148{
14149 LogFlowThisFunc(("\n"));
14150
14151 AutoCaller autoCaller(this);
14152 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14153
14154 ComPtr<IInternalSessionControl> directControl;
14155 {
14156 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14157 if (mData->mSession.mLockType == LockType_VM)
14158 directControl = mData->mSession.mDirectControl;
14159 }
14160
14161 /* ignore notifications sent after #OnSessionEnd() is called */
14162 if (!directControl)
14163 return S_OK;
14164
14165 return directControl->OnCPUChange(aCPU, aRemove);
14166}
14167
14168HRESULT SessionMachine::i_onCPUExecutionCapChange(ULONG aExecutionCap)
14169{
14170 LogFlowThisFunc(("\n"));
14171
14172 AutoCaller autoCaller(this);
14173 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14174
14175 ComPtr<IInternalSessionControl> directControl;
14176 {
14177 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14178 if (mData->mSession.mLockType == LockType_VM)
14179 directControl = mData->mSession.mDirectControl;
14180 }
14181
14182 /* ignore notifications sent after #OnSessionEnd() is called */
14183 if (!directControl)
14184 return S_OK;
14185
14186 return directControl->OnCPUExecutionCapChange(aExecutionCap);
14187}
14188
14189/**
14190 * @note Locks this object for reading.
14191 */
14192HRESULT SessionMachine::i_onVRDEServerChange(BOOL aRestart)
14193{
14194 LogFlowThisFunc(("\n"));
14195
14196 AutoCaller autoCaller(this);
14197 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14198
14199 ComPtr<IInternalSessionControl> directControl;
14200 {
14201 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14202 if (mData->mSession.mLockType == LockType_VM)
14203 directControl = mData->mSession.mDirectControl;
14204 }
14205
14206 /* ignore notifications sent after #OnSessionEnd() is called */
14207 if (!directControl)
14208 return S_OK;
14209
14210 return directControl->OnVRDEServerChange(aRestart);
14211}
14212
14213/**
14214 * @note Locks this object for reading.
14215 */
14216HRESULT SessionMachine::i_onVideoCaptureChange()
14217{
14218 LogFlowThisFunc(("\n"));
14219
14220 AutoCaller autoCaller(this);
14221 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14222
14223 ComPtr<IInternalSessionControl> directControl;
14224 {
14225 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14226 if (mData->mSession.mLockType == LockType_VM)
14227 directControl = mData->mSession.mDirectControl;
14228 }
14229
14230 /* ignore notifications sent after #OnSessionEnd() is called */
14231 if (!directControl)
14232 return S_OK;
14233
14234 return directControl->OnVideoCaptureChange();
14235}
14236
14237/**
14238 * @note Locks this object for reading.
14239 */
14240HRESULT SessionMachine::i_onUSBControllerChange()
14241{
14242 LogFlowThisFunc(("\n"));
14243
14244 AutoCaller autoCaller(this);
14245 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14246
14247 ComPtr<IInternalSessionControl> directControl;
14248 {
14249 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14250 if (mData->mSession.mLockType == LockType_VM)
14251 directControl = mData->mSession.mDirectControl;
14252 }
14253
14254 /* ignore notifications sent after #OnSessionEnd() is called */
14255 if (!directControl)
14256 return S_OK;
14257
14258 return directControl->OnUSBControllerChange();
14259}
14260
14261/**
14262 * @note Locks this object for reading.
14263 */
14264HRESULT SessionMachine::i_onSharedFolderChange()
14265{
14266 LogFlowThisFunc(("\n"));
14267
14268 AutoCaller autoCaller(this);
14269 AssertComRCReturnRC(autoCaller.rc());
14270
14271 ComPtr<IInternalSessionControl> directControl;
14272 {
14273 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14274 if (mData->mSession.mLockType == LockType_VM)
14275 directControl = mData->mSession.mDirectControl;
14276 }
14277
14278 /* ignore notifications sent after #OnSessionEnd() is called */
14279 if (!directControl)
14280 return S_OK;
14281
14282 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
14283}
14284
14285/**
14286 * @note Locks this object for reading.
14287 */
14288HRESULT SessionMachine::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
14289{
14290 LogFlowThisFunc(("\n"));
14291
14292 AutoCaller autoCaller(this);
14293 AssertComRCReturnRC(autoCaller.rc());
14294
14295 ComPtr<IInternalSessionControl> directControl;
14296 {
14297 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14298 if (mData->mSession.mLockType == LockType_VM)
14299 directControl = mData->mSession.mDirectControl;
14300 }
14301
14302 /* ignore notifications sent after #OnSessionEnd() is called */
14303 if (!directControl)
14304 return S_OK;
14305
14306 return directControl->OnClipboardModeChange(aClipboardMode);
14307}
14308
14309/**
14310 * @note Locks this object for reading.
14311 */
14312HRESULT SessionMachine::i_onDnDModeChange(DnDMode_T aDnDMode)
14313{
14314 LogFlowThisFunc(("\n"));
14315
14316 AutoCaller autoCaller(this);
14317 AssertComRCReturnRC(autoCaller.rc());
14318
14319 ComPtr<IInternalSessionControl> directControl;
14320 {
14321 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14322 if (mData->mSession.mLockType == LockType_VM)
14323 directControl = mData->mSession.mDirectControl;
14324 }
14325
14326 /* ignore notifications sent after #OnSessionEnd() is called */
14327 if (!directControl)
14328 return S_OK;
14329
14330 return directControl->OnDnDModeChange(aDnDMode);
14331}
14332
14333/**
14334 * @note Locks this object for reading.
14335 */
14336HRESULT SessionMachine::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
14337{
14338 LogFlowThisFunc(("\n"));
14339
14340 AutoCaller autoCaller(this);
14341 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14342
14343 ComPtr<IInternalSessionControl> directControl;
14344 {
14345 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14346 if (mData->mSession.mLockType == LockType_VM)
14347 directControl = mData->mSession.mDirectControl;
14348 }
14349
14350 /* ignore notifications sent after #OnSessionEnd() is called */
14351 if (!directControl)
14352 return S_OK;
14353
14354 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
14355}
14356
14357/**
14358 * @note Locks this object for reading.
14359 */
14360HRESULT SessionMachine::i_onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove, BOOL aSilent)
14361{
14362 LogFlowThisFunc(("\n"));
14363
14364 AutoCaller autoCaller(this);
14365 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14366
14367 ComPtr<IInternalSessionControl> directControl;
14368 {
14369 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14370 if (mData->mSession.mLockType == LockType_VM)
14371 directControl = mData->mSession.mDirectControl;
14372 }
14373
14374 /* ignore notifications sent after #OnSessionEnd() is called */
14375 if (!directControl)
14376 return S_OK;
14377
14378 return directControl->OnStorageDeviceChange(aAttachment, aRemove, aSilent);
14379}
14380
14381/**
14382 * Returns @c true if this machine's USB controller reports it has a matching
14383 * filter for the given USB device and @c false otherwise.
14384 *
14385 * @note locks this object for reading.
14386 */
14387bool SessionMachine::i_hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
14388{
14389 AutoCaller autoCaller(this);
14390 /* silently return if not ready -- this method may be called after the
14391 * direct machine session has been called */
14392 if (!autoCaller.isOk())
14393 return false;
14394
14395#ifdef VBOX_WITH_USB
14396 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14397
14398 switch (mData->mMachineState)
14399 {
14400 case MachineState_Starting:
14401 case MachineState_Restoring:
14402 case MachineState_TeleportingIn:
14403 case MachineState_Paused:
14404 case MachineState_Running:
14405 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
14406 * elsewhere... */
14407 alock.release();
14408 return mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedIfs);
14409 default: break;
14410 }
14411#else
14412 NOREF(aDevice);
14413 NOREF(aMaskedIfs);
14414#endif
14415 return false;
14416}
14417
14418/**
14419 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14420 */
14421HRESULT SessionMachine::i_onUSBDeviceAttach(IUSBDevice *aDevice,
14422 IVirtualBoxErrorInfo *aError,
14423 ULONG aMaskedIfs,
14424 const com::Utf8Str &aCaptureFilename)
14425{
14426 LogFlowThisFunc(("\n"));
14427
14428 AutoCaller autoCaller(this);
14429
14430 /* This notification may happen after the machine object has been
14431 * uninitialized (the session was closed), so don't assert. */
14432 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14433
14434 ComPtr<IInternalSessionControl> directControl;
14435 {
14436 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14437 if (mData->mSession.mLockType == LockType_VM)
14438 directControl = mData->mSession.mDirectControl;
14439 }
14440
14441 /* fail on notifications sent after #OnSessionEnd() is called, it is
14442 * expected by the caller */
14443 if (!directControl)
14444 return E_FAIL;
14445
14446 /* No locks should be held at this point. */
14447 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14448 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14449
14450 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs, Bstr(aCaptureFilename).raw());
14451}
14452
14453/**
14454 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14455 */
14456HRESULT SessionMachine::i_onUSBDeviceDetach(IN_BSTR aId,
14457 IVirtualBoxErrorInfo *aError)
14458{
14459 LogFlowThisFunc(("\n"));
14460
14461 AutoCaller autoCaller(this);
14462
14463 /* This notification may happen after the machine object has been
14464 * uninitialized (the session was closed), so don't assert. */
14465 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14466
14467 ComPtr<IInternalSessionControl> directControl;
14468 {
14469 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14470 if (mData->mSession.mLockType == LockType_VM)
14471 directControl = mData->mSession.mDirectControl;
14472 }
14473
14474 /* fail on notifications sent after #OnSessionEnd() is called, it is
14475 * expected by the caller */
14476 if (!directControl)
14477 return E_FAIL;
14478
14479 /* No locks should be held at this point. */
14480 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14481 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14482
14483 return directControl->OnUSBDeviceDetach(aId, aError);
14484}
14485
14486// protected methods
14487/////////////////////////////////////////////////////////////////////////////
14488
14489/**
14490 * Deletes the given file if it is no longer in use by either the current machine state
14491 * (if the machine is "saved") or any of the machine's snapshots.
14492 *
14493 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
14494 * but is different for each SnapshotMachine. When calling this, the order of calling this
14495 * function on the one hand and changing that variable OR the snapshots tree on the other hand
14496 * is therefore critical. I know, it's all rather messy.
14497 *
14498 * @param strStateFile
14499 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in
14500 * the test for whether the saved state file is in use.
14501 */
14502void SessionMachine::i_releaseSavedStateFile(const Utf8Str &strStateFile,
14503 Snapshot *pSnapshotToIgnore)
14504{
14505 // it is safe to delete this saved state file if it is not currently in use by the machine ...
14506 if ( (strStateFile.isNotEmpty())
14507 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
14508 )
14509 // ... and it must also not be shared with other snapshots
14510 if ( !mData->mFirstSnapshot
14511 || !mData->mFirstSnapshot->i_sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
14512 // this checks the SnapshotMachine's state file paths
14513 )
14514 RTFileDelete(strStateFile.c_str());
14515}
14516
14517/**
14518 * Locks the attached media.
14519 *
14520 * All attached hard disks are locked for writing and DVD/floppy are locked for
14521 * reading. Parents of attached hard disks (if any) are locked for reading.
14522 *
14523 * This method also performs accessibility check of all media it locks: if some
14524 * media is inaccessible, the method will return a failure and a bunch of
14525 * extended error info objects per each inaccessible medium.
14526 *
14527 * Note that this method is atomic: if it returns a success, all media are
14528 * locked as described above; on failure no media is locked at all (all
14529 * succeeded individual locks will be undone).
14530 *
14531 * The caller is responsible for doing the necessary state sanity checks.
14532 *
14533 * The locks made by this method must be undone by calling #unlockMedia() when
14534 * no more needed.
14535 */
14536HRESULT SessionMachine::i_lockMedia()
14537{
14538 AutoCaller autoCaller(this);
14539 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14540
14541 AutoMultiWriteLock2 alock(this->lockHandle(),
14542 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
14543
14544 /* bail out if trying to lock things with already set up locking */
14545 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
14546
14547 MultiResult mrc(S_OK);
14548
14549 /* Collect locking information for all medium objects attached to the VM. */
14550 for (MediumAttachmentList::const_iterator
14551 it = mMediumAttachments->begin();
14552 it != mMediumAttachments->end();
14553 ++it)
14554 {
14555 MediumAttachment *pAtt = *it;
14556 DeviceType_T devType = pAtt->i_getType();
14557 Medium *pMedium = pAtt->i_getMedium();
14558
14559 MediumLockList *pMediumLockList(new MediumLockList());
14560 // There can be attachments without a medium (floppy/dvd), and thus
14561 // it's impossible to create a medium lock list. It still makes sense
14562 // to have the empty medium lock list in the map in case a medium is
14563 // attached later.
14564 if (pMedium != NULL)
14565 {
14566 MediumType_T mediumType = pMedium->i_getType();
14567 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
14568 || mediumType == MediumType_Shareable;
14569 bool fIsVitalImage = (devType == DeviceType_HardDisk);
14570
14571 alock.release();
14572 mrc = pMedium->i_createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
14573 !fIsReadOnlyLock ? pMedium : NULL /* pToLockWrite */,
14574 false /* fMediumLockWriteAll */,
14575 NULL,
14576 *pMediumLockList);
14577 alock.acquire();
14578 if (FAILED(mrc))
14579 {
14580 delete pMediumLockList;
14581 mData->mSession.mLockedMedia.Clear();
14582 break;
14583 }
14584 }
14585
14586 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
14587 if (FAILED(rc))
14588 {
14589 mData->mSession.mLockedMedia.Clear();
14590 mrc = setError(rc,
14591 tr("Collecting locking information for all attached media failed"));
14592 break;
14593 }
14594 }
14595
14596 if (SUCCEEDED(mrc))
14597 {
14598 /* Now lock all media. If this fails, nothing is locked. */
14599 alock.release();
14600 HRESULT rc = mData->mSession.mLockedMedia.Lock();
14601 alock.acquire();
14602 if (FAILED(rc))
14603 {
14604 mrc = setError(rc,
14605 tr("Locking of attached media failed. A possible reason is that one of the media is attached to a running VM"));
14606 }
14607 }
14608
14609 return mrc;
14610}
14611
14612/**
14613 * Undoes the locks made by by #lockMedia().
14614 */
14615HRESULT SessionMachine::i_unlockMedia()
14616{
14617 AutoCaller autoCaller(this);
14618 AssertComRCReturn(autoCaller.rc(),autoCaller.rc());
14619
14620 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14621
14622 /* we may be holding important error info on the current thread;
14623 * preserve it */
14624 ErrorInfoKeeper eik;
14625
14626 HRESULT rc = mData->mSession.mLockedMedia.Clear();
14627 AssertComRC(rc);
14628 return rc;
14629}
14630
14631/**
14632 * Helper to change the machine state (reimplementation).
14633 *
14634 * @note Locks this object for writing.
14635 * @note This method must not call i_saveSettings or SaveSettings, otherwise
14636 * it can cause crashes in random places due to unexpectedly committing
14637 * the current settings. The caller is responsible for that. The call
14638 * to saveStateSettings is fine, because this method does not commit.
14639 */
14640HRESULT SessionMachine::i_setMachineState(MachineState_T aMachineState)
14641{
14642 LogFlowThisFuncEnter();
14643 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
14644
14645 AutoCaller autoCaller(this);
14646 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14647
14648 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14649
14650 MachineState_T oldMachineState = mData->mMachineState;
14651
14652 AssertMsgReturn(oldMachineState != aMachineState,
14653 ("oldMachineState=%s, aMachineState=%s\n",
14654 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
14655 E_FAIL);
14656
14657 HRESULT rc = S_OK;
14658
14659 int stsFlags = 0;
14660 bool deleteSavedState = false;
14661
14662 /* detect some state transitions */
14663
14664 if ( ( oldMachineState == MachineState_Saved
14665 && aMachineState == MachineState_Restoring)
14666 || ( ( oldMachineState == MachineState_PoweredOff
14667 || oldMachineState == MachineState_Teleported
14668 || oldMachineState == MachineState_Aborted
14669 )
14670 && ( aMachineState == MachineState_TeleportingIn
14671 || aMachineState == MachineState_Starting
14672 )
14673 )
14674 )
14675 {
14676 /* The EMT thread is about to start */
14677
14678 /* Nothing to do here for now... */
14679
14680 /// @todo NEWMEDIA don't let mDVDDrive and other children
14681 /// change anything when in the Starting/Restoring state
14682 }
14683 else if ( ( oldMachineState == MachineState_Running
14684 || oldMachineState == MachineState_Paused
14685 || oldMachineState == MachineState_Teleporting
14686 || oldMachineState == MachineState_OnlineSnapshotting
14687 || oldMachineState == MachineState_LiveSnapshotting
14688 || oldMachineState == MachineState_Stuck
14689 || oldMachineState == MachineState_Starting
14690 || oldMachineState == MachineState_Stopping
14691 || oldMachineState == MachineState_Saving
14692 || oldMachineState == MachineState_Restoring
14693 || oldMachineState == MachineState_TeleportingPausedVM
14694 || oldMachineState == MachineState_TeleportingIn
14695 )
14696 && ( aMachineState == MachineState_PoweredOff
14697 || aMachineState == MachineState_Saved
14698 || aMachineState == MachineState_Teleported
14699 || aMachineState == MachineState_Aborted
14700 )
14701 )
14702 {
14703 /* The EMT thread has just stopped, unlock attached media. Note that as
14704 * opposed to locking that is done from Console, we do unlocking here
14705 * because the VM process may have aborted before having a chance to
14706 * properly unlock all media it locked. */
14707
14708 unlockMedia();
14709 }
14710
14711 if (oldMachineState == MachineState_Restoring)
14712 {
14713 if (aMachineState != MachineState_Saved)
14714 {
14715 /*
14716 * delete the saved state file once the machine has finished
14717 * restoring from it (note that Console sets the state from
14718 * Restoring to Saved if the VM couldn't restore successfully,
14719 * to give the user an ability to fix an error and retry --
14720 * we keep the saved state file in this case)
14721 */
14722 deleteSavedState = true;
14723 }
14724 }
14725 else if ( oldMachineState == MachineState_Saved
14726 && ( aMachineState == MachineState_PoweredOff
14727 || aMachineState == MachineState_Aborted
14728 || aMachineState == MachineState_Teleported
14729 )
14730 )
14731 {
14732 /*
14733 * delete the saved state after SessionMachine::ForgetSavedState() is called
14734 * or if the VM process (owning a direct VM session) crashed while the
14735 * VM was Saved
14736 */
14737
14738 /// @todo (dmik)
14739 // Not sure that deleting the saved state file just because of the
14740 // client death before it attempted to restore the VM is a good
14741 // thing. But when it crashes we need to go to the Aborted state
14742 // which cannot have the saved state file associated... The only
14743 // way to fix this is to make the Aborted condition not a VM state
14744 // but a bool flag: i.e., when a crash occurs, set it to true and
14745 // change the state to PoweredOff or Saved depending on the
14746 // saved state presence.
14747
14748 deleteSavedState = true;
14749 mData->mCurrentStateModified = TRUE;
14750 stsFlags |= SaveSTS_CurStateModified;
14751 }
14752
14753 if ( aMachineState == MachineState_Starting
14754 || aMachineState == MachineState_Restoring
14755 || aMachineState == MachineState_TeleportingIn
14756 )
14757 {
14758 /* set the current state modified flag to indicate that the current
14759 * state is no more identical to the state in the
14760 * current snapshot */
14761 if (!mData->mCurrentSnapshot.isNull())
14762 {
14763 mData->mCurrentStateModified = TRUE;
14764 stsFlags |= SaveSTS_CurStateModified;
14765 }
14766 }
14767
14768 if (deleteSavedState)
14769 {
14770 if (mRemoveSavedState)
14771 {
14772 Assert(!mSSData->strStateFilePath.isEmpty());
14773
14774 // it is safe to delete the saved state file if ...
14775 if ( !mData->mFirstSnapshot // ... we have no snapshots or
14776 || !mData->mFirstSnapshot->i_sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
14777 // ... none of the snapshots share the saved state file
14778 )
14779 RTFileDelete(mSSData->strStateFilePath.c_str());
14780 }
14781
14782 mSSData->strStateFilePath.setNull();
14783 stsFlags |= SaveSTS_StateFilePath;
14784 }
14785
14786 /* redirect to the underlying peer machine */
14787 mPeer->i_setMachineState(aMachineState);
14788
14789 if ( oldMachineState != MachineState_RestoringSnapshot
14790 && ( aMachineState == MachineState_PoweredOff
14791 || aMachineState == MachineState_Teleported
14792 || aMachineState == MachineState_Aborted
14793 || aMachineState == MachineState_Saved))
14794 {
14795 /* the machine has stopped execution
14796 * (or the saved state file was adopted) */
14797 stsFlags |= SaveSTS_StateTimeStamp;
14798 }
14799
14800 if ( ( oldMachineState == MachineState_PoweredOff
14801 || oldMachineState == MachineState_Aborted
14802 || oldMachineState == MachineState_Teleported
14803 )
14804 && aMachineState == MachineState_Saved)
14805 {
14806 /* the saved state file was adopted */
14807 Assert(!mSSData->strStateFilePath.isEmpty());
14808 stsFlags |= SaveSTS_StateFilePath;
14809 }
14810
14811#ifdef VBOX_WITH_GUEST_PROPS
14812 if ( aMachineState == MachineState_PoweredOff
14813 || aMachineState == MachineState_Aborted
14814 || aMachineState == MachineState_Teleported)
14815 {
14816 /* Make sure any transient guest properties get removed from the
14817 * property store on shutdown. */
14818 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
14819
14820 /* remove it from the settings representation */
14821 settings::GuestPropertiesList &llGuestProperties = mData->pMachineConfigFile->hardwareMachine.llGuestProperties;
14822 for (settings::GuestPropertiesList::iterator
14823 it = llGuestProperties.begin();
14824 it != llGuestProperties.end();
14825 /*nothing*/)
14826 {
14827 const settings::GuestProperty &prop = *it;
14828 if ( prop.strFlags.contains("TRANSRESET", Utf8Str::CaseInsensitive)
14829 || prop.strFlags.contains("TRANSIENT", Utf8Str::CaseInsensitive))
14830 {
14831 it = llGuestProperties.erase(it);
14832 fNeedsSaving = true;
14833 }
14834 else
14835 {
14836 ++it;
14837 }
14838 }
14839
14840 /* Additionally remove it from the HWData representation. Required to
14841 * keep everything in sync, as this is what the API keeps using. */
14842 HWData::GuestPropertyMap &llHWGuestProperties = mHWData->mGuestProperties;
14843 for (HWData::GuestPropertyMap::iterator
14844 it = llHWGuestProperties.begin();
14845 it != llHWGuestProperties.end();
14846 /*nothing*/)
14847 {
14848 uint32_t fFlags = it->second.mFlags;
14849 if ( fFlags & guestProp::TRANSIENT
14850 || fFlags & guestProp::TRANSRESET)
14851 {
14852 /* iterator where we need to continue after the erase call
14853 * (C++03 is a fact still, and it doesn't return the iterator
14854 * which would allow continuing) */
14855 HWData::GuestPropertyMap::iterator it2 = it;
14856 ++it2;
14857 llHWGuestProperties.erase(it);
14858 it = it2;
14859 fNeedsSaving = true;
14860 }
14861 else
14862 {
14863 ++it;
14864 }
14865 }
14866
14867 if (fNeedsSaving)
14868 {
14869 mData->mCurrentStateModified = TRUE;
14870 stsFlags |= SaveSTS_CurStateModified;
14871 }
14872 }
14873#endif /* VBOX_WITH_GUEST_PROPS */
14874
14875 rc = i_saveStateSettings(stsFlags);
14876
14877 if ( ( oldMachineState != MachineState_PoweredOff
14878 && oldMachineState != MachineState_Aborted
14879 && oldMachineState != MachineState_Teleported
14880 )
14881 && ( aMachineState == MachineState_PoweredOff
14882 || aMachineState == MachineState_Aborted
14883 || aMachineState == MachineState_Teleported
14884 )
14885 )
14886 {
14887 /* we've been shut down for any reason */
14888 /* no special action so far */
14889 }
14890
14891 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
14892 LogFlowThisFuncLeave();
14893 return rc;
14894}
14895
14896/**
14897 * Sends the current machine state value to the VM process.
14898 *
14899 * @note Locks this object for reading, then calls a client process.
14900 */
14901HRESULT SessionMachine::i_updateMachineStateOnClient()
14902{
14903 AutoCaller autoCaller(this);
14904 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14905
14906 ComPtr<IInternalSessionControl> directControl;
14907 {
14908 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14909 AssertReturn(!!mData, E_FAIL);
14910 if (mData->mSession.mLockType == LockType_VM)
14911 directControl = mData->mSession.mDirectControl;
14912
14913 /* directControl may be already set to NULL here in #OnSessionEnd()
14914 * called too early by the direct session process while there is still
14915 * some operation (like deleting the snapshot) in progress. The client
14916 * process in this case is waiting inside Session::close() for the
14917 * "end session" process object to complete, while #uninit() called by
14918 * #i_checkForDeath() on the Watcher thread is waiting for the pending
14919 * operation to complete. For now, we accept this inconsistent behavior
14920 * and simply do nothing here. */
14921
14922 if (mData->mSession.mState == SessionState_Unlocking)
14923 return S_OK;
14924 }
14925
14926 /* ignore notifications sent after #OnSessionEnd() is called */
14927 if (!directControl)
14928 return S_OK;
14929
14930 return directControl->UpdateMachineState(mData->mMachineState);
14931}
14932
14933
14934/*static*/
14935HRESULT Machine::i_setErrorStatic(HRESULT aResultCode, const char *pcszMsg, ...)
14936{
14937 va_list args;
14938 va_start(args, pcszMsg);
14939 HRESULT rc = setErrorInternal(aResultCode,
14940 getStaticClassIID(),
14941 getStaticComponentName(),
14942 Utf8Str(pcszMsg, args),
14943 false /* aWarning */,
14944 true /* aLogIt */);
14945 va_end(args);
14946 return rc;
14947}
14948
14949
14950HRESULT Machine::updateState(MachineState_T aState)
14951{
14952 NOREF(aState);
14953 ReturnComNotImplemented();
14954}
14955
14956HRESULT Machine::beginPowerUp(const ComPtr<IProgress> &aProgress)
14957{
14958 NOREF(aProgress);
14959 ReturnComNotImplemented();
14960}
14961
14962HRESULT Machine::endPowerUp(LONG aResult)
14963{
14964 NOREF(aResult);
14965 ReturnComNotImplemented();
14966}
14967
14968HRESULT Machine::beginPoweringDown(ComPtr<IProgress> &aProgress)
14969{
14970 NOREF(aProgress);
14971 ReturnComNotImplemented();
14972}
14973
14974HRESULT Machine::endPoweringDown(LONG aResult,
14975 const com::Utf8Str &aErrMsg)
14976{
14977 NOREF(aResult);
14978 NOREF(aErrMsg);
14979 ReturnComNotImplemented();
14980}
14981
14982HRESULT Machine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
14983 BOOL *aMatched,
14984 ULONG *aMaskedInterfaces)
14985{
14986 NOREF(aDevice);
14987 NOREF(aMatched);
14988 NOREF(aMaskedInterfaces);
14989 ReturnComNotImplemented();
14990
14991}
14992
14993HRESULT Machine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
14994{
14995 NOREF(aId); NOREF(aCaptureFilename);
14996 ReturnComNotImplemented();
14997}
14998
14999HRESULT Machine::detachUSBDevice(const com::Guid &aId,
15000 BOOL aDone)
15001{
15002 NOREF(aId);
15003 NOREF(aDone);
15004 ReturnComNotImplemented();
15005}
15006
15007HRESULT Machine::autoCaptureUSBDevices()
15008{
15009 ReturnComNotImplemented();
15010}
15011
15012HRESULT Machine::detachAllUSBDevices(BOOL aDone)
15013{
15014 NOREF(aDone);
15015 ReturnComNotImplemented();
15016}
15017
15018HRESULT Machine::onSessionEnd(const ComPtr<ISession> &aSession,
15019 ComPtr<IProgress> &aProgress)
15020{
15021 NOREF(aSession);
15022 NOREF(aProgress);
15023 ReturnComNotImplemented();
15024}
15025
15026HRESULT Machine::finishOnlineMergeMedium()
15027{
15028 ReturnComNotImplemented();
15029}
15030
15031HRESULT Machine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
15032 std::vector<com::Utf8Str> &aValues,
15033 std::vector<LONG64> &aTimestamps,
15034 std::vector<com::Utf8Str> &aFlags)
15035{
15036 NOREF(aNames);
15037 NOREF(aValues);
15038 NOREF(aTimestamps);
15039 NOREF(aFlags);
15040 ReturnComNotImplemented();
15041}
15042
15043HRESULT Machine::pushGuestProperty(const com::Utf8Str &aName,
15044 const com::Utf8Str &aValue,
15045 LONG64 aTimestamp,
15046 const com::Utf8Str &aFlags)
15047{
15048 NOREF(aName);
15049 NOREF(aValue);
15050 NOREF(aTimestamp);
15051 NOREF(aFlags);
15052 ReturnComNotImplemented();
15053}
15054
15055HRESULT Machine::lockMedia()
15056{
15057 ReturnComNotImplemented();
15058}
15059
15060HRESULT Machine::unlockMedia()
15061{
15062 ReturnComNotImplemented();
15063}
15064
15065HRESULT Machine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
15066 ComPtr<IMediumAttachment> &aNewAttachment)
15067{
15068 NOREF(aAttachment);
15069 NOREF(aNewAttachment);
15070 ReturnComNotImplemented();
15071}
15072
15073HRESULT Machine::reportVmStatistics(ULONG aValidStats,
15074 ULONG aCpuUser,
15075 ULONG aCpuKernel,
15076 ULONG aCpuIdle,
15077 ULONG aMemTotal,
15078 ULONG aMemFree,
15079 ULONG aMemBalloon,
15080 ULONG aMemShared,
15081 ULONG aMemCache,
15082 ULONG aPagedTotal,
15083 ULONG aMemAllocTotal,
15084 ULONG aMemFreeTotal,
15085 ULONG aMemBalloonTotal,
15086 ULONG aMemSharedTotal,
15087 ULONG aVmNetRx,
15088 ULONG aVmNetTx)
15089{
15090 NOREF(aValidStats);
15091 NOREF(aCpuUser);
15092 NOREF(aCpuKernel);
15093 NOREF(aCpuIdle);
15094 NOREF(aMemTotal);
15095 NOREF(aMemFree);
15096 NOREF(aMemBalloon);
15097 NOREF(aMemShared);
15098 NOREF(aMemCache);
15099 NOREF(aPagedTotal);
15100 NOREF(aMemAllocTotal);
15101 NOREF(aMemFreeTotal);
15102 NOREF(aMemBalloonTotal);
15103 NOREF(aMemSharedTotal);
15104 NOREF(aVmNetRx);
15105 NOREF(aVmNetTx);
15106 ReturnComNotImplemented();
15107}
15108
15109HRESULT Machine::authenticateExternal(const std::vector<com::Utf8Str> &aAuthParams,
15110 com::Utf8Str &aResult)
15111{
15112 NOREF(aAuthParams);
15113 NOREF(aResult);
15114 ReturnComNotImplemented();
15115}
15116
15117HRESULT Machine::createUnattendedInstaller(ComPtr<IUnattended> &aUnattended)
15118{
15119#ifdef VBOX_WITH_UNATTENDED
15120 ComObjPtr<Unattended> ptrUnattended;
15121 HRESULT hrc = ptrUnattended.createObject();
15122 if (SUCCEEDED(hrc))
15123 {
15124 AutoReadLock wlock(this COMMA_LOCKVAL_SRC_POS);
15125 hrc = ptrUnattended->init(this);
15126 if (SUCCEEDED(hrc))
15127 hrc = ptrUnattended.queryInterfaceTo(aUnattended.asOutParam());
15128 }
15129 return hrc;
15130#else
15131 NOREF(aUnattended);
15132 return E_NOTIMPL;
15133#endif
15134}
15135
15136HRESULT Machine::applyDefaults(const com::Utf8Str &aFlags)
15137{
15138 NOREF(aFlags);
15139 ReturnComNotImplemented();
15140}
15141
15142/* This isn't handled entirely by the wrapper generator yet. */
15143#ifdef VBOX_WITH_XPCOM
15144NS_DECL_CLASSINFO(SessionMachine)
15145NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
15146
15147NS_DECL_CLASSINFO(SnapshotMachine)
15148NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
15149#endif
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