VirtualBox

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

Last change on this file since 67729 was 67729, checked in by vboxsync, 8 years ago

UnattendedImpl: Better default properties. Added internal data getters so we can do away with the data passing later.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 519.0 KB
Line 
1/* $Id: MachineImpl.cpp 67729 2017-06-30 12:29:35Z 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.215389.xyz. 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#include "SystemPropertiesImpl.h"
47
48// generated header
49#include "VBoxEvents.h"
50
51#ifdef VBOX_WITH_USB
52# include "USBProxyService.h"
53#endif
54
55#include "AutoCaller.h"
56#include "HashedPw.h"
57#include "Performance.h"
58
59#include <iprt/asm.h>
60#include <iprt/path.h>
61#include <iprt/dir.h>
62#include <iprt/env.h>
63#include <iprt/lockvalidator.h>
64#include <iprt/process.h>
65#include <iprt/cpp/utils.h>
66#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
67#include <iprt/sha.h>
68#include <iprt/string.h>
69
70#include <VBox/com/array.h>
71#include <VBox/com/list.h>
72
73#include <VBox/err.h>
74#include <VBox/param.h>
75#include <VBox/settings.h>
76#include <VBox/vmm/ssm.h>
77
78#ifdef VBOX_WITH_GUEST_PROPS
79# include <VBox/HostServices/GuestPropertySvc.h>
80# include <VBox/com/array.h>
81#endif
82
83#include "VBox/com/MultiResult.h"
84
85#include <algorithm>
86
87#ifdef VBOX_WITH_DTRACE_R3_MAIN
88# include "dtrace/VBoxAPI.h"
89#endif
90
91#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
92# define HOSTSUFF_EXE ".exe"
93#else /* !RT_OS_WINDOWS */
94# define HOSTSUFF_EXE ""
95#endif /* !RT_OS_WINDOWS */
96
97// defines / prototypes
98/////////////////////////////////////////////////////////////////////////////
99
100/////////////////////////////////////////////////////////////////////////////
101// Machine::Data structure
102/////////////////////////////////////////////////////////////////////////////
103
104Machine::Data::Data()
105{
106 mRegistered = FALSE;
107 pMachineConfigFile = NULL;
108 /* Contains hints on what has changed when the user is using the VM (config
109 * changes, running the VM, ...). This is used to decide if a config needs
110 * to be written to disk. */
111 flModifications = 0;
112 /* VM modification usually also trigger setting the current state to
113 * "Modified". Although this is not always the case. An e.g. is the VM
114 * initialization phase or when snapshot related data is changed. The
115 * actually behavior is controlled by the following flag. */
116 m_fAllowStateModification = false;
117 mAccessible = FALSE;
118 /* mUuid is initialized in Machine::init() */
119
120 mMachineState = MachineState_PoweredOff;
121 RTTimeNow(&mLastStateChange);
122
123 mMachineStateDeps = 0;
124 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
125 mMachineStateChangePending = 0;
126
127 mCurrentStateModified = TRUE;
128 mGuestPropertiesModified = FALSE;
129
130 mSession.mPID = NIL_RTPROCESS;
131 mSession.mLockType = LockType_Null;
132 mSession.mState = SessionState_Unlocked;
133}
134
135Machine::Data::~Data()
136{
137 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
138 {
139 RTSemEventMultiDestroy(mMachineStateDepsSem);
140 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
141 }
142 if (pMachineConfigFile)
143 {
144 delete pMachineConfigFile;
145 pMachineConfigFile = NULL;
146 }
147}
148
149/////////////////////////////////////////////////////////////////////////////
150// Machine::HWData structure
151/////////////////////////////////////////////////////////////////////////////
152
153Machine::HWData::HWData()
154{
155 /* default values for a newly created machine */
156 mHWVersion = Utf8StrFmt("%d", SchemaDefs::DefaultHardwareVersion);
157 mMemorySize = 128;
158 mCPUCount = 1;
159 mCPUHotPlugEnabled = false;
160 mMemoryBalloonSize = 0;
161 mPageFusionEnabled = false;
162 mGraphicsControllerType = GraphicsControllerType_VBoxVGA;
163 mVRAMSize = 8;
164 mAccelerate3DEnabled = false;
165 mAccelerate2DVideoEnabled = false;
166 mMonitorCount = 1;
167 mVideoCaptureWidth = 1024;
168 mVideoCaptureHeight = 768;
169 mVideoCaptureRate = 512;
170 mVideoCaptureFPS = 25;
171 mVideoCaptureMaxTime = 0;
172 mVideoCaptureMaxFileSize = 0;
173 mVideoCaptureEnabled = false;
174 for (unsigned i = 0; i < RT_ELEMENTS(maVideoCaptureScreens); ++i)
175 maVideoCaptureScreens[i] = true;
176
177 mHWVirtExEnabled = true;
178 mHWVirtExNestedPagingEnabled = true;
179#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
180 mHWVirtExLargePagesEnabled = true;
181#else
182 /* Not supported on 32 bits hosts. */
183 mHWVirtExLargePagesEnabled = false;
184#endif
185 mHWVirtExVPIDEnabled = true;
186 mHWVirtExUXEnabled = true;
187 mHWVirtExForceEnabled = false;
188#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
189 mPAEEnabled = true;
190#else
191 mPAEEnabled = false;
192#endif
193 mLongMode = HC_ARCH_BITS == 64 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
194 mTripleFaultReset = false;
195 mAPIC = true;
196 mX2APIC = false;
197 mHPETEnabled = false;
198 mCpuExecutionCap = 100; /* Maximum CPU execution cap by default. */
199 mCpuIdPortabilityLevel = 0;
200 mCpuProfile = "host";
201
202 /* default boot order: floppy - DVD - HDD */
203 mBootOrder[0] = DeviceType_Floppy;
204 mBootOrder[1] = DeviceType_DVD;
205 mBootOrder[2] = DeviceType_HardDisk;
206 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
207 mBootOrder[i] = DeviceType_Null;
208
209 mClipboardMode = ClipboardMode_Disabled;
210 mDnDMode = DnDMode_Disabled;
211
212 mFirmwareType = FirmwareType_BIOS;
213 mKeyboardHIDType = KeyboardHIDType_PS2Keyboard;
214 mPointingHIDType = PointingHIDType_PS2Mouse;
215 mChipsetType = ChipsetType_PIIX3;
216 mParavirtProvider = ParavirtProvider_Default;
217 mEmulatedUSBCardReaderEnabled = FALSE;
218
219 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); ++i)
220 mCPUAttached[i] = false;
221
222 mIOCacheEnabled = true;
223 mIOCacheSize = 5; /* 5MB */
224}
225
226Machine::HWData::~HWData()
227{
228}
229
230/////////////////////////////////////////////////////////////////////////////
231// Machine class
232/////////////////////////////////////////////////////////////////////////////
233
234// constructor / destructor
235/////////////////////////////////////////////////////////////////////////////
236
237Machine::Machine() :
238#ifdef VBOX_WITH_RESOURCE_USAGE_API
239 mCollectorGuest(NULL),
240#endif
241 mPeer(NULL),
242 mParent(NULL),
243 mSerialPorts(),
244 mParallelPorts(),
245 uRegistryNeedsSaving(0)
246{}
247
248Machine::~Machine()
249{}
250
251HRESULT Machine::FinalConstruct()
252{
253 LogFlowThisFunc(("\n"));
254 return BaseFinalConstruct();
255}
256
257void Machine::FinalRelease()
258{
259 LogFlowThisFunc(("\n"));
260 uninit();
261 BaseFinalRelease();
262}
263
264/**
265 * Initializes a new machine instance; this init() variant creates a new, empty machine.
266 * This gets called from VirtualBox::CreateMachine().
267 *
268 * @param aParent Associated parent object
269 * @param strConfigFile Local file system path to the VM settings file (can
270 * be relative to the VirtualBox config directory).
271 * @param strName name for the machine
272 * @param llGroups list of groups for the machine
273 * @param aOsType OS Type of this machine or NULL.
274 * @param aId UUID for the new machine.
275 * @param fForceOverwrite Whether to overwrite an existing machine settings file.
276 * @param fDirectoryIncludesUUID Whether the use a special VM directory naming
277 * scheme (includes the UUID).
278 *
279 * @return Success indicator. if not S_OK, the machine object is invalid
280 */
281HRESULT Machine::init(VirtualBox *aParent,
282 const Utf8Str &strConfigFile,
283 const Utf8Str &strName,
284 const StringsList &llGroups,
285 GuestOSType *aOsType,
286 const Guid &aId,
287 bool fForceOverwrite,
288 bool fDirectoryIncludesUUID)
289{
290 LogFlowThisFuncEnter();
291 LogFlowThisFunc(("(Init_New) aConfigFile='%s'\n", strConfigFile.c_str()));
292
293 /* Enclose the state transition NotReady->InInit->Ready */
294 AutoInitSpan autoInitSpan(this);
295 AssertReturn(autoInitSpan.isOk(), E_FAIL);
296
297 HRESULT rc = initImpl(aParent, strConfigFile);
298 if (FAILED(rc)) return rc;
299
300 rc = i_tryCreateMachineConfigFile(fForceOverwrite);
301 if (FAILED(rc)) return rc;
302
303 if (SUCCEEDED(rc))
304 {
305 // create an empty machine config
306 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
307
308 rc = initDataAndChildObjects();
309 }
310
311 if (SUCCEEDED(rc))
312 {
313 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
314 mData->mAccessible = TRUE;
315
316 unconst(mData->mUuid) = aId;
317
318 mUserData->s.strName = strName;
319
320 mUserData->s.llGroups = llGroups;
321
322 mUserData->s.fDirectoryIncludesUUID = fDirectoryIncludesUUID;
323 // the "name sync" flag determines whether the machine directory gets renamed along
324 // with the machine file; say so if the settings file name is the same as the
325 // settings file parent directory (machine directory)
326 mUserData->s.fNameSync = i_isInOwnDir();
327
328 // initialize the default snapshots folder
329 rc = COMSETTER(SnapshotFolder)(NULL);
330 AssertComRC(rc);
331
332 if (aOsType)
333 {
334 /* Store OS type */
335 mUserData->s.strOsType = aOsType->i_id();
336
337 /* Apply BIOS defaults */
338 mBIOSSettings->i_applyDefaults(aOsType);
339
340 /* Let the OS type select 64-bit ness. */
341 mHWData->mLongMode = aOsType->i_is64Bit()
342 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
343
344 /* Let the OS type enable the X2APIC */
345 mHWData->mX2APIC = aOsType->i_recommendedX2APIC();
346 }
347
348 /* Apply network adapters defaults */
349 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
350 mNetworkAdapters[slot]->i_applyDefaults(aOsType);
351
352 /* Apply serial port defaults */
353 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
354 mSerialPorts[slot]->i_applyDefaults(aOsType);
355
356 /* Apply parallel port defaults */
357 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
358 mParallelPorts[slot]->i_applyDefaults();
359
360 /* At this point the changing of the current state modification
361 * flag is allowed. */
362 i_allowStateModification();
363
364 /* commit all changes made during the initialization */
365 i_commit();
366 }
367
368 /* Confirm a successful initialization when it's the case */
369 if (SUCCEEDED(rc))
370 {
371 if (mData->mAccessible)
372 autoInitSpan.setSucceeded();
373 else
374 autoInitSpan.setLimited();
375 }
376
377 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool, rc=%08X\n",
378 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
379 mData->mRegistered,
380 mData->mAccessible,
381 rc));
382
383 LogFlowThisFuncLeave();
384
385 return rc;
386}
387
388/**
389 * Initializes a new instance with data from machine XML (formerly Init_Registered).
390 * Gets called in two modes:
391 *
392 * -- from VirtualBox::initMachines() during VirtualBox startup; in that case, the
393 * UUID is specified and we mark the machine as "registered";
394 *
395 * -- from the public VirtualBox::OpenMachine() API, in which case the UUID is NULL
396 * and the machine remains unregistered until RegisterMachine() is called.
397 *
398 * @param aParent Associated parent object
399 * @param strConfigFile Local file system path to the VM settings file (can
400 * be relative to the VirtualBox config directory).
401 * @param aId UUID of the machine or NULL (see above).
402 *
403 * @return Success indicator. if not S_OK, the machine object is invalid
404 */
405HRESULT Machine::initFromSettings(VirtualBox *aParent,
406 const Utf8Str &strConfigFile,
407 const Guid *aId)
408{
409 LogFlowThisFuncEnter();
410 LogFlowThisFunc(("(Init_Registered) aConfigFile='%s\n", strConfigFile.c_str()));
411
412 /* Enclose the state transition NotReady->InInit->Ready */
413 AutoInitSpan autoInitSpan(this);
414 AssertReturn(autoInitSpan.isOk(), E_FAIL);
415
416 HRESULT rc = initImpl(aParent, strConfigFile);
417 if (FAILED(rc)) return rc;
418
419 if (aId)
420 {
421 // loading a registered VM:
422 unconst(mData->mUuid) = *aId;
423 mData->mRegistered = TRUE;
424 // now load the settings from XML:
425 rc = i_registeredInit();
426 // this calls initDataAndChildObjects() and loadSettings()
427 }
428 else
429 {
430 // opening an unregistered VM (VirtualBox::OpenMachine()):
431 rc = initDataAndChildObjects();
432
433 if (SUCCEEDED(rc))
434 {
435 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
436 mData->mAccessible = TRUE;
437
438 try
439 {
440 // load and parse machine XML; this will throw on XML or logic errors
441 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
442
443 // reject VM UUID duplicates, they can happen if someone
444 // tries to register an already known VM config again
445 if (aParent->i_findMachine(mData->pMachineConfigFile->uuid,
446 true /* fPermitInaccessible */,
447 false /* aDoSetError */,
448 NULL) != VBOX_E_OBJECT_NOT_FOUND)
449 {
450 throw setError(E_FAIL,
451 tr("Trying to open a VM config '%s' which has the same UUID as an existing virtual machine"),
452 mData->m_strConfigFile.c_str());
453 }
454
455 // use UUID from machine config
456 unconst(mData->mUuid) = mData->pMachineConfigFile->uuid;
457
458 rc = i_loadMachineDataFromSettings(*mData->pMachineConfigFile,
459 NULL /* puuidRegistry */);
460 if (FAILED(rc)) throw rc;
461
462 /* At this point the changing of the current state modification
463 * flag is allowed. */
464 i_allowStateModification();
465
466 i_commit();
467 }
468 catch (HRESULT err)
469 {
470 /* we assume that error info is set by the thrower */
471 rc = err;
472 }
473 catch (...)
474 {
475 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
476 }
477 }
478 }
479
480 /* Confirm a successful initialization when it's the case */
481 if (SUCCEEDED(rc))
482 {
483 if (mData->mAccessible)
484 autoInitSpan.setSucceeded();
485 else
486 {
487 autoInitSpan.setLimited();
488
489 // uninit media from this machine's media registry, or else
490 // reloading the settings will fail
491 mParent->i_unregisterMachineMedia(i_getId());
492 }
493 }
494
495 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
496 "rc=%08X\n",
497 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
498 mData->mRegistered, mData->mAccessible, rc));
499
500 LogFlowThisFuncLeave();
501
502 return rc;
503}
504
505/**
506 * Initializes a new instance from a machine config that is already in memory
507 * (import OVF case). Since we are importing, the UUID in the machine
508 * config is ignored and we always generate a fresh one.
509 *
510 * @param aParent Associated parent object.
511 * @param strName Name for the new machine; this overrides what is specified in config and is used
512 * for the settings file as well.
513 * @param config Machine configuration loaded and parsed from XML.
514 *
515 * @return Success indicator. if not S_OK, the machine object is invalid
516 */
517HRESULT Machine::init(VirtualBox *aParent,
518 const Utf8Str &strName,
519 const settings::MachineConfigFile &config)
520{
521 LogFlowThisFuncEnter();
522
523 /* Enclose the state transition NotReady->InInit->Ready */
524 AutoInitSpan autoInitSpan(this);
525 AssertReturn(autoInitSpan.isOk(), E_FAIL);
526
527 Utf8Str strConfigFile;
528 aParent->i_getDefaultMachineFolder(strConfigFile);
529 strConfigFile.append(RTPATH_DELIMITER);
530 strConfigFile.append(strName);
531 strConfigFile.append(RTPATH_DELIMITER);
532 strConfigFile.append(strName);
533 strConfigFile.append(".vbox");
534
535 HRESULT rc = initImpl(aParent, strConfigFile);
536 if (FAILED(rc)) return rc;
537
538 rc = i_tryCreateMachineConfigFile(false /* fForceOverwrite */);
539 if (FAILED(rc)) return rc;
540
541 rc = initDataAndChildObjects();
542
543 if (SUCCEEDED(rc))
544 {
545 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
546 mData->mAccessible = TRUE;
547
548 // create empty machine config for instance data
549 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
550
551 // generate fresh UUID, ignore machine config
552 unconst(mData->mUuid).create();
553
554 rc = i_loadMachineDataFromSettings(config,
555 &mData->mUuid); // puuidRegistry: initialize media with this registry ID
556
557 // override VM name as well, it may be different
558 mUserData->s.strName = strName;
559
560 if (SUCCEEDED(rc))
561 {
562 /* At this point the changing of the current state modification
563 * flag is allowed. */
564 i_allowStateModification();
565
566 /* commit all changes made during the initialization */
567 i_commit();
568 }
569 }
570
571 /* Confirm a successful initialization when it's the case */
572 if (SUCCEEDED(rc))
573 {
574 if (mData->mAccessible)
575 autoInitSpan.setSucceeded();
576 else
577 {
578 /* Ignore all errors from unregistering, they would destroy
579- * the more interesting error information we already have,
580- * pinpointing the issue with the VM config. */
581 ErrorInfoKeeper eik;
582
583 autoInitSpan.setLimited();
584
585 // uninit media from this machine's media registry, or else
586 // reloading the settings will fail
587 mParent->i_unregisterMachineMedia(i_getId());
588 }
589 }
590
591 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
592 "rc=%08X\n",
593 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
594 mData->mRegistered, mData->mAccessible, rc));
595
596 LogFlowThisFuncLeave();
597
598 return rc;
599}
600
601/**
602 * Shared code between the various init() implementations.
603 * @param aParent The VirtualBox object.
604 * @param strConfigFile Settings file.
605 * @return
606 */
607HRESULT Machine::initImpl(VirtualBox *aParent,
608 const Utf8Str &strConfigFile)
609{
610 LogFlowThisFuncEnter();
611
612 AssertReturn(aParent, E_INVALIDARG);
613 AssertReturn(!strConfigFile.isEmpty(), E_INVALIDARG);
614
615 HRESULT rc = S_OK;
616
617 /* share the parent weakly */
618 unconst(mParent) = aParent;
619
620 /* allocate the essential machine data structure (the rest will be
621 * allocated later by initDataAndChildObjects() */
622 mData.allocate();
623
624 /* memorize the config file name (as provided) */
625 mData->m_strConfigFile = strConfigFile;
626
627 /* get the full file name */
628 int vrc1 = mParent->i_calculateFullPath(strConfigFile, mData->m_strConfigFileFull);
629 if (RT_FAILURE(vrc1))
630 return setError(VBOX_E_FILE_ERROR,
631 tr("Invalid machine settings file name '%s' (%Rrc)"),
632 strConfigFile.c_str(),
633 vrc1);
634
635 LogFlowThisFuncLeave();
636
637 return rc;
638}
639
640/**
641 * Tries to create a machine settings file in the path stored in the machine
642 * instance data. Used when a new machine is created to fail gracefully if
643 * the settings file could not be written (e.g. because machine dir is read-only).
644 * @return
645 */
646HRESULT Machine::i_tryCreateMachineConfigFile(bool fForceOverwrite)
647{
648 HRESULT rc = S_OK;
649
650 // when we create a new machine, we must be able to create the settings file
651 RTFILE f = NIL_RTFILE;
652 int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
653 if ( RT_SUCCESS(vrc)
654 || vrc == VERR_SHARING_VIOLATION
655 )
656 {
657 if (RT_SUCCESS(vrc))
658 RTFileClose(f);
659 if (!fForceOverwrite)
660 rc = setError(VBOX_E_FILE_ERROR,
661 tr("Machine settings file '%s' already exists"),
662 mData->m_strConfigFileFull.c_str());
663 else
664 {
665 /* try to delete the config file, as otherwise the creation
666 * of a new settings file will fail. */
667 int vrc2 = RTFileDelete(mData->m_strConfigFileFull.c_str());
668 if (RT_FAILURE(vrc2))
669 rc = setError(VBOX_E_FILE_ERROR,
670 tr("Could not delete the existing settings file '%s' (%Rrc)"),
671 mData->m_strConfigFileFull.c_str(), vrc2);
672 }
673 }
674 else if ( vrc != VERR_FILE_NOT_FOUND
675 && vrc != VERR_PATH_NOT_FOUND
676 )
677 rc = setError(VBOX_E_FILE_ERROR,
678 tr("Invalid machine settings file name '%s' (%Rrc)"),
679 mData->m_strConfigFileFull.c_str(),
680 vrc);
681 return rc;
682}
683
684/**
685 * Initializes the registered machine by loading the settings file.
686 * This method is separated from #init() in order to make it possible to
687 * retry the operation after VirtualBox startup instead of refusing to
688 * startup the whole VirtualBox server in case if the settings file of some
689 * registered VM is invalid or inaccessible.
690 *
691 * @note Must be always called from this object's write lock
692 * (unless called from #init() that doesn't need any locking).
693 * @note Locks the mUSBController method for writing.
694 * @note Subclasses must not call this method.
695 */
696HRESULT Machine::i_registeredInit()
697{
698 AssertReturn(!i_isSessionMachine(), E_FAIL);
699 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
700 AssertReturn(mData->mUuid.isValid(), E_FAIL);
701 AssertReturn(!mData->mAccessible, E_FAIL);
702
703 HRESULT rc = initDataAndChildObjects();
704
705 if (SUCCEEDED(rc))
706 {
707 /* Temporarily reset the registered flag in order to let setters
708 * potentially called from loadSettings() succeed (isMutable() used in
709 * all setters will return FALSE for a Machine instance if mRegistered
710 * is TRUE). */
711 mData->mRegistered = FALSE;
712
713 try
714 {
715 // load and parse machine XML; this will throw on XML or logic errors
716 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
717
718 if (mData->mUuid != mData->pMachineConfigFile->uuid)
719 throw setError(E_FAIL,
720 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
721 mData->pMachineConfigFile->uuid.raw(),
722 mData->m_strConfigFileFull.c_str(),
723 mData->mUuid.toString().c_str(),
724 mParent->i_settingsFilePath().c_str());
725
726 rc = i_loadMachineDataFromSettings(*mData->pMachineConfigFile,
727 NULL /* const Guid *puuidRegistry */);
728 if (FAILED(rc)) throw rc;
729 }
730 catch (HRESULT err)
731 {
732 /* we assume that error info is set by the thrower */
733 rc = err;
734 }
735 catch (...)
736 {
737 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
738 }
739
740 /* Restore the registered flag (even on failure) */
741 mData->mRegistered = TRUE;
742 }
743
744 if (SUCCEEDED(rc))
745 {
746 /* Set mAccessible to TRUE only if we successfully locked and loaded
747 * the settings file */
748 mData->mAccessible = TRUE;
749
750 /* commit all changes made during loading the settings file */
751 i_commit(); /// @todo r=dj why do we need a commit during init?!? this is very expensive
752 /// @todo r=klaus for some reason the settings loading logic backs up
753 // the settings, and therefore a commit is needed. Should probably be changed.
754 }
755 else
756 {
757 /* If the machine is registered, then, instead of returning a
758 * failure, we mark it as inaccessible and set the result to
759 * success to give it a try later */
760
761 /* fetch the current error info */
762 mData->mAccessError = com::ErrorInfo();
763 Log1Warning(("Machine {%RTuuid} is inaccessible! [%ls]\n", mData->mUuid.raw(), mData->mAccessError.getText().raw()));
764
765 /* rollback all changes */
766 i_rollback(false /* aNotify */);
767
768 // uninit media from this machine's media registry, or else
769 // reloading the settings will fail
770 mParent->i_unregisterMachineMedia(i_getId());
771
772 /* uninitialize the common part to make sure all data is reset to
773 * default (null) values */
774 uninitDataAndChildObjects();
775
776 rc = S_OK;
777 }
778
779 return rc;
780}
781
782/**
783 * Uninitializes the instance.
784 * Called either from FinalRelease() or by the parent when it gets destroyed.
785 *
786 * @note The caller of this method must make sure that this object
787 * a) doesn't have active callers on the current thread and b) is not locked
788 * by the current thread; otherwise uninit() will hang either a) due to
789 * AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
790 * a dead-lock caused by this thread waiting for all callers on the other
791 * threads are done but preventing them from doing so by holding a lock.
792 */
793void Machine::uninit()
794{
795 LogFlowThisFuncEnter();
796
797 Assert(!isWriteLockOnCurrentThread());
798
799 Assert(!uRegistryNeedsSaving);
800 if (uRegistryNeedsSaving)
801 {
802 AutoCaller autoCaller(this);
803 if (SUCCEEDED(autoCaller.rc()))
804 {
805 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
806 i_saveSettings(NULL, Machine::SaveS_Force);
807 }
808 }
809
810 /* Enclose the state transition Ready->InUninit->NotReady */
811 AutoUninitSpan autoUninitSpan(this);
812 if (autoUninitSpan.uninitDone())
813 return;
814
815 Assert(!i_isSnapshotMachine());
816 Assert(!i_isSessionMachine());
817 Assert(!!mData);
818
819 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
820 LogFlowThisFunc(("mRegistered=%d\n", mData->mRegistered));
821
822 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
823
824 if (!mData->mSession.mMachine.isNull())
825 {
826 /* Theoretically, this can only happen if the VirtualBox server has been
827 * terminated while there were clients running that owned open direct
828 * sessions. Since in this case we are definitely called by
829 * VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
830 * won't happen on the client watcher thread (because it has a
831 * VirtualBox caller for the duration of the
832 * SessionMachine::i_checkForDeath() call, so that VirtualBox::uninit()
833 * cannot happen until the VirtualBox caller is released). This is
834 * important, because SessionMachine::uninit() cannot correctly operate
835 * after we return from this method (it expects the Machine instance is
836 * still valid). We'll call it ourselves below.
837 */
838 Log1WarningThisFunc(("Session machine is not NULL (%p), the direct session is still open!\n",
839 (SessionMachine*)mData->mSession.mMachine));
840
841 if (Global::IsOnlineOrTransient(mData->mMachineState))
842 {
843 Log1WarningThisFunc(("Setting state to Aborted!\n"));
844 /* set machine state using SessionMachine reimplementation */
845 static_cast<Machine*>(mData->mSession.mMachine)->i_setMachineState(MachineState_Aborted);
846 }
847
848 /*
849 * Uninitialize SessionMachine using public uninit() to indicate
850 * an unexpected uninitialization.
851 */
852 mData->mSession.mMachine->uninit();
853 /* SessionMachine::uninit() must set mSession.mMachine to null */
854 Assert(mData->mSession.mMachine.isNull());
855 }
856
857 // uninit media from this machine's media registry, if they're still there
858 Guid uuidMachine(i_getId());
859
860 /* the lock is no more necessary (SessionMachine is uninitialized) */
861 alock.release();
862
863 /* XXX This will fail with
864 * "cannot be closed because it is still attached to 1 virtual machines"
865 * because at this point we did not call uninitDataAndChildObjects() yet
866 * and therefore also removeBackReference() for all these mediums was not called! */
867
868 if (uuidMachine.isValid() && !uuidMachine.isZero()) // can be empty if we're called from a failure of Machine::init
869 mParent->i_unregisterMachineMedia(uuidMachine);
870
871 // has machine been modified?
872 if (mData->flModifications)
873 {
874 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
875 i_rollback(false /* aNotify */);
876 }
877
878 if (mData->mAccessible)
879 uninitDataAndChildObjects();
880
881 /* free the essential data structure last */
882 mData.free();
883
884 LogFlowThisFuncLeave();
885}
886
887// Wrapped IMachine properties
888/////////////////////////////////////////////////////////////////////////////
889HRESULT Machine::getParent(ComPtr<IVirtualBox> &aParent)
890{
891 /* mParent is constant during life time, no need to lock */
892 ComObjPtr<VirtualBox> pVirtualBox(mParent);
893 aParent = pVirtualBox;
894
895 return S_OK;
896}
897
898
899HRESULT Machine::getAccessible(BOOL *aAccessible)
900{
901 /* In some cases (medium registry related), it is necessary to be able to
902 * go through the list of all machines. Happens when an inaccessible VM
903 * has a sensible medium registry. */
904 AutoReadLock mllock(mParent->i_getMachinesListLockHandle() COMMA_LOCKVAL_SRC_POS);
905 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
906
907 HRESULT rc = S_OK;
908
909 if (!mData->mAccessible)
910 {
911 /* try to initialize the VM once more if not accessible */
912
913 AutoReinitSpan autoReinitSpan(this);
914 AssertReturn(autoReinitSpan.isOk(), E_FAIL);
915
916#ifdef DEBUG
917 LogFlowThisFunc(("Dumping media backreferences\n"));
918 mParent->i_dumpAllBackRefs();
919#endif
920
921 if (mData->pMachineConfigFile)
922 {
923 // reset the XML file to force loadSettings() (called from i_registeredInit())
924 // to parse it again; the file might have changed
925 delete mData->pMachineConfigFile;
926 mData->pMachineConfigFile = NULL;
927 }
928
929 rc = i_registeredInit();
930
931 if (SUCCEEDED(rc) && mData->mAccessible)
932 {
933 autoReinitSpan.setSucceeded();
934
935 /* make sure interesting parties will notice the accessibility
936 * state change */
937 mParent->i_onMachineStateChange(mData->mUuid, mData->mMachineState);
938 mParent->i_onMachineDataChange(mData->mUuid);
939 }
940 }
941
942 if (SUCCEEDED(rc))
943 *aAccessible = mData->mAccessible;
944
945 LogFlowThisFuncLeave();
946
947 return rc;
948}
949
950HRESULT Machine::getAccessError(ComPtr<IVirtualBoxErrorInfo> &aAccessError)
951{
952 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
953
954 if (mData->mAccessible || !mData->mAccessError.isBasicAvailable())
955 {
956 /* return shortly */
957 aAccessError = NULL;
958 return S_OK;
959 }
960
961 HRESULT rc = S_OK;
962
963 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
964 rc = errorInfo.createObject();
965 if (SUCCEEDED(rc))
966 {
967 errorInfo->init(mData->mAccessError.getResultCode(),
968 mData->mAccessError.getInterfaceID().ref(),
969 Utf8Str(mData->mAccessError.getComponent()).c_str(),
970 Utf8Str(mData->mAccessError.getText()));
971 aAccessError = errorInfo;
972 }
973
974 return rc;
975}
976
977HRESULT Machine::getName(com::Utf8Str &aName)
978{
979 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
980
981 aName = mUserData->s.strName;
982
983 return S_OK;
984}
985
986HRESULT Machine::setName(const com::Utf8Str &aName)
987{
988 // prohibit setting a UUID only as the machine name, or else it can
989 // never be found by findMachine()
990 Guid test(aName);
991
992 if (test.isValid())
993 return setError(E_INVALIDARG, tr("A machine cannot have a UUID as its name"));
994
995 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
996
997 HRESULT rc = i_checkStateDependency(MutableStateDep);
998 if (FAILED(rc)) return rc;
999
1000 i_setModified(IsModified_MachineData);
1001 mUserData.backup();
1002 mUserData->s.strName = aName;
1003
1004 return S_OK;
1005}
1006
1007HRESULT Machine::getDescription(com::Utf8Str &aDescription)
1008{
1009 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1010
1011 aDescription = mUserData->s.strDescription;
1012
1013 return S_OK;
1014}
1015
1016HRESULT Machine::setDescription(const com::Utf8Str &aDescription)
1017{
1018 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1019
1020 // this can be done in principle in any state as it doesn't affect the VM
1021 // significantly, but play safe by not messing around while complex
1022 // activities are going on
1023 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
1024 if (FAILED(rc)) return rc;
1025
1026 i_setModified(IsModified_MachineData);
1027 mUserData.backup();
1028 mUserData->s.strDescription = aDescription;
1029
1030 return S_OK;
1031}
1032
1033HRESULT Machine::getId(com::Guid &aId)
1034{
1035 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1036
1037 aId = mData->mUuid;
1038
1039 return S_OK;
1040}
1041
1042HRESULT Machine::getGroups(std::vector<com::Utf8Str> &aGroups)
1043{
1044 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1045 aGroups.resize(mUserData->s.llGroups.size());
1046 size_t i = 0;
1047 for (StringsList::const_iterator
1048 it = mUserData->s.llGroups.begin();
1049 it != mUserData->s.llGroups.end();
1050 ++it, ++i)
1051 aGroups[i] = (*it);
1052
1053 return S_OK;
1054}
1055
1056HRESULT Machine::setGroups(const std::vector<com::Utf8Str> &aGroups)
1057{
1058 StringsList llGroups;
1059 HRESULT rc = mParent->i_convertMachineGroups(aGroups, &llGroups);
1060 if (FAILED(rc))
1061 return rc;
1062
1063 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1064
1065 rc = i_checkStateDependency(MutableOrSavedStateDep);
1066 if (FAILED(rc)) return rc;
1067
1068 i_setModified(IsModified_MachineData);
1069 mUserData.backup();
1070 mUserData->s.llGroups = llGroups;
1071
1072 return S_OK;
1073}
1074
1075HRESULT Machine::getOSTypeId(com::Utf8Str &aOSTypeId)
1076{
1077 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1078
1079 aOSTypeId = mUserData->s.strOsType;
1080
1081 return S_OK;
1082}
1083
1084HRESULT Machine::setOSTypeId(const com::Utf8Str &aOSTypeId)
1085{
1086 /* look up the object by Id to check it is valid */
1087 ComObjPtr<GuestOSType> pGuestOSType;
1088 HRESULT rc = mParent->i_findGuestOSType(aOSTypeId,
1089 pGuestOSType);
1090 if (FAILED(rc)) return rc;
1091
1092 /* when setting, always use the "etalon" value for consistency -- lookup
1093 * by ID is case-insensitive and the input value may have different case */
1094 Utf8Str osTypeId = pGuestOSType->i_id();
1095
1096 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1097
1098 rc = i_checkStateDependency(MutableStateDep);
1099 if (FAILED(rc)) return rc;
1100
1101 i_setModified(IsModified_MachineData);
1102 mUserData.backup();
1103 mUserData->s.strOsType = osTypeId;
1104
1105 return S_OK;
1106}
1107
1108HRESULT Machine::getFirmwareType(FirmwareType_T *aFirmwareType)
1109{
1110 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1111
1112 *aFirmwareType = mHWData->mFirmwareType;
1113
1114 return S_OK;
1115}
1116
1117HRESULT Machine::setFirmwareType(FirmwareType_T aFirmwareType)
1118{
1119 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1120
1121 HRESULT rc = i_checkStateDependency(MutableStateDep);
1122 if (FAILED(rc)) return rc;
1123
1124 i_setModified(IsModified_MachineData);
1125 mHWData.backup();
1126 mHWData->mFirmwareType = aFirmwareType;
1127
1128 return S_OK;
1129}
1130
1131HRESULT Machine::getKeyboardHIDType(KeyboardHIDType_T *aKeyboardHIDType)
1132{
1133 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1134
1135 *aKeyboardHIDType = mHWData->mKeyboardHIDType;
1136
1137 return S_OK;
1138}
1139
1140HRESULT Machine::setKeyboardHIDType(KeyboardHIDType_T aKeyboardHIDType)
1141{
1142 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1143
1144 HRESULT rc = i_checkStateDependency(MutableStateDep);
1145 if (FAILED(rc)) return rc;
1146
1147 i_setModified(IsModified_MachineData);
1148 mHWData.backup();
1149 mHWData->mKeyboardHIDType = aKeyboardHIDType;
1150
1151 return S_OK;
1152}
1153
1154HRESULT Machine::getPointingHIDType(PointingHIDType_T *aPointingHIDType)
1155{
1156 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1157
1158 *aPointingHIDType = mHWData->mPointingHIDType;
1159
1160 return S_OK;
1161}
1162
1163HRESULT Machine::setPointingHIDType(PointingHIDType_T aPointingHIDType)
1164{
1165 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1166
1167 HRESULT rc = i_checkStateDependency(MutableStateDep);
1168 if (FAILED(rc)) return rc;
1169
1170 i_setModified(IsModified_MachineData);
1171 mHWData.backup();
1172 mHWData->mPointingHIDType = aPointingHIDType;
1173
1174 return S_OK;
1175}
1176
1177HRESULT Machine::getChipsetType(ChipsetType_T *aChipsetType)
1178{
1179 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1180
1181 *aChipsetType = mHWData->mChipsetType;
1182
1183 return S_OK;
1184}
1185
1186HRESULT Machine::setChipsetType(ChipsetType_T aChipsetType)
1187{
1188 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1189
1190 HRESULT rc = i_checkStateDependency(MutableStateDep);
1191 if (FAILED(rc)) return rc;
1192
1193 if (aChipsetType != mHWData->mChipsetType)
1194 {
1195 i_setModified(IsModified_MachineData);
1196 mHWData.backup();
1197 mHWData->mChipsetType = aChipsetType;
1198
1199 // Resize network adapter array, to be finalized on commit/rollback.
1200 // We must not throw away entries yet, otherwise settings are lost
1201 // without a way to roll back.
1202 size_t newCount = Global::getMaxNetworkAdapters(aChipsetType);
1203 size_t oldCount = mNetworkAdapters.size();
1204 if (newCount > oldCount)
1205 {
1206 mNetworkAdapters.resize(newCount);
1207 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); slot++)
1208 {
1209 unconst(mNetworkAdapters[slot]).createObject();
1210 mNetworkAdapters[slot]->init(this, (ULONG)slot);
1211 }
1212 }
1213 }
1214
1215 return S_OK;
1216}
1217
1218HRESULT Machine::getParavirtDebug(com::Utf8Str &aParavirtDebug)
1219{
1220 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1221
1222 aParavirtDebug = mHWData->mParavirtDebug;
1223 return S_OK;
1224}
1225
1226HRESULT Machine::setParavirtDebug(const com::Utf8Str &aParavirtDebug)
1227{
1228 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1229
1230 HRESULT rc = i_checkStateDependency(MutableStateDep);
1231 if (FAILED(rc)) return rc;
1232
1233 /** @todo Parse/validate options? */
1234 if (aParavirtDebug != mHWData->mParavirtDebug)
1235 {
1236 i_setModified(IsModified_MachineData);
1237 mHWData.backup();
1238 mHWData->mParavirtDebug = aParavirtDebug;
1239 }
1240
1241 return S_OK;
1242}
1243
1244HRESULT Machine::getParavirtProvider(ParavirtProvider_T *aParavirtProvider)
1245{
1246 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1247
1248 *aParavirtProvider = mHWData->mParavirtProvider;
1249
1250 return S_OK;
1251}
1252
1253HRESULT Machine::setParavirtProvider(ParavirtProvider_T aParavirtProvider)
1254{
1255 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1256
1257 HRESULT rc = i_checkStateDependency(MutableStateDep);
1258 if (FAILED(rc)) return rc;
1259
1260 if (aParavirtProvider != mHWData->mParavirtProvider)
1261 {
1262 i_setModified(IsModified_MachineData);
1263 mHWData.backup();
1264 mHWData->mParavirtProvider = aParavirtProvider;
1265 }
1266
1267 return S_OK;
1268}
1269
1270HRESULT Machine::getEffectiveParavirtProvider(ParavirtProvider_T *aParavirtProvider)
1271{
1272 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1273
1274 *aParavirtProvider = mHWData->mParavirtProvider;
1275 switch (mHWData->mParavirtProvider)
1276 {
1277 case ParavirtProvider_None:
1278 case ParavirtProvider_HyperV:
1279 case ParavirtProvider_KVM:
1280 case ParavirtProvider_Minimal:
1281 break;
1282
1283 /* Resolve dynamic provider types to the effective types. */
1284 default:
1285 {
1286 ComObjPtr<GuestOSType> pGuestOSType;
1287 HRESULT hrc2 = mParent->i_findGuestOSType(mUserData->s.strOsType,
1288 pGuestOSType);
1289 AssertMsgReturn(SUCCEEDED(hrc2), ("Failed to get guest OS type. hrc2=%Rhrc\n", hrc2), hrc2);
1290
1291 Utf8Str guestTypeFamilyId = pGuestOSType->i_familyId();
1292 bool fOsXGuest = guestTypeFamilyId == "MacOS";
1293
1294 switch (mHWData->mParavirtProvider)
1295 {
1296 case ParavirtProvider_Legacy:
1297 {
1298 if (fOsXGuest)
1299 *aParavirtProvider = ParavirtProvider_Minimal;
1300 else
1301 *aParavirtProvider = ParavirtProvider_None;
1302 break;
1303 }
1304
1305 case ParavirtProvider_Default:
1306 {
1307 if (fOsXGuest)
1308 *aParavirtProvider = ParavirtProvider_Minimal;
1309 else if ( mUserData->s.strOsType == "Windows10"
1310 || mUserData->s.strOsType == "Windows10_64"
1311 || mUserData->s.strOsType == "Windows81"
1312 || mUserData->s.strOsType == "Windows81_64"
1313 || mUserData->s.strOsType == "Windows8"
1314 || mUserData->s.strOsType == "Windows8_64"
1315 || mUserData->s.strOsType == "Windows7"
1316 || mUserData->s.strOsType == "Windows7_64"
1317 || mUserData->s.strOsType == "WindowsVista"
1318 || mUserData->s.strOsType == "WindowsVista_64"
1319 || mUserData->s.strOsType == "Windows2012"
1320 || mUserData->s.strOsType == "Windows2012_64"
1321 || mUserData->s.strOsType == "Windows2008"
1322 || mUserData->s.strOsType == "Windows2008_64")
1323 {
1324 *aParavirtProvider = ParavirtProvider_HyperV;
1325 }
1326 else if ( mUserData->s.strOsType == "Linux26" // Linux22 and Linux24 omitted as they're too old
1327 || mUserData->s.strOsType == "Linux26_64" // for having any KVM paravirtualization support.
1328 || mUserData->s.strOsType == "Linux"
1329 || mUserData->s.strOsType == "Linux_64"
1330 || mUserData->s.strOsType == "ArchLinux"
1331 || mUserData->s.strOsType == "ArchLinux_64"
1332 || mUserData->s.strOsType == "Debian"
1333 || mUserData->s.strOsType == "Debian_64"
1334 || mUserData->s.strOsType == "Fedora"
1335 || mUserData->s.strOsType == "Fedora_64"
1336 || mUserData->s.strOsType == "Gentoo"
1337 || mUserData->s.strOsType == "Gentoo_64"
1338 || mUserData->s.strOsType == "Mandriva"
1339 || mUserData->s.strOsType == "Mandriva_64"
1340 || mUserData->s.strOsType == "OpenSUSE"
1341 || mUserData->s.strOsType == "OpenSUSE_64"
1342 || mUserData->s.strOsType == "Oracle"
1343 || mUserData->s.strOsType == "Oracle_64"
1344 || mUserData->s.strOsType == "RedHat"
1345 || mUserData->s.strOsType == "RedHat_64"
1346 || mUserData->s.strOsType == "Turbolinux"
1347 || mUserData->s.strOsType == "Turbolinux_64"
1348 || mUserData->s.strOsType == "Ubuntu"
1349 || mUserData->s.strOsType == "Ubuntu_64"
1350 || mUserData->s.strOsType == "Xandros"
1351 || mUserData->s.strOsType == "Xandros_64")
1352 {
1353 *aParavirtProvider = ParavirtProvider_KVM;
1354 }
1355 else
1356 *aParavirtProvider = ParavirtProvider_None;
1357 break;
1358 }
1359
1360 default: AssertFailedBreak(); /* Shut up MSC. */
1361 }
1362 break;
1363 }
1364 }
1365
1366 Assert( *aParavirtProvider == ParavirtProvider_None
1367 || *aParavirtProvider == ParavirtProvider_Minimal
1368 || *aParavirtProvider == ParavirtProvider_HyperV
1369 || *aParavirtProvider == ParavirtProvider_KVM);
1370 return S_OK;
1371}
1372
1373HRESULT Machine::getHardwareVersion(com::Utf8Str &aHardwareVersion)
1374{
1375 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1376
1377 aHardwareVersion = mHWData->mHWVersion;
1378
1379 return S_OK;
1380}
1381
1382HRESULT Machine::setHardwareVersion(const com::Utf8Str &aHardwareVersion)
1383{
1384 /* check known version */
1385 Utf8Str hwVersion = aHardwareVersion;
1386 if ( hwVersion.compare("1") != 0
1387 && hwVersion.compare("2") != 0) // VBox 2.1.x and later (VMMDev heap)
1388 return setError(E_INVALIDARG,
1389 tr("Invalid hardware version: %s\n"), aHardwareVersion.c_str());
1390
1391 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1392
1393 HRESULT rc = i_checkStateDependency(MutableStateDep);
1394 if (FAILED(rc)) return rc;
1395
1396 i_setModified(IsModified_MachineData);
1397 mHWData.backup();
1398 mHWData->mHWVersion = aHardwareVersion;
1399
1400 return S_OK;
1401}
1402
1403HRESULT Machine::getHardwareUUID(com::Guid &aHardwareUUID)
1404{
1405 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1406
1407 if (!mHWData->mHardwareUUID.isZero())
1408 aHardwareUUID = mHWData->mHardwareUUID;
1409 else
1410 aHardwareUUID = mData->mUuid;
1411
1412 return S_OK;
1413}
1414
1415HRESULT Machine::setHardwareUUID(const com::Guid &aHardwareUUID)
1416{
1417 if (!aHardwareUUID.isValid())
1418 return E_INVALIDARG;
1419
1420 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1421
1422 HRESULT rc = i_checkStateDependency(MutableStateDep);
1423 if (FAILED(rc)) return rc;
1424
1425 i_setModified(IsModified_MachineData);
1426 mHWData.backup();
1427 if (aHardwareUUID == mData->mUuid)
1428 mHWData->mHardwareUUID.clear();
1429 else
1430 mHWData->mHardwareUUID = aHardwareUUID;
1431
1432 return S_OK;
1433}
1434
1435HRESULT Machine::getMemorySize(ULONG *aMemorySize)
1436{
1437 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1438
1439 *aMemorySize = mHWData->mMemorySize;
1440
1441 return S_OK;
1442}
1443
1444HRESULT Machine::setMemorySize(ULONG aMemorySize)
1445{
1446 /* check RAM limits */
1447 if ( aMemorySize < MM_RAM_MIN_IN_MB
1448 || aMemorySize > MM_RAM_MAX_IN_MB
1449 )
1450 return setError(E_INVALIDARG,
1451 tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1452 aMemorySize, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
1453
1454 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1455
1456 HRESULT rc = i_checkStateDependency(MutableStateDep);
1457 if (FAILED(rc)) return rc;
1458
1459 i_setModified(IsModified_MachineData);
1460 mHWData.backup();
1461 mHWData->mMemorySize = aMemorySize;
1462
1463 return S_OK;
1464}
1465
1466HRESULT Machine::getCPUCount(ULONG *aCPUCount)
1467{
1468 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1469
1470 *aCPUCount = mHWData->mCPUCount;
1471
1472 return S_OK;
1473}
1474
1475HRESULT Machine::setCPUCount(ULONG aCPUCount)
1476{
1477 /* check CPU limits */
1478 if ( aCPUCount < SchemaDefs::MinCPUCount
1479 || aCPUCount > SchemaDefs::MaxCPUCount
1480 )
1481 return setError(E_INVALIDARG,
1482 tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
1483 aCPUCount, SchemaDefs::MinCPUCount, SchemaDefs::MaxCPUCount);
1484
1485 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1486
1487 /* We cant go below the current number of CPUs attached if hotplug is enabled*/
1488 if (mHWData->mCPUHotPlugEnabled)
1489 {
1490 for (unsigned idx = aCPUCount; idx < SchemaDefs::MaxCPUCount; idx++)
1491 {
1492 if (mHWData->mCPUAttached[idx])
1493 return setError(E_INVALIDARG,
1494 tr("There is still a CPU attached to socket %lu."
1495 "Detach the CPU before removing the socket"),
1496 aCPUCount, idx+1);
1497 }
1498 }
1499
1500 HRESULT rc = i_checkStateDependency(MutableStateDep);
1501 if (FAILED(rc)) return rc;
1502
1503 i_setModified(IsModified_MachineData);
1504 mHWData.backup();
1505 mHWData->mCPUCount = aCPUCount;
1506
1507 return S_OK;
1508}
1509
1510HRESULT Machine::getCPUExecutionCap(ULONG *aCPUExecutionCap)
1511{
1512 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1513
1514 *aCPUExecutionCap = mHWData->mCpuExecutionCap;
1515
1516 return S_OK;
1517}
1518
1519HRESULT Machine::setCPUExecutionCap(ULONG aCPUExecutionCap)
1520{
1521 HRESULT rc = S_OK;
1522
1523 /* check throttle limits */
1524 if ( aCPUExecutionCap < 1
1525 || aCPUExecutionCap > 100
1526 )
1527 return setError(E_INVALIDARG,
1528 tr("Invalid CPU execution cap value: %lu (must be in range [%lu, %lu])"),
1529 aCPUExecutionCap, 1, 100);
1530
1531 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1532
1533 alock.release();
1534 rc = i_onCPUExecutionCapChange(aCPUExecutionCap);
1535 alock.acquire();
1536 if (FAILED(rc)) return rc;
1537
1538 i_setModified(IsModified_MachineData);
1539 mHWData.backup();
1540 mHWData->mCpuExecutionCap = aCPUExecutionCap;
1541
1542 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1543 if (Global::IsOnline(mData->mMachineState))
1544 i_saveSettings(NULL);
1545
1546 return S_OK;
1547}
1548
1549HRESULT Machine::getCPUHotPlugEnabled(BOOL *aCPUHotPlugEnabled)
1550{
1551 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1552
1553 *aCPUHotPlugEnabled = mHWData->mCPUHotPlugEnabled;
1554
1555 return S_OK;
1556}
1557
1558HRESULT Machine::setCPUHotPlugEnabled(BOOL aCPUHotPlugEnabled)
1559{
1560 HRESULT rc = S_OK;
1561
1562 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1563
1564 rc = i_checkStateDependency(MutableStateDep);
1565 if (FAILED(rc)) return rc;
1566
1567 if (mHWData->mCPUHotPlugEnabled != aCPUHotPlugEnabled)
1568 {
1569 if (aCPUHotPlugEnabled)
1570 {
1571 i_setModified(IsModified_MachineData);
1572 mHWData.backup();
1573
1574 /* Add the amount of CPUs currently attached */
1575 for (unsigned i = 0; i < mHWData->mCPUCount; ++i)
1576 mHWData->mCPUAttached[i] = true;
1577 }
1578 else
1579 {
1580 /*
1581 * We can disable hotplug only if the amount of maximum CPUs is equal
1582 * to the amount of attached CPUs
1583 */
1584 unsigned cCpusAttached = 0;
1585 unsigned iHighestId = 0;
1586
1587 for (unsigned i = 0; i < SchemaDefs::MaxCPUCount; ++i)
1588 {
1589 if (mHWData->mCPUAttached[i])
1590 {
1591 cCpusAttached++;
1592 iHighestId = i;
1593 }
1594 }
1595
1596 if ( (cCpusAttached != mHWData->mCPUCount)
1597 || (iHighestId >= mHWData->mCPUCount))
1598 return setError(E_INVALIDARG,
1599 tr("CPU hotplugging can't be disabled because the maximum number of CPUs is not equal to the amount of CPUs attached"));
1600
1601 i_setModified(IsModified_MachineData);
1602 mHWData.backup();
1603 }
1604 }
1605
1606 mHWData->mCPUHotPlugEnabled = aCPUHotPlugEnabled;
1607
1608 return rc;
1609}
1610
1611HRESULT Machine::getCPUIDPortabilityLevel(ULONG *aCPUIDPortabilityLevel)
1612{
1613 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1614
1615 *aCPUIDPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
1616
1617 return S_OK;
1618}
1619
1620HRESULT Machine::setCPUIDPortabilityLevel(ULONG aCPUIDPortabilityLevel)
1621{
1622 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1623
1624 HRESULT hrc = i_checkStateDependency(MutableStateDep);
1625 if (SUCCEEDED(hrc))
1626 {
1627 i_setModified(IsModified_MachineData);
1628 mHWData.backup();
1629 mHWData->mCpuIdPortabilityLevel = aCPUIDPortabilityLevel;
1630 }
1631 return hrc;
1632}
1633
1634HRESULT Machine::getCPUProfile(com::Utf8Str &aCPUProfile)
1635{
1636 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1637 aCPUProfile = mHWData->mCpuProfile;
1638 return S_OK;
1639}
1640
1641HRESULT Machine::setCPUProfile(const com::Utf8Str &aCPUProfile)
1642{
1643 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1644 HRESULT hrc = i_checkStateDependency(MutableStateDep);
1645 if (SUCCEEDED(hrc))
1646 {
1647 i_setModified(IsModified_MachineData);
1648 mHWData.backup();
1649 /* Empty equals 'host'. */
1650 if (aCPUProfile.isNotEmpty())
1651 mHWData->mCpuProfile = aCPUProfile;
1652 else
1653 mHWData->mCpuProfile = "host";
1654 }
1655 return hrc;
1656}
1657
1658HRESULT Machine::getEmulatedUSBCardReaderEnabled(BOOL *aEmulatedUSBCardReaderEnabled)
1659{
1660#ifdef VBOX_WITH_USB_CARDREADER
1661 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1662
1663 *aEmulatedUSBCardReaderEnabled = mHWData->mEmulatedUSBCardReaderEnabled;
1664
1665 return S_OK;
1666#else
1667 NOREF(aEmulatedUSBCardReaderEnabled);
1668 return E_NOTIMPL;
1669#endif
1670}
1671
1672HRESULT Machine::setEmulatedUSBCardReaderEnabled(BOOL aEmulatedUSBCardReaderEnabled)
1673{
1674#ifdef VBOX_WITH_USB_CARDREADER
1675 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1676
1677 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
1678 if (FAILED(rc)) return rc;
1679
1680 i_setModified(IsModified_MachineData);
1681 mHWData.backup();
1682 mHWData->mEmulatedUSBCardReaderEnabled = aEmulatedUSBCardReaderEnabled;
1683
1684 return S_OK;
1685#else
1686 NOREF(aEmulatedUSBCardReaderEnabled);
1687 return E_NOTIMPL;
1688#endif
1689}
1690
1691HRESULT Machine::getHPETEnabled(BOOL *aHPETEnabled)
1692{
1693 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1694
1695 *aHPETEnabled = mHWData->mHPETEnabled;
1696
1697 return S_OK;
1698}
1699
1700HRESULT Machine::setHPETEnabled(BOOL aHPETEnabled)
1701{
1702 HRESULT rc = S_OK;
1703
1704 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1705
1706 rc = i_checkStateDependency(MutableStateDep);
1707 if (FAILED(rc)) return rc;
1708
1709 i_setModified(IsModified_MachineData);
1710 mHWData.backup();
1711
1712 mHWData->mHPETEnabled = aHPETEnabled;
1713
1714 return rc;
1715}
1716
1717HRESULT Machine::getVideoCaptureEnabled(BOOL *aVideoCaptureEnabled)
1718{
1719 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1720
1721 *aVideoCaptureEnabled = mHWData->mVideoCaptureEnabled;
1722 return S_OK;
1723}
1724
1725HRESULT Machine::setVideoCaptureEnabled(BOOL aVideoCaptureEnabled)
1726{
1727 HRESULT rc = S_OK;
1728
1729 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1730
1731 i_setModified(IsModified_MachineData);
1732 mHWData.backup();
1733 mHWData->mVideoCaptureEnabled = aVideoCaptureEnabled;
1734
1735 alock.release();
1736 rc = i_onVideoCaptureChange();
1737 alock.acquire();
1738 if (FAILED(rc))
1739 {
1740 /*
1741 * Normally we would do the actual change _after_ i_onVideoCaptureChange() succeeded.
1742 * We cannot do this because that function uses Machine::GetVideoCaptureEnabled to
1743 * determine if it should start or stop capturing. Therefore we need to manually
1744 * undo change.
1745 */
1746 mHWData->mVideoCaptureEnabled = mHWData.backedUpData()->mVideoCaptureEnabled;
1747 return rc;
1748 }
1749
1750 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1751 if (Global::IsOnline(mData->mMachineState))
1752 i_saveSettings(NULL);
1753
1754 return rc;
1755}
1756
1757HRESULT Machine::getVideoCaptureScreens(std::vector<BOOL> &aVideoCaptureScreens)
1758{
1759 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1760 aVideoCaptureScreens.resize(mHWData->mMonitorCount);
1761 for (unsigned i = 0; i < mHWData->mMonitorCount; ++i)
1762 aVideoCaptureScreens[i] = mHWData->maVideoCaptureScreens[i];
1763 return S_OK;
1764}
1765
1766HRESULT Machine::setVideoCaptureScreens(const std::vector<BOOL> &aVideoCaptureScreens)
1767{
1768 AssertReturn(aVideoCaptureScreens.size() <= RT_ELEMENTS(mHWData->maVideoCaptureScreens), E_INVALIDARG);
1769 bool fChanged = false;
1770
1771 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1772
1773 for (unsigned i = 0; i < aVideoCaptureScreens.size(); ++i)
1774 {
1775 if (mHWData->maVideoCaptureScreens[i] != RT_BOOL(aVideoCaptureScreens[i]))
1776 {
1777 mHWData->maVideoCaptureScreens[i] = RT_BOOL(aVideoCaptureScreens[i]);
1778 fChanged = true;
1779 }
1780 }
1781 if (fChanged)
1782 {
1783 alock.release();
1784 HRESULT rc = i_onVideoCaptureChange();
1785 alock.acquire();
1786 if (FAILED(rc)) return rc;
1787 i_setModified(IsModified_MachineData);
1788
1789 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1790 if (Global::IsOnline(mData->mMachineState))
1791 i_saveSettings(NULL);
1792 }
1793
1794 return S_OK;
1795}
1796
1797HRESULT Machine::getVideoCaptureFile(com::Utf8Str &aVideoCaptureFile)
1798{
1799 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1800 if (mHWData->mVideoCaptureFile.isEmpty())
1801 i_getDefaultVideoCaptureFile(aVideoCaptureFile);
1802 else
1803 aVideoCaptureFile = mHWData->mVideoCaptureFile;
1804 return S_OK;
1805}
1806
1807HRESULT Machine::setVideoCaptureFile(const com::Utf8Str &aVideoCaptureFile)
1808{
1809 Utf8Str strFile(aVideoCaptureFile);
1810 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1811
1812 if ( Global::IsOnline(mData->mMachineState)
1813 && mHWData->mVideoCaptureEnabled)
1814 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1815
1816 if (!RTPathStartsWithRoot(strFile.c_str()))
1817 return setError(E_INVALIDARG, tr("Video capture file name '%s' is not absolute"), strFile.c_str());
1818
1819 if (!strFile.isEmpty())
1820 {
1821 Utf8Str defaultFile;
1822 i_getDefaultVideoCaptureFile(defaultFile);
1823 if (!RTPathCompare(strFile.c_str(), defaultFile.c_str()))
1824 strFile.setNull();
1825 }
1826
1827 i_setModified(IsModified_MachineData);
1828 mHWData.backup();
1829 mHWData->mVideoCaptureFile = strFile;
1830
1831 return S_OK;
1832}
1833
1834HRESULT Machine::getVideoCaptureWidth(ULONG *aVideoCaptureWidth)
1835{
1836 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1837 *aVideoCaptureWidth = mHWData->mVideoCaptureWidth;
1838 return S_OK;
1839}
1840
1841HRESULT Machine::setVideoCaptureWidth(ULONG aVideoCaptureWidth)
1842{
1843 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1844
1845 if ( Global::IsOnline(mData->mMachineState)
1846 && mHWData->mVideoCaptureEnabled)
1847 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1848
1849 i_setModified(IsModified_MachineData);
1850 mHWData.backup();
1851 mHWData->mVideoCaptureWidth = aVideoCaptureWidth;
1852
1853 return S_OK;
1854}
1855
1856HRESULT Machine::getVideoCaptureHeight(ULONG *aVideoCaptureHeight)
1857{
1858 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1859 *aVideoCaptureHeight = mHWData->mVideoCaptureHeight;
1860 return S_OK;
1861}
1862
1863HRESULT Machine::setVideoCaptureHeight(ULONG aVideoCaptureHeight)
1864{
1865 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1866
1867 if ( Global::IsOnline(mData->mMachineState)
1868 && mHWData->mVideoCaptureEnabled)
1869 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1870
1871 i_setModified(IsModified_MachineData);
1872 mHWData.backup();
1873 mHWData->mVideoCaptureHeight = aVideoCaptureHeight;
1874
1875 return S_OK;
1876}
1877
1878HRESULT Machine::getVideoCaptureRate(ULONG *aVideoCaptureRate)
1879{
1880 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1881 *aVideoCaptureRate = mHWData->mVideoCaptureRate;
1882 return S_OK;
1883}
1884
1885HRESULT Machine::setVideoCaptureRate(ULONG aVideoCaptureRate)
1886{
1887 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1888
1889 if ( Global::IsOnline(mData->mMachineState)
1890 && mHWData->mVideoCaptureEnabled)
1891 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1892
1893 i_setModified(IsModified_MachineData);
1894 mHWData.backup();
1895 mHWData->mVideoCaptureRate = aVideoCaptureRate;
1896
1897 return S_OK;
1898}
1899
1900HRESULT Machine::getVideoCaptureFPS(ULONG *aVideoCaptureFPS)
1901{
1902 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1903 *aVideoCaptureFPS = mHWData->mVideoCaptureFPS;
1904 return S_OK;
1905}
1906
1907HRESULT Machine::setVideoCaptureFPS(ULONG aVideoCaptureFPS)
1908{
1909 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1910
1911 if ( Global::IsOnline(mData->mMachineState)
1912 && mHWData->mVideoCaptureEnabled)
1913 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1914
1915 i_setModified(IsModified_MachineData);
1916 mHWData.backup();
1917 mHWData->mVideoCaptureFPS = aVideoCaptureFPS;
1918
1919 return S_OK;
1920}
1921
1922HRESULT Machine::getVideoCaptureMaxTime(ULONG *aVideoCaptureMaxTime)
1923{
1924 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1925 *aVideoCaptureMaxTime = mHWData->mVideoCaptureMaxTime;
1926 return S_OK;
1927}
1928
1929HRESULT Machine::setVideoCaptureMaxTime(ULONG aVideoCaptureMaxTime)
1930{
1931 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1932
1933 if ( Global::IsOnline(mData->mMachineState)
1934 && mHWData->mVideoCaptureEnabled)
1935 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1936
1937 i_setModified(IsModified_MachineData);
1938 mHWData.backup();
1939 mHWData->mVideoCaptureMaxTime = aVideoCaptureMaxTime;
1940
1941 return S_OK;
1942}
1943
1944HRESULT Machine::getVideoCaptureMaxFileSize(ULONG *aVideoCaptureMaxFileSize)
1945{
1946 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1947 *aVideoCaptureMaxFileSize = mHWData->mVideoCaptureMaxFileSize;
1948 return S_OK;
1949}
1950
1951HRESULT Machine::setVideoCaptureMaxFileSize(ULONG aVideoCaptureMaxFileSize)
1952{
1953 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1954
1955 if ( Global::IsOnline(mData->mMachineState)
1956 && mHWData->mVideoCaptureEnabled)
1957 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1958
1959 i_setModified(IsModified_MachineData);
1960 mHWData.backup();
1961 mHWData->mVideoCaptureMaxFileSize = aVideoCaptureMaxFileSize;
1962
1963 return S_OK;
1964}
1965
1966HRESULT Machine::getVideoCaptureOptions(com::Utf8Str &aVideoCaptureOptions)
1967{
1968 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1969
1970 aVideoCaptureOptions = mHWData->mVideoCaptureOptions;
1971 return S_OK;
1972}
1973
1974HRESULT Machine::setVideoCaptureOptions(const com::Utf8Str &aVideoCaptureOptions)
1975{
1976 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1977
1978 if ( Global::IsOnline(mData->mMachineState)
1979 && mHWData->mVideoCaptureEnabled)
1980 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1981
1982 i_setModified(IsModified_MachineData);
1983 mHWData.backup();
1984 mHWData->mVideoCaptureOptions = aVideoCaptureOptions;
1985
1986 return S_OK;
1987}
1988
1989HRESULT Machine::getGraphicsControllerType(GraphicsControllerType_T *aGraphicsControllerType)
1990{
1991 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1992
1993 *aGraphicsControllerType = mHWData->mGraphicsControllerType;
1994
1995 return S_OK;
1996}
1997
1998HRESULT Machine::setGraphicsControllerType(GraphicsControllerType_T aGraphicsControllerType)
1999{
2000 switch (aGraphicsControllerType)
2001 {
2002 case GraphicsControllerType_Null:
2003 case GraphicsControllerType_VBoxVGA:
2004#ifdef VBOX_WITH_VMSVGA
2005 case GraphicsControllerType_VMSVGA:
2006#endif
2007 break;
2008 default:
2009 return setError(E_INVALIDARG, tr("The graphics controller type (%d) is invalid"), aGraphicsControllerType);
2010 }
2011
2012 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2013
2014 HRESULT rc = i_checkStateDependency(MutableStateDep);
2015 if (FAILED(rc)) return rc;
2016
2017 i_setModified(IsModified_MachineData);
2018 mHWData.backup();
2019 mHWData->mGraphicsControllerType = aGraphicsControllerType;
2020
2021 return S_OK;
2022}
2023
2024HRESULT Machine::getVRAMSize(ULONG *aVRAMSize)
2025{
2026 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2027
2028 *aVRAMSize = mHWData->mVRAMSize;
2029
2030 return S_OK;
2031}
2032
2033HRESULT Machine::setVRAMSize(ULONG aVRAMSize)
2034{
2035 /* check VRAM limits */
2036 if (aVRAMSize > SchemaDefs::MaxGuestVRAM)
2037 return setError(E_INVALIDARG,
2038 tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
2039 aVRAMSize, SchemaDefs::MinGuestVRAM, SchemaDefs::MaxGuestVRAM);
2040
2041 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2042
2043 HRESULT rc = i_checkStateDependency(MutableStateDep);
2044 if (FAILED(rc)) return rc;
2045
2046 i_setModified(IsModified_MachineData);
2047 mHWData.backup();
2048 mHWData->mVRAMSize = aVRAMSize;
2049
2050 return S_OK;
2051}
2052
2053/** @todo this method should not be public */
2054HRESULT Machine::getMemoryBalloonSize(ULONG *aMemoryBalloonSize)
2055{
2056 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2057
2058 *aMemoryBalloonSize = mHWData->mMemoryBalloonSize;
2059
2060 return S_OK;
2061}
2062
2063/**
2064 * Set the memory balloon size.
2065 *
2066 * This method is also called from IGuest::COMSETTER(MemoryBalloonSize) so
2067 * we have to make sure that we never call IGuest from here.
2068 */
2069HRESULT Machine::setMemoryBalloonSize(ULONG aMemoryBalloonSize)
2070{
2071 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
2072#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
2073 /* check limits */
2074 if (aMemoryBalloonSize >= VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize))
2075 return setError(E_INVALIDARG,
2076 tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
2077 aMemoryBalloonSize, 0, VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize));
2078
2079 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2080
2081 i_setModified(IsModified_MachineData);
2082 mHWData.backup();
2083 mHWData->mMemoryBalloonSize = aMemoryBalloonSize;
2084
2085 return S_OK;
2086#else
2087 NOREF(aMemoryBalloonSize);
2088 return setError(E_NOTIMPL, tr("Memory ballooning is only supported on 64-bit hosts"));
2089#endif
2090}
2091
2092HRESULT Machine::getPageFusionEnabled(BOOL *aPageFusionEnabled)
2093{
2094 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2095
2096 *aPageFusionEnabled = mHWData->mPageFusionEnabled;
2097 return S_OK;
2098}
2099
2100HRESULT Machine::setPageFusionEnabled(BOOL aPageFusionEnabled)
2101{
2102#ifdef VBOX_WITH_PAGE_SHARING
2103 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2104
2105 /** @todo must support changes for running vms and keep this in sync with IGuest. */
2106 i_setModified(IsModified_MachineData);
2107 mHWData.backup();
2108 mHWData->mPageFusionEnabled = aPageFusionEnabled;
2109 return S_OK;
2110#else
2111 NOREF(aPageFusionEnabled);
2112 return setError(E_NOTIMPL, tr("Page fusion is only supported on 64-bit hosts"));
2113#endif
2114}
2115
2116HRESULT Machine::getAccelerate3DEnabled(BOOL *aAccelerate3DEnabled)
2117{
2118 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2119
2120 *aAccelerate3DEnabled = mHWData->mAccelerate3DEnabled;
2121
2122 return S_OK;
2123}
2124
2125HRESULT Machine::setAccelerate3DEnabled(BOOL aAccelerate3DEnabled)
2126{
2127 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2128
2129 HRESULT rc = i_checkStateDependency(MutableStateDep);
2130 if (FAILED(rc)) return rc;
2131
2132 /** @todo check validity! */
2133
2134 i_setModified(IsModified_MachineData);
2135 mHWData.backup();
2136 mHWData->mAccelerate3DEnabled = aAccelerate3DEnabled;
2137
2138 return S_OK;
2139}
2140
2141
2142HRESULT Machine::getAccelerate2DVideoEnabled(BOOL *aAccelerate2DVideoEnabled)
2143{
2144 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2145
2146 *aAccelerate2DVideoEnabled = mHWData->mAccelerate2DVideoEnabled;
2147
2148 return S_OK;
2149}
2150
2151HRESULT Machine::setAccelerate2DVideoEnabled(BOOL aAccelerate2DVideoEnabled)
2152{
2153 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2154
2155 HRESULT rc = i_checkStateDependency(MutableStateDep);
2156 if (FAILED(rc)) return rc;
2157
2158 /** @todo check validity! */
2159 i_setModified(IsModified_MachineData);
2160 mHWData.backup();
2161 mHWData->mAccelerate2DVideoEnabled = aAccelerate2DVideoEnabled;
2162
2163 return S_OK;
2164}
2165
2166HRESULT Machine::getMonitorCount(ULONG *aMonitorCount)
2167{
2168 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2169
2170 *aMonitorCount = mHWData->mMonitorCount;
2171
2172 return S_OK;
2173}
2174
2175HRESULT Machine::setMonitorCount(ULONG aMonitorCount)
2176{
2177 /* make sure monitor count is a sensible number */
2178 if (aMonitorCount < 1 || aMonitorCount > SchemaDefs::MaxGuestMonitors)
2179 return setError(E_INVALIDARG,
2180 tr("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
2181 aMonitorCount, 1, SchemaDefs::MaxGuestMonitors);
2182
2183 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2184
2185 HRESULT rc = i_checkStateDependency(MutableStateDep);
2186 if (FAILED(rc)) return rc;
2187
2188 i_setModified(IsModified_MachineData);
2189 mHWData.backup();
2190 mHWData->mMonitorCount = aMonitorCount;
2191
2192 return S_OK;
2193}
2194
2195HRESULT Machine::getBIOSSettings(ComPtr<IBIOSSettings> &aBIOSSettings)
2196{
2197 /* mBIOSSettings is constant during life time, no need to lock */
2198 aBIOSSettings = mBIOSSettings;
2199
2200 return S_OK;
2201}
2202
2203HRESULT Machine::getCPUProperty(CPUPropertyType_T aProperty, BOOL *aValue)
2204{
2205 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2206
2207 switch (aProperty)
2208 {
2209 case CPUPropertyType_PAE:
2210 *aValue = mHWData->mPAEEnabled;
2211 break;
2212
2213 case CPUPropertyType_LongMode:
2214 if (mHWData->mLongMode == settings::Hardware::LongMode_Enabled)
2215 *aValue = TRUE;
2216 else if (mHWData->mLongMode == settings::Hardware::LongMode_Disabled)
2217 *aValue = FALSE;
2218#if HC_ARCH_BITS == 64
2219 else
2220 *aValue = TRUE;
2221#else
2222 else
2223 {
2224 *aValue = FALSE;
2225
2226 ComObjPtr<GuestOSType> pGuestOSType;
2227 HRESULT hrc2 = mParent->i_findGuestOSType(mUserData->s.strOsType,
2228 pGuestOSType);
2229 if (SUCCEEDED(hrc2))
2230 {
2231 if (pGuestOSType->i_is64Bit())
2232 {
2233 ComObjPtr<Host> pHost = mParent->i_host();
2234 alock.release();
2235
2236 hrc2 = pHost->GetProcessorFeature(ProcessorFeature_LongMode, aValue); AssertComRC(hrc2);
2237 if (FAILED(hrc2))
2238 *aValue = FALSE;
2239 }
2240 }
2241 }
2242#endif
2243 break;
2244
2245 case CPUPropertyType_TripleFaultReset:
2246 *aValue = mHWData->mTripleFaultReset;
2247 break;
2248
2249 case CPUPropertyType_APIC:
2250 *aValue = mHWData->mAPIC;
2251 break;
2252
2253 case CPUPropertyType_X2APIC:
2254 *aValue = mHWData->mX2APIC;
2255 break;
2256
2257 default:
2258 return E_INVALIDARG;
2259 }
2260 return S_OK;
2261}
2262
2263HRESULT Machine::setCPUProperty(CPUPropertyType_T aProperty, BOOL aValue)
2264{
2265 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2266
2267 HRESULT rc = i_checkStateDependency(MutableStateDep);
2268 if (FAILED(rc)) return rc;
2269
2270 switch (aProperty)
2271 {
2272 case CPUPropertyType_PAE:
2273 i_setModified(IsModified_MachineData);
2274 mHWData.backup();
2275 mHWData->mPAEEnabled = !!aValue;
2276 break;
2277
2278 case CPUPropertyType_LongMode:
2279 i_setModified(IsModified_MachineData);
2280 mHWData.backup();
2281 mHWData->mLongMode = !aValue ? settings::Hardware::LongMode_Disabled : settings::Hardware::LongMode_Enabled;
2282 break;
2283
2284 case CPUPropertyType_TripleFaultReset:
2285 i_setModified(IsModified_MachineData);
2286 mHWData.backup();
2287 mHWData->mTripleFaultReset = !!aValue;
2288 break;
2289
2290 case CPUPropertyType_APIC:
2291 if (mHWData->mX2APIC)
2292 aValue = TRUE;
2293 i_setModified(IsModified_MachineData);
2294 mHWData.backup();
2295 mHWData->mAPIC = !!aValue;
2296 break;
2297
2298 case CPUPropertyType_X2APIC:
2299 i_setModified(IsModified_MachineData);
2300 mHWData.backup();
2301 mHWData->mX2APIC = !!aValue;
2302 if (aValue)
2303 mHWData->mAPIC = !!aValue;
2304 break;
2305
2306 default:
2307 return E_INVALIDARG;
2308 }
2309 return S_OK;
2310}
2311
2312HRESULT Machine::getCPUIDLeaf(ULONG aId, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx)
2313{
2314 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2315
2316 switch(aId)
2317 {
2318 case 0x0:
2319 case 0x1:
2320 case 0x2:
2321 case 0x3:
2322 case 0x4:
2323 case 0x5:
2324 case 0x6:
2325 case 0x7:
2326 case 0x8:
2327 case 0x9:
2328 case 0xA:
2329 if (mHWData->mCpuIdStdLeafs[aId].ulId != aId)
2330 return E_INVALIDARG;
2331
2332 *aValEax = mHWData->mCpuIdStdLeafs[aId].ulEax;
2333 *aValEbx = mHWData->mCpuIdStdLeafs[aId].ulEbx;
2334 *aValEcx = mHWData->mCpuIdStdLeafs[aId].ulEcx;
2335 *aValEdx = mHWData->mCpuIdStdLeafs[aId].ulEdx;
2336 break;
2337
2338 case 0x80000000:
2339 case 0x80000001:
2340 case 0x80000002:
2341 case 0x80000003:
2342 case 0x80000004:
2343 case 0x80000005:
2344 case 0x80000006:
2345 case 0x80000007:
2346 case 0x80000008:
2347 case 0x80000009:
2348 case 0x8000000A:
2349 if (mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId != aId)
2350 return E_INVALIDARG;
2351
2352 *aValEax = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax;
2353 *aValEbx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx;
2354 *aValEcx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx;
2355 *aValEdx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx;
2356 break;
2357
2358 default:
2359 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2360 }
2361 return S_OK;
2362}
2363
2364
2365HRESULT Machine::setCPUIDLeaf(ULONG aId, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx)
2366{
2367 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2368
2369 HRESULT rc = i_checkStateDependency(MutableStateDep);
2370 if (FAILED(rc)) return rc;
2371
2372 switch(aId)
2373 {
2374 case 0x0:
2375 case 0x1:
2376 case 0x2:
2377 case 0x3:
2378 case 0x4:
2379 case 0x5:
2380 case 0x6:
2381 case 0x7:
2382 case 0x8:
2383 case 0x9:
2384 case 0xA:
2385 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2386 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2387 i_setModified(IsModified_MachineData);
2388 mHWData.backup();
2389 mHWData->mCpuIdStdLeafs[aId].ulId = aId;
2390 mHWData->mCpuIdStdLeafs[aId].ulEax = aValEax;
2391 mHWData->mCpuIdStdLeafs[aId].ulEbx = aValEbx;
2392 mHWData->mCpuIdStdLeafs[aId].ulEcx = aValEcx;
2393 mHWData->mCpuIdStdLeafs[aId].ulEdx = aValEdx;
2394 break;
2395
2396 case 0x80000000:
2397 case 0x80000001:
2398 case 0x80000002:
2399 case 0x80000003:
2400 case 0x80000004:
2401 case 0x80000005:
2402 case 0x80000006:
2403 case 0x80000007:
2404 case 0x80000008:
2405 case 0x80000009:
2406 case 0x8000000A:
2407 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2408 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2409 i_setModified(IsModified_MachineData);
2410 mHWData.backup();
2411 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = aId;
2412 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax = aValEax;
2413 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx = aValEbx;
2414 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx = aValEcx;
2415 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx = aValEdx;
2416 break;
2417
2418 default:
2419 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2420 }
2421 return S_OK;
2422}
2423
2424HRESULT Machine::removeCPUIDLeaf(ULONG aId)
2425{
2426 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2427
2428 HRESULT rc = i_checkStateDependency(MutableStateDep);
2429 if (FAILED(rc)) return rc;
2430
2431 switch(aId)
2432 {
2433 case 0x0:
2434 case 0x1:
2435 case 0x2:
2436 case 0x3:
2437 case 0x4:
2438 case 0x5:
2439 case 0x6:
2440 case 0x7:
2441 case 0x8:
2442 case 0x9:
2443 case 0xA:
2444 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2445 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2446 i_setModified(IsModified_MachineData);
2447 mHWData.backup();
2448 /* Invalidate leaf. */
2449 mHWData->mCpuIdStdLeafs[aId].ulId = UINT32_MAX;
2450 break;
2451
2452 case 0x80000000:
2453 case 0x80000001:
2454 case 0x80000002:
2455 case 0x80000003:
2456 case 0x80000004:
2457 case 0x80000005:
2458 case 0x80000006:
2459 case 0x80000007:
2460 case 0x80000008:
2461 case 0x80000009:
2462 case 0x8000000A:
2463 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2464 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2465 i_setModified(IsModified_MachineData);
2466 mHWData.backup();
2467 /* Invalidate leaf. */
2468 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = UINT32_MAX;
2469 break;
2470
2471 default:
2472 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2473 }
2474 return S_OK;
2475}
2476
2477HRESULT Machine::removeAllCPUIDLeaves()
2478{
2479 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2480
2481 HRESULT rc = i_checkStateDependency(MutableStateDep);
2482 if (FAILED(rc)) return rc;
2483
2484 i_setModified(IsModified_MachineData);
2485 mHWData.backup();
2486
2487 /* Invalidate all standard leafs. */
2488 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++i)
2489 mHWData->mCpuIdStdLeafs[i].ulId = UINT32_MAX;
2490
2491 /* Invalidate all extended leafs. */
2492 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++i)
2493 mHWData->mCpuIdExtLeafs[i].ulId = UINT32_MAX;
2494
2495 return S_OK;
2496}
2497HRESULT Machine::getHWVirtExProperty(HWVirtExPropertyType_T aProperty, BOOL *aValue)
2498{
2499 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2500
2501 switch(aProperty)
2502 {
2503 case HWVirtExPropertyType_Enabled:
2504 *aValue = mHWData->mHWVirtExEnabled;
2505 break;
2506
2507 case HWVirtExPropertyType_VPID:
2508 *aValue = mHWData->mHWVirtExVPIDEnabled;
2509 break;
2510
2511 case HWVirtExPropertyType_NestedPaging:
2512 *aValue = mHWData->mHWVirtExNestedPagingEnabled;
2513 break;
2514
2515 case HWVirtExPropertyType_UnrestrictedExecution:
2516 *aValue = mHWData->mHWVirtExUXEnabled;
2517 break;
2518
2519 case HWVirtExPropertyType_LargePages:
2520 *aValue = mHWData->mHWVirtExLargePagesEnabled;
2521#if defined(DEBUG_bird) && defined(RT_OS_LINUX) /* This feature is deadly here */
2522 *aValue = FALSE;
2523#endif
2524 break;
2525
2526 case HWVirtExPropertyType_Force:
2527 *aValue = mHWData->mHWVirtExForceEnabled;
2528 break;
2529
2530 default:
2531 return E_INVALIDARG;
2532 }
2533 return S_OK;
2534}
2535
2536HRESULT Machine::setHWVirtExProperty(HWVirtExPropertyType_T aProperty, BOOL aValue)
2537{
2538 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2539
2540 HRESULT rc = i_checkStateDependency(MutableStateDep);
2541 if (FAILED(rc)) return rc;
2542
2543 switch(aProperty)
2544 {
2545 case HWVirtExPropertyType_Enabled:
2546 i_setModified(IsModified_MachineData);
2547 mHWData.backup();
2548 mHWData->mHWVirtExEnabled = !!aValue;
2549 break;
2550
2551 case HWVirtExPropertyType_VPID:
2552 i_setModified(IsModified_MachineData);
2553 mHWData.backup();
2554 mHWData->mHWVirtExVPIDEnabled = !!aValue;
2555 break;
2556
2557 case HWVirtExPropertyType_NestedPaging:
2558 i_setModified(IsModified_MachineData);
2559 mHWData.backup();
2560 mHWData->mHWVirtExNestedPagingEnabled = !!aValue;
2561 break;
2562
2563 case HWVirtExPropertyType_UnrestrictedExecution:
2564 i_setModified(IsModified_MachineData);
2565 mHWData.backup();
2566 mHWData->mHWVirtExUXEnabled = !!aValue;
2567 break;
2568
2569 case HWVirtExPropertyType_LargePages:
2570 i_setModified(IsModified_MachineData);
2571 mHWData.backup();
2572 mHWData->mHWVirtExLargePagesEnabled = !!aValue;
2573 break;
2574
2575 case HWVirtExPropertyType_Force:
2576 i_setModified(IsModified_MachineData);
2577 mHWData.backup();
2578 mHWData->mHWVirtExForceEnabled = !!aValue;
2579 break;
2580
2581 default:
2582 return E_INVALIDARG;
2583 }
2584
2585 return S_OK;
2586}
2587
2588HRESULT Machine::getSnapshotFolder(com::Utf8Str &aSnapshotFolder)
2589{
2590 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2591
2592 i_calculateFullPath(mUserData->s.strSnapshotFolder, aSnapshotFolder);
2593
2594 return S_OK;
2595}
2596
2597HRESULT Machine::setSnapshotFolder(const com::Utf8Str &aSnapshotFolder)
2598{
2599 /** @todo (r=dmik):
2600 * 1. Allow to change the name of the snapshot folder containing snapshots
2601 * 2. Rename the folder on disk instead of just changing the property
2602 * value (to be smart and not to leave garbage). Note that it cannot be
2603 * done here because the change may be rolled back. Thus, the right
2604 * place is #saveSettings().
2605 */
2606
2607 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2608
2609 HRESULT rc = i_checkStateDependency(MutableStateDep);
2610 if (FAILED(rc)) return rc;
2611
2612 if (!mData->mCurrentSnapshot.isNull())
2613 return setError(E_FAIL,
2614 tr("The snapshot folder of a machine with snapshots cannot be changed (please delete all snapshots first)"));
2615
2616 Utf8Str strSnapshotFolder(aSnapshotFolder); // keep original
2617
2618 if (strSnapshotFolder.isEmpty())
2619 strSnapshotFolder = "Snapshots";
2620 int vrc = i_calculateFullPath(strSnapshotFolder,
2621 strSnapshotFolder);
2622 if (RT_FAILURE(vrc))
2623 return setError(E_FAIL,
2624 tr("Invalid snapshot folder '%s' (%Rrc)"),
2625 strSnapshotFolder.c_str(), vrc);
2626
2627 i_setModified(IsModified_MachineData);
2628 mUserData.backup();
2629
2630 i_copyPathRelativeToMachine(strSnapshotFolder, mUserData->s.strSnapshotFolder);
2631
2632 return S_OK;
2633}
2634
2635HRESULT Machine::getMediumAttachments(std::vector<ComPtr<IMediumAttachment> > &aMediumAttachments)
2636{
2637 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2638
2639 aMediumAttachments.resize(mMediumAttachments->size());
2640 size_t i = 0;
2641 for (MediumAttachmentList::const_iterator
2642 it = mMediumAttachments->begin();
2643 it != mMediumAttachments->end();
2644 ++it, ++i)
2645 aMediumAttachments[i] = *it;
2646
2647 return S_OK;
2648}
2649
2650HRESULT Machine::getVRDEServer(ComPtr<IVRDEServer> &aVRDEServer)
2651{
2652 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2653
2654 Assert(!!mVRDEServer);
2655
2656 aVRDEServer = mVRDEServer;
2657
2658 return S_OK;
2659}
2660
2661HRESULT Machine::getAudioAdapter(ComPtr<IAudioAdapter> &aAudioAdapter)
2662{
2663 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2664
2665 aAudioAdapter = mAudioAdapter;
2666
2667 return S_OK;
2668}
2669
2670HRESULT Machine::getUSBControllers(std::vector<ComPtr<IUSBController> > &aUSBControllers)
2671{
2672#ifdef VBOX_WITH_VUSB
2673 clearError();
2674 MultiResult rc(S_OK);
2675
2676# ifdef VBOX_WITH_USB
2677 rc = mParent->i_host()->i_checkUSBProxyService();
2678 if (FAILED(rc)) return rc;
2679# endif
2680
2681 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2682
2683 aUSBControllers.resize(mUSBControllers->size());
2684 size_t i = 0;
2685 for (USBControllerList::const_iterator
2686 it = mUSBControllers->begin();
2687 it != mUSBControllers->end();
2688 ++it, ++i)
2689 aUSBControllers[i] = *it;
2690
2691 return S_OK;
2692#else
2693 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2694 * extended error info to indicate that USB is simply not available
2695 * (w/o treating it as a failure), for example, as in OSE */
2696 NOREF(aUSBControllers);
2697 ReturnComNotImplemented();
2698#endif /* VBOX_WITH_VUSB */
2699}
2700
2701HRESULT Machine::getUSBDeviceFilters(ComPtr<IUSBDeviceFilters> &aUSBDeviceFilters)
2702{
2703#ifdef VBOX_WITH_VUSB
2704 clearError();
2705 MultiResult rc(S_OK);
2706
2707# ifdef VBOX_WITH_USB
2708 rc = mParent->i_host()->i_checkUSBProxyService();
2709 if (FAILED(rc)) return rc;
2710# endif
2711
2712 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2713
2714 aUSBDeviceFilters = mUSBDeviceFilters;
2715 return rc;
2716#else
2717 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2718 * extended error info to indicate that USB is simply not available
2719 * (w/o treating it as a failure), for example, as in OSE */
2720 NOREF(aUSBDeviceFilters);
2721 ReturnComNotImplemented();
2722#endif /* VBOX_WITH_VUSB */
2723}
2724
2725HRESULT Machine::getSettingsFilePath(com::Utf8Str &aSettingsFilePath)
2726{
2727 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2728
2729 aSettingsFilePath = mData->m_strConfigFileFull;
2730
2731 return S_OK;
2732}
2733
2734HRESULT Machine::getSettingsAuxFilePath(com::Utf8Str &aSettingsFilePath)
2735{
2736 RT_NOREF(aSettingsFilePath);
2737 ReturnComNotImplemented();
2738}
2739
2740HRESULT Machine::getSettingsModified(BOOL *aSettingsModified)
2741{
2742 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2743
2744 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2745 if (FAILED(rc)) return rc;
2746
2747 if (!mData->pMachineConfigFile->fileExists())
2748 // this is a new machine, and no config file exists yet:
2749 *aSettingsModified = TRUE;
2750 else
2751 *aSettingsModified = (mData->flModifications != 0);
2752
2753 return S_OK;
2754}
2755
2756HRESULT Machine::getSessionState(SessionState_T *aSessionState)
2757{
2758 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2759
2760 *aSessionState = mData->mSession.mState;
2761
2762 return S_OK;
2763}
2764
2765HRESULT Machine::getSessionName(com::Utf8Str &aSessionName)
2766{
2767 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2768
2769 aSessionName = mData->mSession.mName;
2770
2771 return S_OK;
2772}
2773
2774HRESULT Machine::getSessionPID(ULONG *aSessionPID)
2775{
2776 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2777
2778 *aSessionPID = mData->mSession.mPID;
2779
2780 return S_OK;
2781}
2782
2783HRESULT Machine::getState(MachineState_T *aState)
2784{
2785 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2786
2787 *aState = mData->mMachineState;
2788 Assert(mData->mMachineState != MachineState_Null);
2789
2790 return S_OK;
2791}
2792
2793HRESULT Machine::getLastStateChange(LONG64 *aLastStateChange)
2794{
2795 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2796
2797 *aLastStateChange = RTTimeSpecGetMilli(&mData->mLastStateChange);
2798
2799 return S_OK;
2800}
2801
2802HRESULT Machine::getStateFilePath(com::Utf8Str &aStateFilePath)
2803{
2804 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2805
2806 aStateFilePath = mSSData->strStateFilePath;
2807
2808 return S_OK;
2809}
2810
2811HRESULT Machine::getLogFolder(com::Utf8Str &aLogFolder)
2812{
2813 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2814
2815 i_getLogFolder(aLogFolder);
2816
2817 return S_OK;
2818}
2819
2820HRESULT Machine::getCurrentSnapshot(ComPtr<ISnapshot> &aCurrentSnapshot)
2821{
2822 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2823
2824 aCurrentSnapshot = mData->mCurrentSnapshot;
2825
2826 return S_OK;
2827}
2828
2829HRESULT Machine::getSnapshotCount(ULONG *aSnapshotCount)
2830{
2831 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2832
2833 *aSnapshotCount = mData->mFirstSnapshot.isNull()
2834 ? 0
2835 : mData->mFirstSnapshot->i_getAllChildrenCount() + 1;
2836
2837 return S_OK;
2838}
2839
2840HRESULT Machine::getCurrentStateModified(BOOL *aCurrentStateModified)
2841{
2842 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2843
2844 /* Note: for machines with no snapshots, we always return FALSE
2845 * (mData->mCurrentStateModified will be TRUE in this case, for historical
2846 * reasons :) */
2847
2848 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
2849 ? FALSE
2850 : mData->mCurrentStateModified;
2851
2852 return S_OK;
2853}
2854
2855HRESULT Machine::getSharedFolders(std::vector<ComPtr<ISharedFolder> > &aSharedFolders)
2856{
2857 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2858
2859 aSharedFolders.resize(mHWData->mSharedFolders.size());
2860 size_t i = 0;
2861 for (std::list<ComObjPtr<SharedFolder> >::const_iterator
2862 it = mHWData->mSharedFolders.begin();
2863 it != mHWData->mSharedFolders.end();
2864 ++it, ++i)
2865 aSharedFolders[i] = *it;
2866
2867 return S_OK;
2868}
2869
2870HRESULT Machine::getClipboardMode(ClipboardMode_T *aClipboardMode)
2871{
2872 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2873
2874 *aClipboardMode = mHWData->mClipboardMode;
2875
2876 return S_OK;
2877}
2878
2879HRESULT Machine::setClipboardMode(ClipboardMode_T aClipboardMode)
2880{
2881 HRESULT rc = S_OK;
2882
2883 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2884
2885 alock.release();
2886 rc = i_onClipboardModeChange(aClipboardMode);
2887 alock.acquire();
2888 if (FAILED(rc)) return rc;
2889
2890 i_setModified(IsModified_MachineData);
2891 mHWData.backup();
2892 mHWData->mClipboardMode = aClipboardMode;
2893
2894 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
2895 if (Global::IsOnline(mData->mMachineState))
2896 i_saveSettings(NULL);
2897
2898 return S_OK;
2899}
2900
2901HRESULT Machine::getDnDMode(DnDMode_T *aDnDMode)
2902{
2903 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2904
2905 *aDnDMode = mHWData->mDnDMode;
2906
2907 return S_OK;
2908}
2909
2910HRESULT Machine::setDnDMode(DnDMode_T aDnDMode)
2911{
2912 HRESULT rc = S_OK;
2913
2914 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2915
2916 alock.release();
2917 rc = i_onDnDModeChange(aDnDMode);
2918
2919 alock.acquire();
2920 if (FAILED(rc)) return rc;
2921
2922 i_setModified(IsModified_MachineData);
2923 mHWData.backup();
2924 mHWData->mDnDMode = aDnDMode;
2925
2926 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
2927 if (Global::IsOnline(mData->mMachineState))
2928 i_saveSettings(NULL);
2929
2930 return S_OK;
2931}
2932
2933HRESULT Machine::getStorageControllers(std::vector<ComPtr<IStorageController> > &aStorageControllers)
2934{
2935 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2936
2937 aStorageControllers.resize(mStorageControllers->size());
2938 size_t i = 0;
2939 for (StorageControllerList::const_iterator
2940 it = mStorageControllers->begin();
2941 it != mStorageControllers->end();
2942 ++it, ++i)
2943 aStorageControllers[i] = *it;
2944
2945 return S_OK;
2946}
2947
2948HRESULT Machine::getTeleporterEnabled(BOOL *aEnabled)
2949{
2950 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2951
2952 *aEnabled = mUserData->s.fTeleporterEnabled;
2953
2954 return S_OK;
2955}
2956
2957HRESULT Machine::setTeleporterEnabled(BOOL aTeleporterEnabled)
2958{
2959 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2960
2961 /* Only allow it to be set to true when PoweredOff or Aborted.
2962 (Clearing it is always permitted.) */
2963 if ( aTeleporterEnabled
2964 && mData->mRegistered
2965 && ( !i_isSessionMachine()
2966 || ( mData->mMachineState != MachineState_PoweredOff
2967 && mData->mMachineState != MachineState_Teleported
2968 && mData->mMachineState != MachineState_Aborted
2969 )
2970 )
2971 )
2972 return setError(VBOX_E_INVALID_VM_STATE,
2973 tr("The machine is not powered off (state is %s)"),
2974 Global::stringifyMachineState(mData->mMachineState));
2975
2976 i_setModified(IsModified_MachineData);
2977 mUserData.backup();
2978 mUserData->s.fTeleporterEnabled = !! aTeleporterEnabled;
2979
2980 return S_OK;
2981}
2982
2983HRESULT Machine::getTeleporterPort(ULONG *aTeleporterPort)
2984{
2985 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2986
2987 *aTeleporterPort = (ULONG)mUserData->s.uTeleporterPort;
2988
2989 return S_OK;
2990}
2991
2992HRESULT Machine::setTeleporterPort(ULONG aTeleporterPort)
2993{
2994 if (aTeleporterPort >= _64K)
2995 return setError(E_INVALIDARG, tr("Invalid port number %d"), aTeleporterPort);
2996
2997 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2998
2999 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3000 if (FAILED(rc)) return rc;
3001
3002 i_setModified(IsModified_MachineData);
3003 mUserData.backup();
3004 mUserData->s.uTeleporterPort = (uint32_t)aTeleporterPort;
3005
3006 return S_OK;
3007}
3008
3009HRESULT Machine::getTeleporterAddress(com::Utf8Str &aTeleporterAddress)
3010{
3011 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3012
3013 aTeleporterAddress = mUserData->s.strTeleporterAddress;
3014
3015 return S_OK;
3016}
3017
3018HRESULT Machine::setTeleporterAddress(const com::Utf8Str &aTeleporterAddress)
3019{
3020 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3021
3022 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3023 if (FAILED(rc)) return rc;
3024
3025 i_setModified(IsModified_MachineData);
3026 mUserData.backup();
3027 mUserData->s.strTeleporterAddress = aTeleporterAddress;
3028
3029 return S_OK;
3030}
3031
3032HRESULT Machine::getTeleporterPassword(com::Utf8Str &aTeleporterPassword)
3033{
3034 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3035 aTeleporterPassword = mUserData->s.strTeleporterPassword;
3036
3037 return S_OK;
3038}
3039
3040HRESULT Machine::setTeleporterPassword(const com::Utf8Str &aTeleporterPassword)
3041{
3042 /*
3043 * Hash the password first.
3044 */
3045 com::Utf8Str aT = aTeleporterPassword;
3046
3047 if (!aT.isEmpty())
3048 {
3049 if (VBoxIsPasswordHashed(&aT))
3050 return setError(E_INVALIDARG, tr("Cannot set an already hashed password, only plain text password please"));
3051 VBoxHashPassword(&aT);
3052 }
3053
3054 /*
3055 * Do the update.
3056 */
3057 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3058 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
3059 if (SUCCEEDED(hrc))
3060 {
3061 i_setModified(IsModified_MachineData);
3062 mUserData.backup();
3063 mUserData->s.strTeleporterPassword = aT;
3064 }
3065
3066 return hrc;
3067}
3068
3069HRESULT Machine::getFaultToleranceState(FaultToleranceState_T *aFaultToleranceState)
3070{
3071 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3072
3073 *aFaultToleranceState = mUserData->s.enmFaultToleranceState;
3074 return S_OK;
3075}
3076
3077HRESULT Machine::setFaultToleranceState(FaultToleranceState_T aFaultToleranceState)
3078{
3079 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3080
3081 /** @todo deal with running state change. */
3082 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
3083 if (FAILED(rc)) return rc;
3084
3085 i_setModified(IsModified_MachineData);
3086 mUserData.backup();
3087 mUserData->s.enmFaultToleranceState = aFaultToleranceState;
3088 return S_OK;
3089}
3090
3091HRESULT Machine::getFaultToleranceAddress(com::Utf8Str &aFaultToleranceAddress)
3092{
3093 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3094
3095 aFaultToleranceAddress = mUserData->s.strFaultToleranceAddress;
3096 return S_OK;
3097}
3098
3099HRESULT Machine::setFaultToleranceAddress(const com::Utf8Str &aFaultToleranceAddress)
3100{
3101 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3102
3103 /** @todo deal with running state change. */
3104 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3105 if (FAILED(rc)) return rc;
3106
3107 i_setModified(IsModified_MachineData);
3108 mUserData.backup();
3109 mUserData->s.strFaultToleranceAddress = aFaultToleranceAddress;
3110 return S_OK;
3111}
3112
3113HRESULT Machine::getFaultTolerancePort(ULONG *aFaultTolerancePort)
3114{
3115 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3116
3117 *aFaultTolerancePort = mUserData->s.uFaultTolerancePort;
3118 return S_OK;
3119}
3120
3121HRESULT Machine::setFaultTolerancePort(ULONG aFaultTolerancePort)
3122{
3123 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3124
3125 /** @todo deal with running state change. */
3126 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3127 if (FAILED(rc)) return rc;
3128
3129 i_setModified(IsModified_MachineData);
3130 mUserData.backup();
3131 mUserData->s.uFaultTolerancePort = aFaultTolerancePort;
3132 return S_OK;
3133}
3134
3135HRESULT Machine::getFaultTolerancePassword(com::Utf8Str &aFaultTolerancePassword)
3136{
3137 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3138
3139 aFaultTolerancePassword = mUserData->s.strFaultTolerancePassword;
3140
3141 return S_OK;
3142}
3143
3144HRESULT Machine::setFaultTolerancePassword(const com::Utf8Str &aFaultTolerancePassword)
3145{
3146 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3147
3148 /** @todo deal with running state change. */
3149 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3150 if (FAILED(rc)) return rc;
3151
3152 i_setModified(IsModified_MachineData);
3153 mUserData.backup();
3154 mUserData->s.strFaultTolerancePassword = aFaultTolerancePassword;
3155
3156 return S_OK;
3157}
3158
3159HRESULT Machine::getFaultToleranceSyncInterval(ULONG *aFaultToleranceSyncInterval)
3160{
3161 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3162
3163 *aFaultToleranceSyncInterval = mUserData->s.uFaultToleranceInterval;
3164 return S_OK;
3165}
3166
3167HRESULT Machine::setFaultToleranceSyncInterval(ULONG aFaultToleranceSyncInterval)
3168{
3169 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3170
3171 /** @todo deal with running state change. */
3172 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3173 if (FAILED(rc)) return rc;
3174
3175 i_setModified(IsModified_MachineData);
3176 mUserData.backup();
3177 mUserData->s.uFaultToleranceInterval = aFaultToleranceSyncInterval;
3178 return S_OK;
3179}
3180
3181HRESULT Machine::getRTCUseUTC(BOOL *aRTCUseUTC)
3182{
3183 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3184
3185 *aRTCUseUTC = mUserData->s.fRTCUseUTC;
3186
3187 return S_OK;
3188}
3189
3190HRESULT Machine::setRTCUseUTC(BOOL aRTCUseUTC)
3191{
3192 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3193
3194 /* Only allow it to be set to true when PoweredOff or Aborted.
3195 (Clearing it is always permitted.) */
3196 if ( aRTCUseUTC
3197 && mData->mRegistered
3198 && ( !i_isSessionMachine()
3199 || ( mData->mMachineState != MachineState_PoweredOff
3200 && mData->mMachineState != MachineState_Teleported
3201 && mData->mMachineState != MachineState_Aborted
3202 )
3203 )
3204 )
3205 return setError(VBOX_E_INVALID_VM_STATE,
3206 tr("The machine is not powered off (state is %s)"),
3207 Global::stringifyMachineState(mData->mMachineState));
3208
3209 i_setModified(IsModified_MachineData);
3210 mUserData.backup();
3211 mUserData->s.fRTCUseUTC = !!aRTCUseUTC;
3212
3213 return S_OK;
3214}
3215
3216HRESULT Machine::getIOCacheEnabled(BOOL *aIOCacheEnabled)
3217{
3218 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3219
3220 *aIOCacheEnabled = mHWData->mIOCacheEnabled;
3221
3222 return S_OK;
3223}
3224
3225HRESULT Machine::setIOCacheEnabled(BOOL aIOCacheEnabled)
3226{
3227 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3228
3229 HRESULT rc = i_checkStateDependency(MutableStateDep);
3230 if (FAILED(rc)) return rc;
3231
3232 i_setModified(IsModified_MachineData);
3233 mHWData.backup();
3234 mHWData->mIOCacheEnabled = aIOCacheEnabled;
3235
3236 return S_OK;
3237}
3238
3239HRESULT Machine::getIOCacheSize(ULONG *aIOCacheSize)
3240{
3241 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3242
3243 *aIOCacheSize = mHWData->mIOCacheSize;
3244
3245 return S_OK;
3246}
3247
3248HRESULT Machine::setIOCacheSize(ULONG aIOCacheSize)
3249{
3250 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3251
3252 HRESULT rc = i_checkStateDependency(MutableStateDep);
3253 if (FAILED(rc)) return rc;
3254
3255 i_setModified(IsModified_MachineData);
3256 mHWData.backup();
3257 mHWData->mIOCacheSize = aIOCacheSize;
3258
3259 return S_OK;
3260}
3261
3262
3263/**
3264 * @note Locks objects!
3265 */
3266HRESULT Machine::lockMachine(const ComPtr<ISession> &aSession,
3267 LockType_T aLockType)
3268{
3269 /* check the session state */
3270 SessionState_T state;
3271 HRESULT rc = aSession->COMGETTER(State)(&state);
3272 if (FAILED(rc)) return rc;
3273
3274 if (state != SessionState_Unlocked)
3275 return setError(VBOX_E_INVALID_OBJECT_STATE,
3276 tr("The given session is busy"));
3277
3278 // get the client's IInternalSessionControl interface
3279 ComPtr<IInternalSessionControl> pSessionControl = aSession;
3280 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
3281 E_INVALIDARG);
3282
3283 // session name (only used in some code paths)
3284 Utf8Str strSessionName;
3285
3286 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3287
3288 if (!mData->mRegistered)
3289 return setError(E_UNEXPECTED,
3290 tr("The machine '%s' is not registered"),
3291 mUserData->s.strName.c_str());
3292
3293 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3294
3295 SessionState_T oldState = mData->mSession.mState;
3296 /* Hack: in case the session is closing and there is a progress object
3297 * which allows waiting for the session to be closed, take the opportunity
3298 * and do a limited wait (max. 1 second). This helps a lot when the system
3299 * is busy and thus session closing can take a little while. */
3300 if ( mData->mSession.mState == SessionState_Unlocking
3301 && mData->mSession.mProgress)
3302 {
3303 alock.release();
3304 mData->mSession.mProgress->WaitForCompletion(1000);
3305 alock.acquire();
3306 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3307 }
3308
3309 // try again now
3310 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already
3311 // (i.e. session machine exists)
3312 && (aLockType == LockType_Shared) // caller wants a shared link to the
3313 // existing session that holds the write lock:
3314 )
3315 {
3316 // OK, share the session... we are now dealing with three processes:
3317 // 1) VBoxSVC (where this code runs);
3318 // 2) process C: the caller's client process (who wants a shared session);
3319 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
3320
3321 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
3322 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
3323 ComAssertRet(!pSessionW.isNull(), E_FAIL);
3324 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
3325 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
3326
3327 /*
3328 * Release the lock before calling the client process. It's safe here
3329 * since the only thing to do after we get the lock again is to add
3330 * the remote control to the list (which doesn't directly influence
3331 * anything).
3332 */
3333 alock.release();
3334
3335 // get the console of the session holding the write lock (this is a remote call)
3336 ComPtr<IConsole> pConsoleW;
3337 if (mData->mSession.mLockType == LockType_VM)
3338 {
3339 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
3340 rc = pSessionW->COMGETTER(RemoteConsole)(pConsoleW.asOutParam());
3341 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
3342 if (FAILED(rc))
3343 // the failure may occur w/o any error info (from RPC), so provide one
3344 return setError(VBOX_E_VM_ERROR,
3345 tr("Failed to get a console object from the direct session (%Rhrc)"), rc);
3346 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
3347 }
3348
3349 // share the session machine and W's console with the caller's session
3350 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3351 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
3352 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3353
3354 if (FAILED(rc))
3355 // the failure may occur w/o any error info (from RPC), so provide one
3356 return setError(VBOX_E_VM_ERROR,
3357 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
3358 alock.acquire();
3359
3360 // need to revalidate the state after acquiring the lock again
3361 if (mData->mSession.mState != SessionState_Locked)
3362 {
3363 pSessionControl->Uninitialize();
3364 return setError(VBOX_E_INVALID_SESSION_STATE,
3365 tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
3366 mUserData->s.strName.c_str());
3367 }
3368
3369 // add the caller's session to the list
3370 mData->mSession.mRemoteControls.push_back(pSessionControl);
3371 }
3372 else if ( mData->mSession.mState == SessionState_Locked
3373 || mData->mSession.mState == SessionState_Unlocking
3374 )
3375 {
3376 // sharing not permitted, or machine still unlocking:
3377 return setError(VBOX_E_INVALID_OBJECT_STATE,
3378 tr("The machine '%s' is already locked for a session (or being unlocked)"),
3379 mUserData->s.strName.c_str());
3380 }
3381 else
3382 {
3383 // machine is not locked: then write-lock the machine (create the session machine)
3384
3385 // must not be busy
3386 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
3387
3388 // get the caller's session PID
3389 RTPROCESS pid = NIL_RTPROCESS;
3390 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
3391 pSessionControl->COMGETTER(PID)((ULONG*)&pid);
3392 Assert(pid != NIL_RTPROCESS);
3393
3394 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
3395
3396 if (fLaunchingVMProcess)
3397 {
3398 if (mData->mSession.mPID == NIL_RTPROCESS)
3399 {
3400 // two or more clients racing for a lock, the one which set the
3401 // session state to Spawning will win, the others will get an
3402 // error as we can't decide here if waiting a little would help
3403 // (only for shared locks this would avoid an error)
3404 return setError(VBOX_E_INVALID_OBJECT_STATE,
3405 tr("The machine '%s' already has a lock request pending"),
3406 mUserData->s.strName.c_str());
3407 }
3408
3409 // this machine is awaiting for a spawning session to be opened:
3410 // then the calling process must be the one that got started by
3411 // LaunchVMProcess()
3412
3413 LogFlowThisFunc(("mSession.mPID=%d(0x%x)\n", mData->mSession.mPID, mData->mSession.mPID));
3414 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3415
3416#if defined(VBOX_WITH_HARDENING) && defined(RT_OS_WINDOWS)
3417 /* Hardened windows builds spawns three processes when a VM is
3418 launched, the 3rd one is the one that will end up here. */
3419 RTPROCESS ppid;
3420 int rc = RTProcQueryParent(pid, &ppid);
3421 if (RT_SUCCESS(rc))
3422 rc = RTProcQueryParent(ppid, &ppid);
3423 if ( (RT_SUCCESS(rc) && mData->mSession.mPID == ppid)
3424 || rc == VERR_ACCESS_DENIED)
3425 {
3426 LogFlowThisFunc(("mSession.mPID => %d(%#x) - windows hardening stub\n", mData->mSession.mPID, pid));
3427 mData->mSession.mPID = pid;
3428 }
3429#endif
3430
3431 if (mData->mSession.mPID != pid)
3432 return setError(E_ACCESSDENIED,
3433 tr("An unexpected process (PID=0x%08X) has tried to lock the "
3434 "machine '%s', while only the process started by LaunchVMProcess (PID=0x%08X) is allowed"),
3435 pid, mUserData->s.strName.c_str(), mData->mSession.mPID);
3436 }
3437
3438 // create the mutable SessionMachine from the current machine
3439 ComObjPtr<SessionMachine> sessionMachine;
3440 sessionMachine.createObject();
3441 rc = sessionMachine->init(this);
3442 AssertComRC(rc);
3443
3444 /* NOTE: doing return from this function after this point but
3445 * before the end is forbidden since it may call SessionMachine::uninit()
3446 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3447 * lock while still holding the Machine lock in alock so that a deadlock
3448 * is possible due to the wrong lock order. */
3449
3450 if (SUCCEEDED(rc))
3451 {
3452 /*
3453 * Set the session state to Spawning to protect against subsequent
3454 * attempts to open a session and to unregister the machine after
3455 * we release the lock.
3456 */
3457 SessionState_T origState = mData->mSession.mState;
3458 mData->mSession.mState = SessionState_Spawning;
3459
3460#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
3461 /* Get the client token ID to be passed to the client process */
3462 Utf8Str strTokenId;
3463 sessionMachine->i_getTokenId(strTokenId);
3464 Assert(!strTokenId.isEmpty());
3465#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3466 /* Get the client token to be passed to the client process */
3467 ComPtr<IToken> pToken(sessionMachine->i_getToken());
3468 /* The token is now "owned" by pToken, fix refcount */
3469 if (!pToken.isNull())
3470 pToken->Release();
3471#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3472
3473 /*
3474 * Release the lock before calling the client process -- it will call
3475 * Machine/SessionMachine methods. Releasing the lock here is quite safe
3476 * because the state is Spawning, so that LaunchVMProcess() and
3477 * LockMachine() calls will fail. This method, called before we
3478 * acquire the lock again, will fail because of the wrong PID.
3479 *
3480 * Note that mData->mSession.mRemoteControls accessed outside
3481 * the lock may not be modified when state is Spawning, so it's safe.
3482 */
3483 alock.release();
3484
3485 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3486#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
3487 rc = pSessionControl->AssignMachine(sessionMachine, aLockType, Bstr(strTokenId).raw());
3488#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3489 rc = pSessionControl->AssignMachine(sessionMachine, aLockType, pToken);
3490 /* Now the token is owned by the client process. */
3491 pToken.setNull();
3492#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3493 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3494
3495 /* The failure may occur w/o any error info (from RPC), so provide one */
3496 if (FAILED(rc))
3497 setError(VBOX_E_VM_ERROR,
3498 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
3499
3500 // get session name, either to remember or to compare against
3501 // the already known session name.
3502 {
3503 Bstr bstrSessionName;
3504 HRESULT rc2 = aSession->COMGETTER(Name)(bstrSessionName.asOutParam());
3505 if (SUCCEEDED(rc2))
3506 strSessionName = bstrSessionName;
3507 }
3508
3509 if ( SUCCEEDED(rc)
3510 && fLaunchingVMProcess
3511 )
3512 {
3513 /* complete the remote session initialization */
3514
3515 /* get the console from the direct session */
3516 ComPtr<IConsole> console;
3517 rc = pSessionControl->COMGETTER(RemoteConsole)(console.asOutParam());
3518 ComAssertComRC(rc);
3519
3520 if (SUCCEEDED(rc) && !console)
3521 {
3522 ComAssert(!!console);
3523 rc = E_FAIL;
3524 }
3525
3526 /* assign machine & console to the remote session */
3527 if (SUCCEEDED(rc))
3528 {
3529 /*
3530 * after LaunchVMProcess(), the first and the only
3531 * entry in remoteControls is that remote session
3532 */
3533 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3534 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
3535 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3536
3537 /* The failure may occur w/o any error info (from RPC), so provide one */
3538 if (FAILED(rc))
3539 setError(VBOX_E_VM_ERROR,
3540 tr("Failed to assign the machine to the remote session (%Rhrc)"), rc);
3541 }
3542
3543 if (FAILED(rc))
3544 pSessionControl->Uninitialize();
3545 }
3546
3547 /* acquire the lock again */
3548 alock.acquire();
3549
3550 /* Restore the session state */
3551 mData->mSession.mState = origState;
3552 }
3553
3554 // finalize spawning anyway (this is why we don't return on errors above)
3555 if (fLaunchingVMProcess)
3556 {
3557 Assert(mData->mSession.mName == strSessionName);
3558 /* Note that the progress object is finalized later */
3559 /** @todo Consider checking mData->mSession.mProgress for cancellation
3560 * around here. */
3561
3562 /* We don't reset mSession.mPID here because it is necessary for
3563 * SessionMachine::uninit() to reap the child process later. */
3564
3565 if (FAILED(rc))
3566 {
3567 /* Close the remote session, remove the remote control from the list
3568 * and reset session state to Closed (@note keep the code in sync
3569 * with the relevant part in checkForSpawnFailure()). */
3570
3571 Assert(mData->mSession.mRemoteControls.size() == 1);
3572 if (mData->mSession.mRemoteControls.size() == 1)
3573 {
3574 ErrorInfoKeeper eik;
3575 mData->mSession.mRemoteControls.front()->Uninitialize();
3576 }
3577
3578 mData->mSession.mRemoteControls.clear();
3579 mData->mSession.mState = SessionState_Unlocked;
3580 }
3581 }
3582 else
3583 {
3584 /* memorize PID of the directly opened session */
3585 if (SUCCEEDED(rc))
3586 mData->mSession.mPID = pid;
3587 }
3588
3589 if (SUCCEEDED(rc))
3590 {
3591 mData->mSession.mLockType = aLockType;
3592 /* memorize the direct session control and cache IUnknown for it */
3593 mData->mSession.mDirectControl = pSessionControl;
3594 mData->mSession.mState = SessionState_Locked;
3595 if (!fLaunchingVMProcess)
3596 mData->mSession.mName = strSessionName;
3597 /* associate the SessionMachine with this Machine */
3598 mData->mSession.mMachine = sessionMachine;
3599
3600 /* request an IUnknown pointer early from the remote party for later
3601 * identity checks (it will be internally cached within mDirectControl
3602 * at least on XPCOM) */
3603 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3604 NOREF(unk);
3605 }
3606
3607 /* Release the lock since SessionMachine::uninit() locks VirtualBox which
3608 * would break the lock order */
3609 alock.release();
3610
3611 /* uninitialize the created session machine on failure */
3612 if (FAILED(rc))
3613 sessionMachine->uninit();
3614 }
3615
3616 if (SUCCEEDED(rc))
3617 {
3618 /*
3619 * tell the client watcher thread to update the set of
3620 * machines that have open sessions
3621 */
3622 mParent->i_updateClientWatcher();
3623
3624 if (oldState != SessionState_Locked)
3625 /* fire an event */
3626 mParent->i_onSessionStateChange(i_getId(), SessionState_Locked);
3627 }
3628
3629 return rc;
3630}
3631
3632/**
3633 * @note Locks objects!
3634 */
3635HRESULT Machine::launchVMProcess(const ComPtr<ISession> &aSession,
3636 const com::Utf8Str &aName,
3637 const com::Utf8Str &aEnvironment,
3638 ComPtr<IProgress> &aProgress)
3639{
3640 Utf8Str strFrontend(aName);
3641 /* "emergencystop" doesn't need the session, so skip the checks/interface
3642 * retrieval. This code doesn't quite fit in here, but introducing a
3643 * special API method would be even more effort, and would require explicit
3644 * support by every API client. It's better to hide the feature a bit. */
3645 if (strFrontend != "emergencystop")
3646 CheckComArgNotNull(aSession);
3647
3648 HRESULT rc = S_OK;
3649 if (strFrontend.isEmpty())
3650 {
3651 Bstr bstrFrontend;
3652 rc = COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3653 if (FAILED(rc))
3654 return rc;
3655 strFrontend = bstrFrontend;
3656 if (strFrontend.isEmpty())
3657 {
3658 ComPtr<ISystemProperties> systemProperties;
3659 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
3660 if (FAILED(rc))
3661 return rc;
3662 rc = systemProperties->COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3663 if (FAILED(rc))
3664 return rc;
3665 strFrontend = bstrFrontend;
3666 }
3667 /* paranoia - emergencystop is not a valid default */
3668 if (strFrontend == "emergencystop")
3669 strFrontend = Utf8Str::Empty;
3670 }
3671 /* default frontend: Qt GUI */
3672 if (strFrontend.isEmpty())
3673 strFrontend = "GUI/Qt";
3674
3675 if (strFrontend != "emergencystop")
3676 {
3677 /* check the session state */
3678 SessionState_T state;
3679 rc = aSession->COMGETTER(State)(&state);
3680 if (FAILED(rc))
3681 return rc;
3682
3683 if (state != SessionState_Unlocked)
3684 return setError(VBOX_E_INVALID_OBJECT_STATE,
3685 tr("The given session is busy"));
3686
3687 /* get the IInternalSessionControl interface */
3688 ComPtr<IInternalSessionControl> control(aSession);
3689 ComAssertMsgRet(!control.isNull(),
3690 ("No IInternalSessionControl interface"),
3691 E_INVALIDARG);
3692
3693 /* get the teleporter enable state for the progress object init. */
3694 BOOL fTeleporterEnabled;
3695 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3696 if (FAILED(rc))
3697 return rc;
3698
3699 /* create a progress object */
3700 ComObjPtr<ProgressProxy> progress;
3701 progress.createObject();
3702 rc = progress->init(mParent,
3703 static_cast<IMachine*>(this),
3704 Bstr(tr("Starting VM")).raw(),
3705 TRUE /* aCancelable */,
3706 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3707 BstrFmt(tr("Creating process for virtual machine \"%s\" (%s)"),
3708 mUserData->s.strName.c_str(), strFrontend.c_str()).raw(),
3709 2 /* uFirstOperationWeight */,
3710 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3711
3712 if (SUCCEEDED(rc))
3713 {
3714 rc = i_launchVMProcess(control, strFrontend, aEnvironment, progress);
3715 if (SUCCEEDED(rc))
3716 {
3717 aProgress = progress;
3718
3719 /* signal the client watcher thread */
3720 mParent->i_updateClientWatcher();
3721
3722 /* fire an event */
3723 mParent->i_onSessionStateChange(i_getId(), SessionState_Spawning);
3724 }
3725 }
3726 }
3727 else
3728 {
3729 /* no progress object - either instant success or failure */
3730 aProgress = NULL;
3731
3732 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3733
3734 if (mData->mSession.mState != SessionState_Locked)
3735 return setError(VBOX_E_INVALID_OBJECT_STATE,
3736 tr("The machine '%s' is not locked by a session"),
3737 mUserData->s.strName.c_str());
3738
3739 /* must have a VM process associated - do not kill normal API clients
3740 * with an open session */
3741 if (!Global::IsOnline(mData->mMachineState))
3742 return setError(VBOX_E_INVALID_OBJECT_STATE,
3743 tr("The machine '%s' does not have a VM process"),
3744 mUserData->s.strName.c_str());
3745
3746 /* forcibly terminate the VM process */
3747 if (mData->mSession.mPID != NIL_RTPROCESS)
3748 RTProcTerminate(mData->mSession.mPID);
3749
3750 /* signal the client watcher thread, as most likely the client has
3751 * been terminated */
3752 mParent->i_updateClientWatcher();
3753 }
3754
3755 return rc;
3756}
3757
3758HRESULT Machine::setBootOrder(ULONG aPosition, DeviceType_T aDevice)
3759{
3760 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3761 return setError(E_INVALIDARG,
3762 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3763 aPosition, SchemaDefs::MaxBootPosition);
3764
3765 if (aDevice == DeviceType_USB)
3766 return setError(E_NOTIMPL,
3767 tr("Booting from USB device is currently not supported"));
3768
3769 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3770
3771 HRESULT rc = i_checkStateDependency(MutableStateDep);
3772 if (FAILED(rc)) return rc;
3773
3774 i_setModified(IsModified_MachineData);
3775 mHWData.backup();
3776 mHWData->mBootOrder[aPosition - 1] = aDevice;
3777
3778 return S_OK;
3779}
3780
3781HRESULT Machine::getBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3782{
3783 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3784 return setError(E_INVALIDARG,
3785 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3786 aPosition, SchemaDefs::MaxBootPosition);
3787
3788 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3789
3790 *aDevice = mHWData->mBootOrder[aPosition - 1];
3791
3792 return S_OK;
3793}
3794
3795HRESULT Machine::attachDevice(const com::Utf8Str &aName,
3796 LONG aControllerPort,
3797 LONG aDevice,
3798 DeviceType_T aType,
3799 const ComPtr<IMedium> &aMedium)
3800{
3801 IMedium *aM = aMedium;
3802 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
3803 aName.c_str(), aControllerPort, aDevice, aType, aM));
3804
3805 // request the host lock first, since might be calling Host methods for getting host drives;
3806 // next, protect the media tree all the while we're in here, as well as our member variables
3807 AutoMultiWriteLock2 alock(mParent->i_host(), this COMMA_LOCKVAL_SRC_POS);
3808 AutoWriteLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3809
3810 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
3811 if (FAILED(rc)) return rc;
3812
3813 /// @todo NEWMEDIA implicit machine registration
3814 if (!mData->mRegistered)
3815 return setError(VBOX_E_INVALID_OBJECT_STATE,
3816 tr("Cannot attach storage devices to an unregistered machine"));
3817
3818 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3819
3820 /* Check for an existing controller. */
3821 ComObjPtr<StorageController> ctl;
3822 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
3823 if (FAILED(rc)) return rc;
3824
3825 StorageControllerType_T ctrlType;
3826 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
3827 if (FAILED(rc))
3828 return setError(E_FAIL,
3829 tr("Could not get type of controller '%s'"),
3830 aName.c_str());
3831
3832 bool fSilent = false;
3833 Utf8Str strReconfig;
3834
3835 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
3836 strReconfig = i_getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
3837 if ( mData->mMachineState == MachineState_Paused
3838 && strReconfig == "1")
3839 fSilent = true;
3840
3841 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
3842 bool fHotplug = false;
3843 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
3844 fHotplug = true;
3845
3846 if (fHotplug && !i_isControllerHotplugCapable(ctrlType))
3847 return setError(VBOX_E_INVALID_VM_STATE,
3848 tr("Controller '%s' does not support hotplugging"),
3849 aName.c_str());
3850
3851 // check that the port and device are not out of range
3852 rc = ctl->i_checkPortAndDeviceValid(aControllerPort, aDevice);
3853 if (FAILED(rc)) return rc;
3854
3855 /* check if the device slot is already busy */
3856 MediumAttachment *pAttachTemp;
3857 if ((pAttachTemp = i_findAttachment(*mMediumAttachments.data(),
3858 aName,
3859 aControllerPort,
3860 aDevice)))
3861 {
3862 Medium *pMedium = pAttachTemp->i_getMedium();
3863 if (pMedium)
3864 {
3865 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3866 return setError(VBOX_E_OBJECT_IN_USE,
3867 tr("Medium '%s' is already attached to port %d, device %d of controller '%s' of this virtual machine"),
3868 pMedium->i_getLocationFull().c_str(),
3869 aControllerPort,
3870 aDevice,
3871 aName.c_str());
3872 }
3873 else
3874 return setError(VBOX_E_OBJECT_IN_USE,
3875 tr("Device is already attached to port %d, device %d of controller '%s' of this virtual machine"),
3876 aControllerPort, aDevice, aName.c_str());
3877 }
3878
3879 ComObjPtr<Medium> medium = static_cast<Medium*>(aM);
3880 if (aMedium && medium.isNull())
3881 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3882
3883 AutoCaller mediumCaller(medium);
3884 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3885
3886 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3887
3888 if ( (pAttachTemp = i_findAttachment(*mMediumAttachments.data(), medium))
3889 && !medium.isNull()
3890 )
3891 return setError(VBOX_E_OBJECT_IN_USE,
3892 tr("Medium '%s' is already attached to this virtual machine"),
3893 medium->i_getLocationFull().c_str());
3894
3895 if (!medium.isNull())
3896 {
3897 MediumType_T mtype = medium->i_getType();
3898 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3899 // For DVDs it's not written to the config file, so needs no global config
3900 // version bump. For floppies it's a new attribute "type", which is ignored
3901 // by older VirtualBox version, so needs no global config version bump either.
3902 // For hard disks this type is not accepted.
3903 if (mtype == MediumType_MultiAttach)
3904 {
3905 // This type is new with VirtualBox 4.0 and therefore requires settings
3906 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3907 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3908 // two reasons: The medium type is a property of the media registry tree, which
3909 // can reside in the global config file (for pre-4.0 media); we would therefore
3910 // possibly need to bump the global config version. We don't want to do that though
3911 // because that might make downgrading to pre-4.0 impossible.
3912 // As a result, we can only use these two new types if the medium is NOT in the
3913 // global registry:
3914 const Guid &uuidGlobalRegistry = mParent->i_getGlobalRegistryId();
3915 if ( medium->i_isInRegistry(uuidGlobalRegistry)
3916 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3917 )
3918 return setError(VBOX_E_INVALID_OBJECT_STATE,
3919 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3920 "to machines that were created with VirtualBox 4.0 or later"),
3921 medium->i_getLocationFull().c_str());
3922 }
3923 }
3924
3925 bool fIndirect = false;
3926 if (!medium.isNull())
3927 fIndirect = medium->i_isReadOnly();
3928 bool associate = true;
3929
3930 do
3931 {
3932 if ( aType == DeviceType_HardDisk
3933 && mMediumAttachments.isBackedUp())
3934 {
3935 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
3936
3937 /* check if the medium was attached to the VM before we started
3938 * changing attachments in which case the attachment just needs to
3939 * be restored */
3940 if ((pAttachTemp = i_findAttachment(oldAtts, medium)))
3941 {
3942 AssertReturn(!fIndirect, E_FAIL);
3943
3944 /* see if it's the same bus/channel/device */
3945 if (pAttachTemp->i_matches(aName, aControllerPort, aDevice))
3946 {
3947 /* the simplest case: restore the whole attachment
3948 * and return, nothing else to do */
3949 mMediumAttachments->push_back(pAttachTemp);
3950
3951 /* Reattach the medium to the VM. */
3952 if (fHotplug || fSilent)
3953 {
3954 mediumLock.release();
3955 treeLock.release();
3956 alock.release();
3957
3958 MediumLockList *pMediumLockList(new MediumLockList());
3959
3960 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
3961 medium /* pToLockWrite */,
3962 false /* fMediumLockWriteAll */,
3963 NULL,
3964 *pMediumLockList);
3965 alock.acquire();
3966 if (FAILED(rc))
3967 delete pMediumLockList;
3968 else
3969 {
3970 mData->mSession.mLockedMedia.Unlock();
3971 alock.release();
3972 rc = mData->mSession.mLockedMedia.Insert(pAttachTemp, pMediumLockList);
3973 mData->mSession.mLockedMedia.Lock();
3974 alock.acquire();
3975 }
3976 alock.release();
3977
3978 if (SUCCEEDED(rc))
3979 {
3980 rc = i_onStorageDeviceChange(pAttachTemp, FALSE /* aRemove */, fSilent);
3981 /* Remove lock list in case of error. */
3982 if (FAILED(rc))
3983 {
3984 mData->mSession.mLockedMedia.Unlock();
3985 mData->mSession.mLockedMedia.Remove(pAttachTemp);
3986 mData->mSession.mLockedMedia.Lock();
3987 }
3988 }
3989 }
3990
3991 return S_OK;
3992 }
3993
3994 /* bus/channel/device differ; we need a new attachment object,
3995 * but don't try to associate it again */
3996 associate = false;
3997 break;
3998 }
3999 }
4000
4001 /* go further only if the attachment is to be indirect */
4002 if (!fIndirect)
4003 break;
4004
4005 /* perform the so called smart attachment logic for indirect
4006 * attachments. Note that smart attachment is only applicable to base
4007 * hard disks. */
4008
4009 if (medium->i_getParent().isNull())
4010 {
4011 /* first, investigate the backup copy of the current hard disk
4012 * attachments to make it possible to re-attach existing diffs to
4013 * another device slot w/o losing their contents */
4014 if (mMediumAttachments.isBackedUp())
4015 {
4016 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
4017
4018 MediumAttachmentList::const_iterator foundIt = oldAtts.end();
4019 uint32_t foundLevel = 0;
4020
4021 for (MediumAttachmentList::const_iterator
4022 it = oldAtts.begin();
4023 it != oldAtts.end();
4024 ++it)
4025 {
4026 uint32_t level = 0;
4027 MediumAttachment *pAttach = *it;
4028 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
4029 Assert(!pMedium.isNull() || pAttach->i_getType() != DeviceType_HardDisk);
4030 if (pMedium.isNull())
4031 continue;
4032
4033 if (pMedium->i_getBase(&level) == medium)
4034 {
4035 /* skip the hard disk if its currently attached (we
4036 * cannot attach the same hard disk twice) */
4037 if (i_findAttachment(*mMediumAttachments.data(),
4038 pMedium))
4039 continue;
4040
4041 /* matched device, channel and bus (i.e. attached to the
4042 * same place) will win and immediately stop the search;
4043 * otherwise the attachment that has the youngest
4044 * descendant of medium will be used
4045 */
4046 if (pAttach->i_matches(aName, aControllerPort, aDevice))
4047 {
4048 /* the simplest case: restore the whole attachment
4049 * and return, nothing else to do */
4050 mMediumAttachments->push_back(*it);
4051
4052 /* Reattach the medium to the VM. */
4053 if (fHotplug || fSilent)
4054 {
4055 mediumLock.release();
4056 treeLock.release();
4057 alock.release();
4058
4059 MediumLockList *pMediumLockList(new MediumLockList());
4060
4061 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
4062 medium /* pToLockWrite */,
4063 false /* fMediumLockWriteAll */,
4064 NULL,
4065 *pMediumLockList);
4066 alock.acquire();
4067 if (FAILED(rc))
4068 delete pMediumLockList;
4069 else
4070 {
4071 mData->mSession.mLockedMedia.Unlock();
4072 alock.release();
4073 rc = mData->mSession.mLockedMedia.Insert(pAttachTemp, pMediumLockList);
4074 mData->mSession.mLockedMedia.Lock();
4075 alock.acquire();
4076 }
4077 alock.release();
4078
4079 if (SUCCEEDED(rc))
4080 {
4081 rc = i_onStorageDeviceChange(pAttachTemp, FALSE /* aRemove */, fSilent);
4082 /* Remove lock list in case of error. */
4083 if (FAILED(rc))
4084 {
4085 mData->mSession.mLockedMedia.Unlock();
4086 mData->mSession.mLockedMedia.Remove(pAttachTemp);
4087 mData->mSession.mLockedMedia.Lock();
4088 }
4089 }
4090 }
4091
4092 return S_OK;
4093 }
4094 else if ( foundIt == oldAtts.end()
4095 || level > foundLevel /* prefer younger */
4096 )
4097 {
4098 foundIt = it;
4099 foundLevel = level;
4100 }
4101 }
4102 }
4103
4104 if (foundIt != oldAtts.end())
4105 {
4106 /* use the previously attached hard disk */
4107 medium = (*foundIt)->i_getMedium();
4108 mediumCaller.attach(medium);
4109 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4110 mediumLock.attach(medium);
4111 /* not implicit, doesn't require association with this VM */
4112 fIndirect = false;
4113 associate = false;
4114 /* go right to the MediumAttachment creation */
4115 break;
4116 }
4117 }
4118
4119 /* must give up the medium lock and medium tree lock as below we
4120 * go over snapshots, which needs a lock with higher lock order. */
4121 mediumLock.release();
4122 treeLock.release();
4123
4124 /* then, search through snapshots for the best diff in the given
4125 * hard disk's chain to base the new diff on */
4126
4127 ComObjPtr<Medium> base;
4128 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
4129 while (snap)
4130 {
4131 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
4132
4133 const MediumAttachmentList &snapAtts = *snap->i_getSnapshotMachine()->mMediumAttachments.data();
4134
4135 MediumAttachment *pAttachFound = NULL;
4136 uint32_t foundLevel = 0;
4137
4138 for (MediumAttachmentList::const_iterator
4139 it = snapAtts.begin();
4140 it != snapAtts.end();
4141 ++it)
4142 {
4143 MediumAttachment *pAttach = *it;
4144 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
4145 Assert(!pMedium.isNull() || pAttach->i_getType() != DeviceType_HardDisk);
4146 if (pMedium.isNull())
4147 continue;
4148
4149 uint32_t level = 0;
4150 if (pMedium->i_getBase(&level) == medium)
4151 {
4152 /* matched device, channel and bus (i.e. attached to the
4153 * same place) will win and immediately stop the search;
4154 * otherwise the attachment that has the youngest
4155 * descendant of medium will be used
4156 */
4157 if ( pAttach->i_getDevice() == aDevice
4158 && pAttach->i_getPort() == aControllerPort
4159 && pAttach->i_getControllerName() == aName
4160 )
4161 {
4162 pAttachFound = pAttach;
4163 break;
4164 }
4165 else if ( !pAttachFound
4166 || level > foundLevel /* prefer younger */
4167 )
4168 {
4169 pAttachFound = pAttach;
4170 foundLevel = level;
4171 }
4172 }
4173 }
4174
4175 if (pAttachFound)
4176 {
4177 base = pAttachFound->i_getMedium();
4178 break;
4179 }
4180
4181 snap = snap->i_getParent();
4182 }
4183
4184 /* re-lock medium tree and the medium, as we need it below */
4185 treeLock.acquire();
4186 mediumLock.acquire();
4187
4188 /* found a suitable diff, use it as a base */
4189 if (!base.isNull())
4190 {
4191 medium = base;
4192 mediumCaller.attach(medium);
4193 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4194 mediumLock.attach(medium);
4195 }
4196 }
4197
4198 Utf8Str strFullSnapshotFolder;
4199 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4200
4201 ComObjPtr<Medium> diff;
4202 diff.createObject();
4203 // store this diff in the same registry as the parent
4204 Guid uuidRegistryParent;
4205 if (!medium->i_getFirstRegistryMachineId(uuidRegistryParent))
4206 {
4207 // parent image has no registry: this can happen if we're attaching a new immutable
4208 // image that has not yet been attached (medium then points to the base and we're
4209 // creating the diff image for the immutable, and the parent is not yet registered);
4210 // put the parent in the machine registry then
4211 mediumLock.release();
4212 treeLock.release();
4213 alock.release();
4214 i_addMediumToRegistry(medium);
4215 alock.acquire();
4216 treeLock.acquire();
4217 mediumLock.acquire();
4218 medium->i_getFirstRegistryMachineId(uuidRegistryParent);
4219 }
4220 rc = diff->init(mParent,
4221 medium->i_getPreferredDiffFormat(),
4222 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
4223 uuidRegistryParent,
4224 DeviceType_HardDisk);
4225 if (FAILED(rc)) return rc;
4226
4227 /* Apply the normal locking logic to the entire chain. */
4228 MediumLockList *pMediumLockList(new MediumLockList());
4229 mediumLock.release();
4230 treeLock.release();
4231 rc = diff->i_createMediumLockList(true /* fFailIfInaccessible */,
4232 diff /* pToLockWrite */,
4233 false /* fMediumLockWriteAll */,
4234 medium,
4235 *pMediumLockList);
4236 treeLock.acquire();
4237 mediumLock.acquire();
4238 if (SUCCEEDED(rc))
4239 {
4240 mediumLock.release();
4241 treeLock.release();
4242 rc = pMediumLockList->Lock();
4243 treeLock.acquire();
4244 mediumLock.acquire();
4245 if (FAILED(rc))
4246 setError(rc,
4247 tr("Could not lock medium when creating diff '%s'"),
4248 diff->i_getLocationFull().c_str());
4249 else
4250 {
4251 /* will release the lock before the potentially lengthy
4252 * operation, so protect with the special state */
4253 MachineState_T oldState = mData->mMachineState;
4254 i_setMachineState(MachineState_SettingUp);
4255
4256 mediumLock.release();
4257 treeLock.release();
4258 alock.release();
4259
4260 rc = medium->i_createDiffStorage(diff,
4261 medium->i_getPreferredDiffVariant(),
4262 pMediumLockList,
4263 NULL /* aProgress */,
4264 true /* aWait */);
4265
4266 alock.acquire();
4267 treeLock.acquire();
4268 mediumLock.acquire();
4269
4270 i_setMachineState(oldState);
4271 }
4272 }
4273
4274 /* Unlock the media and free the associated memory. */
4275 delete pMediumLockList;
4276
4277 if (FAILED(rc)) return rc;
4278
4279 /* use the created diff for the actual attachment */
4280 medium = diff;
4281 mediumCaller.attach(medium);
4282 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4283 mediumLock.attach(medium);
4284 }
4285 while (0);
4286
4287 ComObjPtr<MediumAttachment> attachment;
4288 attachment.createObject();
4289 rc = attachment->init(this,
4290 medium,
4291 aName,
4292 aControllerPort,
4293 aDevice,
4294 aType,
4295 fIndirect,
4296 false /* fPassthrough */,
4297 false /* fTempEject */,
4298 false /* fNonRotational */,
4299 false /* fDiscard */,
4300 fHotplug /* fHotPluggable */,
4301 Utf8Str::Empty);
4302 if (FAILED(rc)) return rc;
4303
4304 if (associate && !medium.isNull())
4305 {
4306 // as the last step, associate the medium to the VM
4307 rc = medium->i_addBackReference(mData->mUuid);
4308 // here we can fail because of Deleting, or being in process of creating a Diff
4309 if (FAILED(rc)) return rc;
4310
4311 mediumLock.release();
4312 treeLock.release();
4313 alock.release();
4314 i_addMediumToRegistry(medium);
4315 alock.acquire();
4316 treeLock.acquire();
4317 mediumLock.acquire();
4318 }
4319
4320 /* success: finally remember the attachment */
4321 i_setModified(IsModified_Storage);
4322 mMediumAttachments.backup();
4323 mMediumAttachments->push_back(attachment);
4324
4325 mediumLock.release();
4326 treeLock.release();
4327 alock.release();
4328
4329 if (fHotplug || fSilent)
4330 {
4331 if (!medium.isNull())
4332 {
4333 MediumLockList *pMediumLockList(new MediumLockList());
4334
4335 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
4336 medium /* pToLockWrite */,
4337 false /* fMediumLockWriteAll */,
4338 NULL,
4339 *pMediumLockList);
4340 alock.acquire();
4341 if (FAILED(rc))
4342 delete pMediumLockList;
4343 else
4344 {
4345 mData->mSession.mLockedMedia.Unlock();
4346 alock.release();
4347 rc = mData->mSession.mLockedMedia.Insert(attachment, pMediumLockList);
4348 mData->mSession.mLockedMedia.Lock();
4349 alock.acquire();
4350 }
4351 alock.release();
4352 }
4353
4354 if (SUCCEEDED(rc))
4355 {
4356 rc = i_onStorageDeviceChange(attachment, FALSE /* aRemove */, fSilent);
4357 /* Remove lock list in case of error. */
4358 if (FAILED(rc))
4359 {
4360 mData->mSession.mLockedMedia.Unlock();
4361 mData->mSession.mLockedMedia.Remove(attachment);
4362 mData->mSession.mLockedMedia.Lock();
4363 }
4364 }
4365 }
4366
4367 /* Save modified registries, but skip this machine as it's the caller's
4368 * job to save its settings like all other settings changes. */
4369 mParent->i_unmarkRegistryModified(i_getId());
4370 mParent->i_saveModifiedRegistries();
4371
4372 return rc;
4373}
4374
4375HRESULT Machine::detachDevice(const com::Utf8Str &aName, LONG aControllerPort,
4376 LONG aDevice)
4377{
4378 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
4379 aName.c_str(), aControllerPort, aDevice));
4380
4381 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4382
4383 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
4384 if (FAILED(rc)) return rc;
4385
4386 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4387
4388 /* Check for an existing controller. */
4389 ComObjPtr<StorageController> ctl;
4390 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
4391 if (FAILED(rc)) return rc;
4392
4393 StorageControllerType_T ctrlType;
4394 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4395 if (FAILED(rc))
4396 return setError(E_FAIL,
4397 tr("Could not get type of controller '%s'"),
4398 aName.c_str());
4399
4400 bool fSilent = false;
4401 Utf8Str strReconfig;
4402
4403 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
4404 strReconfig = i_getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
4405 if ( mData->mMachineState == MachineState_Paused
4406 && strReconfig == "1")
4407 fSilent = true;
4408
4409 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
4410 bool fHotplug = false;
4411 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
4412 fHotplug = true;
4413
4414 if (fHotplug && !i_isControllerHotplugCapable(ctrlType))
4415 return setError(VBOX_E_INVALID_VM_STATE,
4416 tr("Controller '%s' does not support hotplugging"),
4417 aName.c_str());
4418
4419 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4420 aName,
4421 aControllerPort,
4422 aDevice);
4423 if (!pAttach)
4424 return setError(VBOX_E_OBJECT_NOT_FOUND,
4425 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4426 aDevice, aControllerPort, aName.c_str());
4427
4428 if (fHotplug && !pAttach->i_getHotPluggable())
4429 return setError(VBOX_E_NOT_SUPPORTED,
4430 tr("The device slot %d on port %d of controller '%s' does not support hotplugging"),
4431 aDevice, aControllerPort, aName.c_str());
4432
4433 /*
4434 * The VM has to detach the device before we delete any implicit diffs.
4435 * If this fails we can roll back without loosing data.
4436 */
4437 if (fHotplug || fSilent)
4438 {
4439 alock.release();
4440 rc = i_onStorageDeviceChange(pAttach, TRUE /* aRemove */, fSilent);
4441 alock.acquire();
4442 }
4443 if (FAILED(rc)) return rc;
4444
4445 /* If we are here everything went well and we can delete the implicit now. */
4446 rc = i_detachDevice(pAttach, alock, NULL /* pSnapshot */);
4447
4448 alock.release();
4449
4450 /* Save modified registries, but skip this machine as it's the caller's
4451 * job to save its settings like all other settings changes. */
4452 mParent->i_unmarkRegistryModified(i_getId());
4453 mParent->i_saveModifiedRegistries();
4454
4455 return rc;
4456}
4457
4458HRESULT Machine::passthroughDevice(const com::Utf8Str &aName, LONG aControllerPort,
4459 LONG aDevice, BOOL aPassthrough)
4460{
4461 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aPassthrough=%d\n",
4462 aName.c_str(), aControllerPort, aDevice, aPassthrough));
4463
4464 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4465
4466 HRESULT rc = i_checkStateDependency(MutableStateDep);
4467 if (FAILED(rc)) return rc;
4468
4469 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4470
4471 if (Global::IsOnlineOrTransient(mData->mMachineState))
4472 return setError(VBOX_E_INVALID_VM_STATE,
4473 tr("Invalid machine state: %s"),
4474 Global::stringifyMachineState(mData->mMachineState));
4475
4476 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4477 aName,
4478 aControllerPort,
4479 aDevice);
4480 if (!pAttach)
4481 return setError(VBOX_E_OBJECT_NOT_FOUND,
4482 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4483 aDevice, aControllerPort, aName.c_str());
4484
4485
4486 i_setModified(IsModified_Storage);
4487 mMediumAttachments.backup();
4488
4489 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4490
4491 if (pAttach->i_getType() != DeviceType_DVD)
4492 return setError(E_INVALIDARG,
4493 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
4494 aDevice, aControllerPort, aName.c_str());
4495 pAttach->i_updatePassthrough(!!aPassthrough);
4496
4497 return S_OK;
4498}
4499
4500HRESULT Machine::temporaryEjectDevice(const com::Utf8Str &aName, LONG aControllerPort,
4501 LONG aDevice, BOOL aTemporaryEject)
4502{
4503
4504 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aTemporaryEject=%d\n",
4505 aName.c_str(), aControllerPort, aDevice, aTemporaryEject));
4506
4507 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4508
4509 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
4510 if (FAILED(rc)) return rc;
4511
4512 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4513 aName,
4514 aControllerPort,
4515 aDevice);
4516 if (!pAttach)
4517 return setError(VBOX_E_OBJECT_NOT_FOUND,
4518 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4519 aDevice, aControllerPort, aName.c_str());
4520
4521
4522 i_setModified(IsModified_Storage);
4523 mMediumAttachments.backup();
4524
4525 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4526
4527 if (pAttach->i_getType() != DeviceType_DVD)
4528 return setError(E_INVALIDARG,
4529 tr("Setting temporary eject flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
4530 aDevice, aControllerPort, aName.c_str());
4531 pAttach->i_updateTempEject(!!aTemporaryEject);
4532
4533 return S_OK;
4534}
4535
4536HRESULT Machine::nonRotationalDevice(const com::Utf8Str &aName, LONG aControllerPort,
4537 LONG aDevice, BOOL aNonRotational)
4538{
4539
4540 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aNonRotational=%d\n",
4541 aName.c_str(), aControllerPort, aDevice, aNonRotational));
4542
4543 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4544
4545 HRESULT rc = i_checkStateDependency(MutableStateDep);
4546 if (FAILED(rc)) return rc;
4547
4548 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4549
4550 if (Global::IsOnlineOrTransient(mData->mMachineState))
4551 return setError(VBOX_E_INVALID_VM_STATE,
4552 tr("Invalid machine state: %s"),
4553 Global::stringifyMachineState(mData->mMachineState));
4554
4555 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4556 aName,
4557 aControllerPort,
4558 aDevice);
4559 if (!pAttach)
4560 return setError(VBOX_E_OBJECT_NOT_FOUND,
4561 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4562 aDevice, aControllerPort, aName.c_str());
4563
4564
4565 i_setModified(IsModified_Storage);
4566 mMediumAttachments.backup();
4567
4568 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4569
4570 if (pAttach->i_getType() != DeviceType_HardDisk)
4571 return setError(E_INVALIDARG,
4572 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"),
4573 aDevice, aControllerPort, aName.c_str());
4574 pAttach->i_updateNonRotational(!!aNonRotational);
4575
4576 return S_OK;
4577}
4578
4579HRESULT Machine::setAutoDiscardForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4580 LONG aDevice, BOOL aDiscard)
4581{
4582
4583 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aDiscard=%d\n",
4584 aName.c_str(), aControllerPort, aDevice, aDiscard));
4585
4586 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4587
4588 HRESULT rc = i_checkStateDependency(MutableStateDep);
4589 if (FAILED(rc)) return rc;
4590
4591 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4592
4593 if (Global::IsOnlineOrTransient(mData->mMachineState))
4594 return setError(VBOX_E_INVALID_VM_STATE,
4595 tr("Invalid machine state: %s"),
4596 Global::stringifyMachineState(mData->mMachineState));
4597
4598 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4599 aName,
4600 aControllerPort,
4601 aDevice);
4602 if (!pAttach)
4603 return setError(VBOX_E_OBJECT_NOT_FOUND,
4604 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4605 aDevice, aControllerPort, aName.c_str());
4606
4607
4608 i_setModified(IsModified_Storage);
4609 mMediumAttachments.backup();
4610
4611 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4612
4613 if (pAttach->i_getType() != DeviceType_HardDisk)
4614 return setError(E_INVALIDARG,
4615 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"),
4616 aDevice, aControllerPort, aName.c_str());
4617 pAttach->i_updateDiscard(!!aDiscard);
4618
4619 return S_OK;
4620}
4621
4622HRESULT Machine::setHotPluggableForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4623 LONG aDevice, BOOL aHotPluggable)
4624{
4625 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aHotPluggable=%d\n",
4626 aName.c_str(), aControllerPort, aDevice, aHotPluggable));
4627
4628 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4629
4630 HRESULT rc = i_checkStateDependency(MutableStateDep);
4631 if (FAILED(rc)) return rc;
4632
4633 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4634
4635 if (Global::IsOnlineOrTransient(mData->mMachineState))
4636 return setError(VBOX_E_INVALID_VM_STATE,
4637 tr("Invalid machine state: %s"),
4638 Global::stringifyMachineState(mData->mMachineState));
4639
4640 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4641 aName,
4642 aControllerPort,
4643 aDevice);
4644 if (!pAttach)
4645 return setError(VBOX_E_OBJECT_NOT_FOUND,
4646 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4647 aDevice, aControllerPort, aName.c_str());
4648
4649 /* Check for an existing controller. */
4650 ComObjPtr<StorageController> ctl;
4651 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
4652 if (FAILED(rc)) return rc;
4653
4654 StorageControllerType_T ctrlType;
4655 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4656 if (FAILED(rc))
4657 return setError(E_FAIL,
4658 tr("Could not get type of controller '%s'"),
4659 aName.c_str());
4660
4661 if (!i_isControllerHotplugCapable(ctrlType))
4662 return setError(VBOX_E_NOT_SUPPORTED,
4663 tr("Controller '%s' does not support changing the hot-pluggable device flag"),
4664 aName.c_str());
4665
4666 i_setModified(IsModified_Storage);
4667 mMediumAttachments.backup();
4668
4669 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4670
4671 if (pAttach->i_getType() == DeviceType_Floppy)
4672 return setError(E_INVALIDARG,
4673 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"),
4674 aDevice, aControllerPort, aName.c_str());
4675 pAttach->i_updateHotPluggable(!!aHotPluggable);
4676
4677 return S_OK;
4678}
4679
4680HRESULT Machine::setNoBandwidthGroupForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4681 LONG aDevice)
4682{
4683 int rc = S_OK;
4684 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4685 aName.c_str(), aControllerPort, aDevice));
4686
4687 rc = setBandwidthGroupForDevice(aName, aControllerPort, aDevice, NULL);
4688
4689 return rc;
4690}
4691
4692HRESULT Machine::setBandwidthGroupForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4693 LONG aDevice, const ComPtr<IBandwidthGroup> &aBandwidthGroup)
4694{
4695 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4696 aName.c_str(), aControllerPort, aDevice));
4697
4698 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4699
4700 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
4701 if (FAILED(rc)) return rc;
4702
4703 if (Global::IsOnlineOrTransient(mData->mMachineState))
4704 return setError(VBOX_E_INVALID_VM_STATE,
4705 tr("Invalid machine state: %s"),
4706 Global::stringifyMachineState(mData->mMachineState));
4707
4708 MediumAttachment *pAttach = i_findAttachment(*mMediumAttachments.data(),
4709 aName,
4710 aControllerPort,
4711 aDevice);
4712 if (!pAttach)
4713 return setError(VBOX_E_OBJECT_NOT_FOUND,
4714 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4715 aDevice, aControllerPort, aName.c_str());
4716
4717
4718 i_setModified(IsModified_Storage);
4719 mMediumAttachments.backup();
4720
4721 IBandwidthGroup *iB = aBandwidthGroup;
4722 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(iB);
4723 if (aBandwidthGroup && group.isNull())
4724 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
4725
4726 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4727
4728 const Utf8Str strBandwidthGroupOld = pAttach->i_getBandwidthGroup();
4729 if (strBandwidthGroupOld.isNotEmpty())
4730 {
4731 /* Get the bandwidth group object and release it - this must not fail. */
4732 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
4733 rc = i_getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
4734 Assert(SUCCEEDED(rc));
4735
4736 pBandwidthGroupOld->i_release();
4737 pAttach->i_updateBandwidthGroup(Utf8Str::Empty);
4738 }
4739
4740 if (!group.isNull())
4741 {
4742 group->i_reference();
4743 pAttach->i_updateBandwidthGroup(group->i_getName());
4744 }
4745
4746 return S_OK;
4747}
4748
4749HRESULT Machine::attachDeviceWithoutMedium(const com::Utf8Str &aName,
4750 LONG aControllerPort,
4751 LONG aDevice,
4752 DeviceType_T aType)
4753{
4754 HRESULT rc = S_OK;
4755
4756 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aType=%d\n",
4757 aName.c_str(), aControllerPort, aDevice, aType));
4758
4759 rc = attachDevice(aName, aControllerPort, aDevice, aType, NULL);
4760
4761 return rc;
4762}
4763
4764
4765HRESULT Machine::unmountMedium(const com::Utf8Str &aName,
4766 LONG aControllerPort,
4767 LONG aDevice,
4768 BOOL aForce)
4769{
4770 int rc = S_OK;
4771 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d",
4772 aName.c_str(), aControllerPort, aForce));
4773
4774 rc = mountMedium(aName, aControllerPort, aDevice, NULL, aForce);
4775
4776 return rc;
4777}
4778
4779HRESULT Machine::mountMedium(const com::Utf8Str &aName,
4780 LONG aControllerPort,
4781 LONG aDevice,
4782 const ComPtr<IMedium> &aMedium,
4783 BOOL aForce)
4784{
4785 int rc = S_OK;
4786 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aForce=%d\n",
4787 aName.c_str(), aControllerPort, aDevice, aForce));
4788
4789 // request the host lock first, since might be calling Host methods for getting host drives;
4790 // next, protect the media tree all the while we're in here, as well as our member variables
4791 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
4792 this->lockHandle(),
4793 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4794
4795 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(*mMediumAttachments.data(),
4796 aName,
4797 aControllerPort,
4798 aDevice);
4799 if (pAttach.isNull())
4800 return setError(VBOX_E_OBJECT_NOT_FOUND,
4801 tr("No drive attached to device slot %d on port %d of controller '%s'"),
4802 aDevice, aControllerPort, aName.c_str());
4803
4804 /* Remember previously mounted medium. The medium before taking the
4805 * backup is not necessarily the same thing. */
4806 ComObjPtr<Medium> oldmedium;
4807 oldmedium = pAttach->i_getMedium();
4808
4809 IMedium *iM = aMedium;
4810 ComObjPtr<Medium> pMedium = static_cast<Medium*>(iM);
4811 if (aMedium && pMedium.isNull())
4812 return setError(E_INVALIDARG, "The given medium pointer is invalid");
4813
4814 AutoCaller mediumCaller(pMedium);
4815 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4816
4817 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4818 if (pMedium)
4819 {
4820 DeviceType_T mediumType = pAttach->i_getType();
4821 switch (mediumType)
4822 {
4823 case DeviceType_DVD:
4824 case DeviceType_Floppy:
4825 break;
4826
4827 default:
4828 return setError(VBOX_E_INVALID_OBJECT_STATE,
4829 tr("The device at port %d, device %d of controller '%s' of this virtual machine is not removeable"),
4830 aControllerPort,
4831 aDevice,
4832 aName.c_str());
4833 }
4834 }
4835
4836 i_setModified(IsModified_Storage);
4837 mMediumAttachments.backup();
4838
4839 {
4840 // The backup operation makes the pAttach reference point to the
4841 // old settings. Re-get the correct reference.
4842 pAttach = i_findAttachment(*mMediumAttachments.data(),
4843 aName,
4844 aControllerPort,
4845 aDevice);
4846 if (!oldmedium.isNull())
4847 oldmedium->i_removeBackReference(mData->mUuid);
4848 if (!pMedium.isNull())
4849 {
4850 pMedium->i_addBackReference(mData->mUuid);
4851
4852 mediumLock.release();
4853 multiLock.release();
4854 i_addMediumToRegistry(pMedium);
4855 multiLock.acquire();
4856 mediumLock.acquire();
4857 }
4858
4859 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4860 pAttach->i_updateMedium(pMedium);
4861 }
4862
4863 i_setModified(IsModified_Storage);
4864
4865 mediumLock.release();
4866 multiLock.release();
4867 rc = i_onMediumChange(pAttach, aForce);
4868 multiLock.acquire();
4869 mediumLock.acquire();
4870
4871 /* On error roll back this change only. */
4872 if (FAILED(rc))
4873 {
4874 if (!pMedium.isNull())
4875 pMedium->i_removeBackReference(mData->mUuid);
4876 pAttach = i_findAttachment(*mMediumAttachments.data(),
4877 aName,
4878 aControllerPort,
4879 aDevice);
4880 /* If the attachment is gone in the meantime, bail out. */
4881 if (pAttach.isNull())
4882 return rc;
4883 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4884 if (!oldmedium.isNull())
4885 oldmedium->i_addBackReference(mData->mUuid);
4886 pAttach->i_updateMedium(oldmedium);
4887 }
4888
4889 mediumLock.release();
4890 multiLock.release();
4891
4892 /* Save modified registries, but skip this machine as it's the caller's
4893 * job to save its settings like all other settings changes. */
4894 mParent->i_unmarkRegistryModified(i_getId());
4895 mParent->i_saveModifiedRegistries();
4896
4897 return rc;
4898}
4899HRESULT Machine::getMedium(const com::Utf8Str &aName,
4900 LONG aControllerPort,
4901 LONG aDevice,
4902 ComPtr<IMedium> &aMedium)
4903{
4904 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4905 aName.c_str(), aControllerPort, aDevice));
4906
4907 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4908
4909 aMedium = NULL;
4910
4911 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(*mMediumAttachments.data(),
4912 aName,
4913 aControllerPort,
4914 aDevice);
4915 if (pAttach.isNull())
4916 return setError(VBOX_E_OBJECT_NOT_FOUND,
4917 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4918 aDevice, aControllerPort, aName.c_str());
4919
4920 aMedium = pAttach->i_getMedium();
4921
4922 return S_OK;
4923}
4924
4925HRESULT Machine::getSerialPort(ULONG aSlot, ComPtr<ISerialPort> &aPort)
4926{
4927
4928 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4929
4930 mSerialPorts[aSlot].queryInterfaceTo(aPort.asOutParam());
4931
4932 return S_OK;
4933}
4934
4935HRESULT Machine::getParallelPort(ULONG aSlot, ComPtr<IParallelPort> &aPort)
4936{
4937 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4938
4939 mParallelPorts[aSlot].queryInterfaceTo(aPort.asOutParam());
4940
4941 return S_OK;
4942}
4943
4944HRESULT Machine::getNetworkAdapter(ULONG aSlot, ComPtr<INetworkAdapter> &aAdapter)
4945{
4946 /* Do not assert if slot is out of range, just return the advertised
4947 status. testdriver/vbox.py triggers this in logVmInfo. */
4948 if (aSlot >= mNetworkAdapters.size())
4949 return setError(E_INVALIDARG,
4950 tr("No network adapter in slot %RU32 (total %RU32 adapters)"),
4951 aSlot, mNetworkAdapters.size());
4952
4953 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4954
4955 mNetworkAdapters[aSlot].queryInterfaceTo(aAdapter.asOutParam());
4956
4957 return S_OK;
4958}
4959
4960HRESULT Machine::getExtraDataKeys(std::vector<com::Utf8Str> &aKeys)
4961{
4962 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4963
4964 aKeys.resize(mData->pMachineConfigFile->mapExtraDataItems.size());
4965 size_t i = 0;
4966 for (settings::StringsMap::const_iterator
4967 it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4968 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4969 ++it, ++i)
4970 aKeys[i] = it->first;
4971
4972 return S_OK;
4973}
4974
4975 /**
4976 * @note Locks this object for reading.
4977 */
4978HRESULT Machine::getExtraData(const com::Utf8Str &aKey,
4979 com::Utf8Str &aValue)
4980{
4981 /* start with nothing found */
4982 aValue = "";
4983
4984 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4985
4986 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(aKey);
4987 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4988 // found:
4989 aValue = it->second; // source is a Utf8Str
4990
4991 /* return the result to caller (may be empty) */
4992 return S_OK;
4993}
4994
4995 /**
4996 * @note Locks mParent for writing + this object for writing.
4997 */
4998HRESULT Machine::setExtraData(const com::Utf8Str &aKey, const com::Utf8Str &aValue)
4999{
5000 Utf8Str strOldValue; // empty
5001
5002 // locking note: we only hold the read lock briefly to look up the old value,
5003 // then release it and call the onExtraCanChange callbacks. There is a small
5004 // chance of a race insofar as the callback might be called twice if two callers
5005 // change the same key at the same time, but that's a much better solution
5006 // than the deadlock we had here before. The actual changing of the extradata
5007 // is then performed under the write lock and race-free.
5008
5009 // look up the old value first; if nothing has changed then we need not do anything
5010 {
5011 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
5012
5013 // For snapshots don't even think about allowing changes, extradata
5014 // is global for a machine, so there is nothing snapshot specific.
5015 if (i_isSnapshotMachine())
5016 return setError(VBOX_E_INVALID_VM_STATE,
5017 tr("Cannot set extradata for a snapshot"));
5018
5019 // check if the right IMachine instance is used
5020 if (mData->mRegistered && !i_isSessionMachine())
5021 return setError(VBOX_E_INVALID_VM_STATE,
5022 tr("Cannot set extradata for an immutable machine"));
5023
5024 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(aKey);
5025 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
5026 strOldValue = it->second;
5027 }
5028
5029 bool fChanged;
5030 if ((fChanged = (strOldValue != aValue)))
5031 {
5032 // ask for permission from all listeners outside the locks;
5033 // i_onExtraDataCanChange() only briefly requests the VirtualBox
5034 // lock to copy the list of callbacks to invoke
5035 Bstr error;
5036 Bstr bstrValue(aValue);
5037
5038 if (!mParent->i_onExtraDataCanChange(mData->mUuid, Bstr(aKey).raw(), bstrValue.raw(), error))
5039 {
5040 const char *sep = error.isEmpty() ? "" : ": ";
5041 CBSTR err = error.raw();
5042 Log1WarningFunc(("Someone vetoed! Change refused%s%ls\n", sep, err));
5043 return setError(E_ACCESSDENIED,
5044 tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
5045 aKey.c_str(),
5046 aValue.c_str(),
5047 sep,
5048 err);
5049 }
5050
5051 // data is changing and change not vetoed: then write it out under the lock
5052 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5053
5054 if (aValue.isEmpty())
5055 mData->pMachineConfigFile->mapExtraDataItems.erase(aKey);
5056 else
5057 mData->pMachineConfigFile->mapExtraDataItems[aKey] = aValue;
5058 // creates a new key if needed
5059
5060 bool fNeedsGlobalSaveSettings = false;
5061 // This saving of settings is tricky: there is no "old state" for the
5062 // extradata items at all (unlike all other settings), so the old/new
5063 // settings comparison would give a wrong result!
5064 i_saveSettings(&fNeedsGlobalSaveSettings, SaveS_Force);
5065
5066 if (fNeedsGlobalSaveSettings)
5067 {
5068 // save the global settings; for that we should hold only the VirtualBox lock
5069 alock.release();
5070 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
5071 mParent->i_saveSettings();
5072 }
5073 }
5074
5075 // fire notification outside the lock
5076 if (fChanged)
5077 mParent->i_onExtraDataChange(mData->mUuid, Bstr(aKey).raw(), Bstr(aValue).raw());
5078
5079 return S_OK;
5080}
5081
5082HRESULT Machine::setSettingsFilePath(const com::Utf8Str &aSettingsFilePath, ComPtr<IProgress> &aProgress)
5083{
5084 aProgress = NULL;
5085 NOREF(aSettingsFilePath);
5086 ReturnComNotImplemented();
5087}
5088
5089HRESULT Machine::saveSettings()
5090{
5091 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
5092
5093 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
5094 if (FAILED(rc)) return rc;
5095
5096 /* the settings file path may never be null */
5097 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
5098
5099 /* save all VM data excluding snapshots */
5100 bool fNeedsGlobalSaveSettings = false;
5101 rc = i_saveSettings(&fNeedsGlobalSaveSettings);
5102 mlock.release();
5103
5104 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
5105 {
5106 // save the global settings; for that we should hold only the VirtualBox lock
5107 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
5108 rc = mParent->i_saveSettings();
5109 }
5110
5111 return rc;
5112}
5113
5114
5115HRESULT Machine::discardSettings()
5116{
5117 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5118
5119 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
5120 if (FAILED(rc)) return rc;
5121
5122 /*
5123 * during this rollback, the session will be notified if data has
5124 * been actually changed
5125 */
5126 i_rollback(true /* aNotify */);
5127
5128 return S_OK;
5129}
5130
5131/** @note Locks objects! */
5132HRESULT Machine::unregister(AutoCaller &autoCaller,
5133 CleanupMode_T aCleanupMode,
5134 std::vector<ComPtr<IMedium> > &aMedia)
5135{
5136 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5137
5138 Guid id(i_getId());
5139
5140 if (mData->mSession.mState != SessionState_Unlocked)
5141 return setError(VBOX_E_INVALID_OBJECT_STATE,
5142 tr("Cannot unregister the machine '%s' while it is locked"),
5143 mUserData->s.strName.c_str());
5144
5145 // wait for state dependents to drop to zero
5146 i_ensureNoStateDependencies();
5147
5148 if (!mData->mAccessible)
5149 {
5150 // inaccessible maschines can only be unregistered; uninitialize ourselves
5151 // here because currently there may be no unregistered that are inaccessible
5152 // (this state combination is not supported). Note releasing the caller and
5153 // leaving the lock before calling uninit()
5154 alock.release();
5155 autoCaller.release();
5156
5157 uninit();
5158
5159 mParent->i_unregisterMachine(this, id);
5160 // calls VirtualBox::i_saveSettings()
5161
5162 return S_OK;
5163 }
5164
5165 HRESULT rc = S_OK;
5166
5167 /// @todo r=klaus this is stupid... why is the saved state always deleted?
5168 // discard saved state
5169 if (mData->mMachineState == MachineState_Saved)
5170 {
5171 // add the saved state file to the list of files the caller should delete
5172 Assert(!mSSData->strStateFilePath.isEmpty());
5173 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
5174
5175 mSSData->strStateFilePath.setNull();
5176
5177 // unconditionally set the machine state to powered off, we now
5178 // know no session has locked the machine
5179 mData->mMachineState = MachineState_PoweredOff;
5180 }
5181
5182 size_t cSnapshots = 0;
5183 if (mData->mFirstSnapshot)
5184 cSnapshots = mData->mFirstSnapshot->i_getAllChildrenCount() + 1;
5185 if (cSnapshots && aCleanupMode == CleanupMode_UnregisterOnly)
5186 // fail now before we start detaching media
5187 return setError(VBOX_E_INVALID_OBJECT_STATE,
5188 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
5189 mUserData->s.strName.c_str(), cSnapshots);
5190
5191 // This list collects the medium objects from all medium attachments
5192 // which we will detach from the machine and its snapshots, in a specific
5193 // order which allows for closing all media without getting "media in use"
5194 // errors, simply by going through the list from the front to the back:
5195 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
5196 // and must be closed before the parent media from the snapshots, or closing the parents
5197 // will fail because they still have children);
5198 // 2) media from the youngest snapshots followed by those from the parent snapshots until
5199 // the root ("first") snapshot of the machine.
5200 MediaList llMedia;
5201
5202 if ( !mMediumAttachments.isNull() // can be NULL if machine is inaccessible
5203 && mMediumAttachments->size()
5204 )
5205 {
5206 // we have media attachments: detach them all and add the Medium objects to our list
5207 if (aCleanupMode != CleanupMode_UnregisterOnly)
5208 i_detachAllMedia(alock, NULL /* pSnapshot */, aCleanupMode, llMedia);
5209 else
5210 return setError(VBOX_E_INVALID_OBJECT_STATE,
5211 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
5212 mUserData->s.strName.c_str(), mMediumAttachments->size());
5213 }
5214
5215 if (cSnapshots)
5216 {
5217 // add the media from the medium attachments of the snapshots to llMedia
5218 // as well, after the "main" machine media; Snapshot::uninitRecursively()
5219 // calls Machine::detachAllMedia() for the snapshot machine, recursing
5220 // into the children first
5221
5222 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
5223 MachineState_T oldState = mData->mMachineState;
5224 mData->mMachineState = MachineState_DeletingSnapshot;
5225
5226 // make a copy of the first snapshot so the refcount does not drop to 0
5227 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
5228 // because of the AutoCaller voodoo)
5229 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
5230
5231 // GO!
5232 pFirstSnapshot->i_uninitRecursively(alock, aCleanupMode, llMedia, mData->llFilesToDelete);
5233
5234 mData->mMachineState = oldState;
5235 }
5236
5237 if (FAILED(rc))
5238 {
5239 i_rollbackMedia();
5240 return rc;
5241 }
5242
5243 // commit all the media changes made above
5244 i_commitMedia();
5245
5246 mData->mRegistered = false;
5247
5248 // machine lock no longer needed
5249 alock.release();
5250
5251 // return media to caller
5252 aMedia.resize(llMedia.size());
5253 size_t i = 0;
5254 for (MediaList::const_iterator
5255 it = llMedia.begin();
5256 it != llMedia.end();
5257 ++it, ++i)
5258 (*it).queryInterfaceTo(aMedia[i].asOutParam());
5259
5260 mParent->i_unregisterMachine(this, id);
5261 // calls VirtualBox::i_saveSettings() and VirtualBox::saveModifiedRegistries()
5262
5263 return S_OK;
5264}
5265
5266/**
5267 * Task record for deleting a machine config.
5268 */
5269class Machine::DeleteConfigTask
5270 : public Machine::Task
5271{
5272public:
5273 DeleteConfigTask(Machine *m,
5274 Progress *p,
5275 const Utf8Str &t,
5276 const RTCList<ComPtr<IMedium> > &llMediums,
5277 const StringsList &llFilesToDelete)
5278 : Task(m, p, t),
5279 m_llMediums(llMediums),
5280 m_llFilesToDelete(llFilesToDelete)
5281 {}
5282
5283private:
5284 void handler()
5285 {
5286 try
5287 {
5288 m_pMachine->i_deleteConfigHandler(*this);
5289 }
5290 catch (...)
5291 {
5292 LogRel(("Some exception in the function Machine::i_deleteConfigHandler()\n"));
5293 }
5294 }
5295
5296 RTCList<ComPtr<IMedium> > m_llMediums;
5297 StringsList m_llFilesToDelete;
5298
5299 friend void Machine::i_deleteConfigHandler(DeleteConfigTask &task);
5300};
5301
5302/**
5303 * Task thread implementation for SessionMachine::DeleteConfig(), called from
5304 * SessionMachine::taskHandler().
5305 *
5306 * @note Locks this object for writing.
5307 *
5308 * @param task
5309 * @return
5310 */
5311void Machine::i_deleteConfigHandler(DeleteConfigTask &task)
5312{
5313 LogFlowThisFuncEnter();
5314
5315 AutoCaller autoCaller(this);
5316 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
5317 if (FAILED(autoCaller.rc()))
5318 {
5319 /* we might have been uninitialized because the session was accidentally
5320 * closed by the client, so don't assert */
5321 HRESULT rc = setError(E_FAIL,
5322 tr("The session has been accidentally closed"));
5323 task.m_pProgress->i_notifyComplete(rc);
5324 LogFlowThisFuncLeave();
5325 return;
5326 }
5327
5328 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5329
5330 HRESULT rc = S_OK;
5331
5332 try
5333 {
5334 ULONG uLogHistoryCount = 3;
5335 ComPtr<ISystemProperties> systemProperties;
5336 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
5337 if (FAILED(rc)) throw rc;
5338
5339 if (!systemProperties.isNull())
5340 {
5341 rc = systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
5342 if (FAILED(rc)) throw rc;
5343 }
5344
5345 MachineState_T oldState = mData->mMachineState;
5346 i_setMachineState(MachineState_SettingUp);
5347 alock.release();
5348 for (size_t i = 0; i < task.m_llMediums.size(); ++i)
5349 {
5350 ComObjPtr<Medium> pMedium = (Medium*)(IMedium*)(task.m_llMediums.at(i));
5351 {
5352 AutoCaller mac(pMedium);
5353 if (FAILED(mac.rc())) throw mac.rc();
5354 Utf8Str strLocation = pMedium->i_getLocationFull();
5355 LogFunc(("Deleting file %s\n", strLocation.c_str()));
5356 rc = task.m_pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), strLocation.c_str()).raw(), 1);
5357 if (FAILED(rc)) throw rc;
5358 }
5359 if (pMedium->i_isMediumFormatFile())
5360 {
5361 ComPtr<IProgress> pProgress2;
5362 rc = pMedium->DeleteStorage(pProgress2.asOutParam());
5363 if (FAILED(rc)) throw rc;
5364 rc = task.m_pProgress->WaitForAsyncProgressCompletion(pProgress2);
5365 if (FAILED(rc)) throw rc;
5366 /* Check the result of the asynchronous process. */
5367 LONG iRc;
5368 rc = pProgress2->COMGETTER(ResultCode)(&iRc);
5369 if (FAILED(rc)) throw rc;
5370 /* If the thread of the progress object has an error, then
5371 * retrieve the error info from there, or it'll be lost. */
5372 if (FAILED(iRc))
5373 throw setError(ProgressErrorInfo(pProgress2));
5374 }
5375
5376 /* Close the medium, deliberately without checking the return
5377 * code, and without leaving any trace in the error info, as
5378 * a failure here is a very minor issue, which shouldn't happen
5379 * as above we even managed to delete the medium. */
5380 {
5381 ErrorInfoKeeper eik;
5382 pMedium->Close();
5383 }
5384 }
5385 i_setMachineState(oldState);
5386 alock.acquire();
5387
5388 // delete the files pushed on the task list by Machine::Delete()
5389 // (this includes saved states of the machine and snapshots and
5390 // medium storage files from the IMedium list passed in, and the
5391 // machine XML file)
5392 for (StringsList::const_iterator
5393 it = task.m_llFilesToDelete.begin();
5394 it != task.m_llFilesToDelete.end();
5395 ++it)
5396 {
5397 const Utf8Str &strFile = *it;
5398 LogFunc(("Deleting file %s\n", strFile.c_str()));
5399 rc = task.m_pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
5400 if (FAILED(rc)) throw rc;
5401
5402 int vrc = RTFileDelete(strFile.c_str());
5403 if (RT_FAILURE(vrc))
5404 throw setError(VBOX_E_IPRT_ERROR,
5405 tr("Could not delete file '%s' (%Rrc)"), strFile.c_str(), vrc);
5406 }
5407
5408 rc = task.m_pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
5409 if (FAILED(rc)) throw rc;
5410
5411 /* delete the settings only when the file actually exists */
5412 if (mData->pMachineConfigFile->fileExists())
5413 {
5414 /* Delete any backup or uncommitted XML files. Ignore failures.
5415 See the fSafe parameter of xml::XmlFileWriter::write for details. */
5416 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
5417 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
5418 RTFileDelete(otherXml.c_str());
5419 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
5420 RTFileDelete(otherXml.c_str());
5421
5422 /* delete the Logs folder, nothing important should be left
5423 * there (we don't check for errors because the user might have
5424 * some private files there that we don't want to delete) */
5425 Utf8Str logFolder;
5426 getLogFolder(logFolder);
5427 Assert(logFolder.length());
5428 if (RTDirExists(logFolder.c_str()))
5429 {
5430 /* Delete all VBox.log[.N] files from the Logs folder
5431 * (this must be in sync with the rotation logic in
5432 * Console::powerUpThread()). Also, delete the VBox.png[.N]
5433 * files that may have been created by the GUI. */
5434 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
5435 logFolder.c_str(), RTPATH_DELIMITER);
5436 RTFileDelete(log.c_str());
5437 log = Utf8StrFmt("%s%cVBox.png",
5438 logFolder.c_str(), RTPATH_DELIMITER);
5439 RTFileDelete(log.c_str());
5440 for (int i = uLogHistoryCount; i > 0; i--)
5441 {
5442 log = Utf8StrFmt("%s%cVBox.log.%d",
5443 logFolder.c_str(), RTPATH_DELIMITER, i);
5444 RTFileDelete(log.c_str());
5445 log = Utf8StrFmt("%s%cVBox.png.%d",
5446 logFolder.c_str(), RTPATH_DELIMITER, i);
5447 RTFileDelete(log.c_str());
5448 }
5449#if defined(RT_OS_WINDOWS)
5450 log = Utf8StrFmt("%s%cVBoxStartup.log", logFolder.c_str(), RTPATH_DELIMITER);
5451 RTFileDelete(log.c_str());
5452 log = Utf8StrFmt("%s%cVBoxHardening.log", logFolder.c_str(), RTPATH_DELIMITER);
5453 RTFileDelete(log.c_str());
5454#endif
5455
5456 RTDirRemove(logFolder.c_str());
5457 }
5458
5459 /* delete the Snapshots folder, nothing important should be left
5460 * there (we don't check for errors because the user might have
5461 * some private files there that we don't want to delete) */
5462 Utf8Str strFullSnapshotFolder;
5463 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
5464 Assert(!strFullSnapshotFolder.isEmpty());
5465 if (RTDirExists(strFullSnapshotFolder.c_str()))
5466 RTDirRemove(strFullSnapshotFolder.c_str());
5467
5468 // delete the directory that contains the settings file, but only
5469 // if it matches the VM name
5470 Utf8Str settingsDir;
5471 if (i_isInOwnDir(&settingsDir))
5472 RTDirRemove(settingsDir.c_str());
5473 }
5474
5475 alock.release();
5476
5477 mParent->i_saveModifiedRegistries();
5478 }
5479 catch (HRESULT aRC) { rc = aRC; }
5480
5481 task.m_pProgress->i_notifyComplete(rc);
5482
5483 LogFlowThisFuncLeave();
5484}
5485
5486HRESULT Machine::deleteConfig(const std::vector<ComPtr<IMedium> > &aMedia, ComPtr<IProgress> &aProgress)
5487{
5488 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5489
5490 HRESULT rc = i_checkStateDependency(MutableStateDep);
5491 if (FAILED(rc)) return rc;
5492
5493 if (mData->mRegistered)
5494 return setError(VBOX_E_INVALID_VM_STATE,
5495 tr("Cannot delete settings of a registered machine"));
5496
5497 // collect files to delete
5498 StringsList llFilesToDelete(mData->llFilesToDelete); // saved states pushed here by Unregister()
5499 if (mData->pMachineConfigFile->fileExists())
5500 llFilesToDelete.push_back(mData->m_strConfigFileFull);
5501
5502 RTCList<ComPtr<IMedium> > llMediums;
5503 for (size_t i = 0; i < aMedia.size(); ++i)
5504 {
5505 IMedium *pIMedium(aMedia[i]);
5506 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
5507 if (pMedium.isNull())
5508 return setError(E_INVALIDARG, "The given medium pointer with index %d is invalid", i);
5509 SafeArray<BSTR> ids;
5510 rc = pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(ids));
5511 if (FAILED(rc)) return rc;
5512 /* At this point the medium should not have any back references
5513 * anymore. If it has it is attached to another VM and *must* not
5514 * deleted. */
5515 if (ids.size() < 1)
5516 llMediums.append(pMedium);
5517 }
5518
5519 ComObjPtr<Progress> pProgress;
5520 pProgress.createObject();
5521 rc = pProgress->init(i_getVirtualBox(),
5522 static_cast<IMachine*>(this) /* aInitiator */,
5523 tr("Deleting files"),
5524 true /* fCancellable */,
5525 (ULONG)(1 + llMediums.size() + llFilesToDelete.size() + 1), // cOperations
5526 tr("Collecting file inventory"));
5527 if (FAILED(rc))
5528 return rc;
5529
5530 /* create and start the task on a separate thread (note that it will not
5531 * start working until we release alock) */
5532 DeleteConfigTask *pTask = new DeleteConfigTask(this, pProgress, "DeleteVM", llMediums, llFilesToDelete);
5533 rc = pTask->createThread();
5534 if (FAILED(rc))
5535 return rc;
5536
5537 pProgress.queryInterfaceTo(aProgress.asOutParam());
5538
5539 LogFlowFuncLeave();
5540
5541 return S_OK;
5542}
5543
5544HRESULT Machine::findSnapshot(const com::Utf8Str &aNameOrId, ComPtr<ISnapshot> &aSnapshot)
5545{
5546 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5547
5548 ComObjPtr<Snapshot> pSnapshot;
5549 HRESULT rc;
5550
5551 if (aNameOrId.isEmpty())
5552 // null case (caller wants root snapshot): i_findSnapshotById() handles this
5553 rc = i_findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
5554 else
5555 {
5556 Guid uuid(aNameOrId);
5557 if (uuid.isValid())
5558 rc = i_findSnapshotById(uuid, pSnapshot, true /* aSetError */);
5559 else
5560 rc = i_findSnapshotByName(aNameOrId, pSnapshot, true /* aSetError */);
5561 }
5562 pSnapshot.queryInterfaceTo(aSnapshot.asOutParam());
5563
5564 return rc;
5565}
5566
5567HRESULT Machine::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable, BOOL aAutomount)
5568{
5569 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5570
5571 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
5572 if (FAILED(rc)) return rc;
5573
5574 ComObjPtr<SharedFolder> sharedFolder;
5575 rc = i_findSharedFolder(aName, sharedFolder, false /* aSetError */);
5576 if (SUCCEEDED(rc))
5577 return setError(VBOX_E_OBJECT_IN_USE,
5578 tr("Shared folder named '%s' already exists"),
5579 aName.c_str());
5580
5581 sharedFolder.createObject();
5582 rc = sharedFolder->init(i_getMachine(),
5583 aName,
5584 aHostPath,
5585 !!aWritable,
5586 !!aAutomount,
5587 true /* fFailOnError */);
5588 if (FAILED(rc)) return rc;
5589
5590 i_setModified(IsModified_SharedFolders);
5591 mHWData.backup();
5592 mHWData->mSharedFolders.push_back(sharedFolder);
5593
5594 /* inform the direct session if any */
5595 alock.release();
5596 i_onSharedFolderChange();
5597
5598 return S_OK;
5599}
5600
5601HRESULT Machine::removeSharedFolder(const com::Utf8Str &aName)
5602{
5603 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5604
5605 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
5606 if (FAILED(rc)) return rc;
5607
5608 ComObjPtr<SharedFolder> sharedFolder;
5609 rc = i_findSharedFolder(aName, sharedFolder, true /* aSetError */);
5610 if (FAILED(rc)) return rc;
5611
5612 i_setModified(IsModified_SharedFolders);
5613 mHWData.backup();
5614 mHWData->mSharedFolders.remove(sharedFolder);
5615
5616 /* inform the direct session if any */
5617 alock.release();
5618 i_onSharedFolderChange();
5619
5620 return S_OK;
5621}
5622
5623HRESULT Machine::canShowConsoleWindow(BOOL *aCanShow)
5624{
5625 /* start with No */
5626 *aCanShow = FALSE;
5627
5628 ComPtr<IInternalSessionControl> directControl;
5629 {
5630 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5631
5632 if (mData->mSession.mState != SessionState_Locked)
5633 return setError(VBOX_E_INVALID_VM_STATE,
5634 tr("Machine is not locked for session (session state: %s)"),
5635 Global::stringifySessionState(mData->mSession.mState));
5636
5637 if (mData->mSession.mLockType == LockType_VM)
5638 directControl = mData->mSession.mDirectControl;
5639 }
5640
5641 /* ignore calls made after #OnSessionEnd() is called */
5642 if (!directControl)
5643 return S_OK;
5644
5645 LONG64 dummy;
5646 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
5647}
5648
5649HRESULT Machine::showConsoleWindow(LONG64 *aWinId)
5650{
5651 ComPtr<IInternalSessionControl> directControl;
5652 {
5653 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5654
5655 if (mData->mSession.mState != SessionState_Locked)
5656 return setError(E_FAIL,
5657 tr("Machine is not locked for session (session state: %s)"),
5658 Global::stringifySessionState(mData->mSession.mState));
5659
5660 if (mData->mSession.mLockType == LockType_VM)
5661 directControl = mData->mSession.mDirectControl;
5662 }
5663
5664 /* ignore calls made after #OnSessionEnd() is called */
5665 if (!directControl)
5666 return S_OK;
5667
5668 BOOL dummy;
5669 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
5670}
5671
5672#ifdef VBOX_WITH_GUEST_PROPS
5673/**
5674 * Look up a guest property in VBoxSVC's internal structures.
5675 */
5676HRESULT Machine::i_getGuestPropertyFromService(const com::Utf8Str &aName,
5677 com::Utf8Str &aValue,
5678 LONG64 *aTimestamp,
5679 com::Utf8Str &aFlags) const
5680{
5681 using namespace guestProp;
5682
5683 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5684 HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.find(aName);
5685
5686 if (it != mHWData->mGuestProperties.end())
5687 {
5688 char szFlags[MAX_FLAGS_LEN + 1];
5689 aValue = it->second.strValue;
5690 *aTimestamp = it->second.mTimestamp;
5691 writeFlags(it->second.mFlags, szFlags);
5692 aFlags = Utf8Str(szFlags);
5693 }
5694
5695 return S_OK;
5696}
5697
5698/**
5699 * Query the VM that a guest property belongs to for the property.
5700 * @returns E_ACCESSDENIED if the VM process is not available or not
5701 * currently handling queries and the lookup should then be done in
5702 * VBoxSVC.
5703 */
5704HRESULT Machine::i_getGuestPropertyFromVM(const com::Utf8Str &aName,
5705 com::Utf8Str &aValue,
5706 LONG64 *aTimestamp,
5707 com::Utf8Str &aFlags) const
5708{
5709 HRESULT rc = S_OK;
5710 BSTR bValue = NULL;
5711 BSTR bFlags = NULL;
5712
5713 ComPtr<IInternalSessionControl> directControl;
5714 {
5715 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5716 if (mData->mSession.mLockType == LockType_VM)
5717 directControl = mData->mSession.mDirectControl;
5718 }
5719
5720 /* ignore calls made after #OnSessionEnd() is called */
5721 if (!directControl)
5722 rc = E_ACCESSDENIED;
5723 else
5724 rc = directControl->AccessGuestProperty(Bstr(aName).raw(), Bstr::Empty.raw(), Bstr::Empty.raw(),
5725 0 /* accessMode */,
5726 &bValue, aTimestamp, &bFlags);
5727
5728 aValue = bValue;
5729 aFlags = bFlags;
5730
5731 return rc;
5732}
5733#endif // VBOX_WITH_GUEST_PROPS
5734
5735HRESULT Machine::getGuestProperty(const com::Utf8Str &aName,
5736 com::Utf8Str &aValue,
5737 LONG64 *aTimestamp,
5738 com::Utf8Str &aFlags)
5739{
5740#ifndef VBOX_WITH_GUEST_PROPS
5741 ReturnComNotImplemented();
5742#else // VBOX_WITH_GUEST_PROPS
5743
5744 HRESULT rc = i_getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
5745
5746 if (rc == E_ACCESSDENIED)
5747 /* The VM is not running or the service is not (yet) accessible */
5748 rc = i_getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
5749 return rc;
5750#endif // VBOX_WITH_GUEST_PROPS
5751}
5752
5753HRESULT Machine::getGuestPropertyValue(const com::Utf8Str &aProperty, com::Utf8Str &aValue)
5754{
5755 LONG64 dummyTimestamp;
5756 com::Utf8Str dummyFlags;
5757 HRESULT rc = getGuestProperty(aProperty, aValue, &dummyTimestamp, dummyFlags);
5758 return rc;
5759
5760}
5761HRESULT Machine::getGuestPropertyTimestamp(const com::Utf8Str &aProperty, LONG64 *aValue)
5762{
5763 com::Utf8Str dummyFlags;
5764 com::Utf8Str dummyValue;
5765 HRESULT rc = getGuestProperty(aProperty, dummyValue, aValue, dummyFlags);
5766 return rc;
5767}
5768
5769#ifdef VBOX_WITH_GUEST_PROPS
5770/**
5771 * Set a guest property in VBoxSVC's internal structures.
5772 */
5773HRESULT Machine::i_setGuestPropertyToService(const com::Utf8Str &aName, const com::Utf8Str &aValue,
5774 const com::Utf8Str &aFlags, bool fDelete)
5775{
5776 using namespace guestProp;
5777
5778 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5779 HRESULT rc = S_OK;
5780
5781 rc = i_checkStateDependency(MutableOrSavedStateDep);
5782 if (FAILED(rc)) return rc;
5783
5784 try
5785 {
5786 uint32_t fFlags = NILFLAG;
5787 if (aFlags.length() && RT_FAILURE(validateFlags(aFlags.c_str(), &fFlags)))
5788 return setError(E_INVALIDARG, tr("Invalid guest property flag values: '%s'"), aFlags.c_str());
5789
5790 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
5791 if (it == mHWData->mGuestProperties.end())
5792 {
5793 if (!fDelete)
5794 {
5795 i_setModified(IsModified_MachineData);
5796 mHWData.backupEx();
5797
5798 RTTIMESPEC time;
5799 HWData::GuestProperty prop;
5800 prop.strValue = Bstr(aValue).raw();
5801 prop.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5802 prop.mFlags = fFlags;
5803 mHWData->mGuestProperties[aName] = prop;
5804 }
5805 }
5806 else
5807 {
5808 if (it->second.mFlags & (RDONLYHOST))
5809 {
5810 rc = setError(E_ACCESSDENIED, tr("The property '%s' cannot be changed by the host"), aName.c_str());
5811 }
5812 else
5813 {
5814 i_setModified(IsModified_MachineData);
5815 mHWData.backupEx();
5816
5817 /* The backupEx() operation invalidates our iterator,
5818 * so get a new one. */
5819 it = mHWData->mGuestProperties.find(aName);
5820 Assert(it != mHWData->mGuestProperties.end());
5821
5822 if (!fDelete)
5823 {
5824 RTTIMESPEC time;
5825 it->second.strValue = aValue;
5826 it->second.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5827 it->second.mFlags = fFlags;
5828 }
5829 else
5830 mHWData->mGuestProperties.erase(it);
5831 }
5832 }
5833
5834 if (SUCCEEDED(rc))
5835 {
5836 alock.release();
5837
5838 mParent->i_onGuestPropertyChange(mData->mUuid,
5839 Bstr(aName).raw(),
5840 Bstr(aValue).raw(),
5841 Bstr(aFlags).raw());
5842 }
5843 }
5844 catch (std::bad_alloc &)
5845 {
5846 rc = E_OUTOFMEMORY;
5847 }
5848
5849 return rc;
5850}
5851
5852/**
5853 * Set a property on the VM that that property belongs to.
5854 * @returns E_ACCESSDENIED if the VM process is not available or not
5855 * currently handling queries and the setting should then be done in
5856 * VBoxSVC.
5857 */
5858HRESULT Machine::i_setGuestPropertyToVM(const com::Utf8Str &aName, const com::Utf8Str &aValue,
5859 const com::Utf8Str &aFlags, bool fDelete)
5860{
5861 HRESULT rc;
5862
5863 try
5864 {
5865 ComPtr<IInternalSessionControl> directControl;
5866 {
5867 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5868 if (mData->mSession.mLockType == LockType_VM)
5869 directControl = mData->mSession.mDirectControl;
5870 }
5871
5872 BSTR dummy = NULL; /* will not be changed (setter) */
5873 LONG64 dummy64;
5874 if (!directControl)
5875 rc = E_ACCESSDENIED;
5876 else
5877 /** @todo Fix when adding DeleteGuestProperty(), see defect. */
5878 rc = directControl->AccessGuestProperty(Bstr(aName).raw(), Bstr(aValue).raw(), Bstr(aFlags).raw(),
5879 fDelete? 2: 1 /* accessMode */,
5880 &dummy, &dummy64, &dummy);
5881 }
5882 catch (std::bad_alloc &)
5883 {
5884 rc = E_OUTOFMEMORY;
5885 }
5886
5887 return rc;
5888}
5889#endif // VBOX_WITH_GUEST_PROPS
5890
5891HRESULT Machine::setGuestProperty(const com::Utf8Str &aProperty, const com::Utf8Str &aValue,
5892 const com::Utf8Str &aFlags)
5893{
5894#ifndef VBOX_WITH_GUEST_PROPS
5895 ReturnComNotImplemented();
5896#else // VBOX_WITH_GUEST_PROPS
5897 HRESULT rc = i_setGuestPropertyToVM(aProperty, aValue, aFlags, /* fDelete = */ false);
5898 if (rc == E_ACCESSDENIED)
5899 /* The VM is not running or the service is not (yet) accessible */
5900 rc = i_setGuestPropertyToService(aProperty, aValue, aFlags, /* fDelete = */ false);
5901 return rc;
5902#endif // VBOX_WITH_GUEST_PROPS
5903}
5904
5905HRESULT Machine::setGuestPropertyValue(const com::Utf8Str &aProperty, const com::Utf8Str &aValue)
5906{
5907 return setGuestProperty(aProperty, aValue, "");
5908}
5909
5910HRESULT Machine::deleteGuestProperty(const com::Utf8Str &aName)
5911{
5912#ifndef VBOX_WITH_GUEST_PROPS
5913 ReturnComNotImplemented();
5914#else // VBOX_WITH_GUEST_PROPS
5915 HRESULT rc = i_setGuestPropertyToVM(aName, "", "", /* fDelete = */ true);
5916 if (rc == E_ACCESSDENIED)
5917 /* The VM is not running or the service is not (yet) accessible */
5918 rc = i_setGuestPropertyToService(aName, "", "", /* fDelete = */ true);
5919 return rc;
5920#endif // VBOX_WITH_GUEST_PROPS
5921}
5922
5923#ifdef VBOX_WITH_GUEST_PROPS
5924/**
5925 * Enumerate the guest properties in VBoxSVC's internal structures.
5926 */
5927HRESULT Machine::i_enumerateGuestPropertiesInService(const com::Utf8Str &aPatterns,
5928 std::vector<com::Utf8Str> &aNames,
5929 std::vector<com::Utf8Str> &aValues,
5930 std::vector<LONG64> &aTimestamps,
5931 std::vector<com::Utf8Str> &aFlags)
5932{
5933 using namespace guestProp;
5934
5935 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5936 Utf8Str strPatterns(aPatterns);
5937
5938 HWData::GuestPropertyMap propMap;
5939
5940 /*
5941 * Look for matching patterns and build up a list.
5942 */
5943 for (HWData::GuestPropertyMap::const_iterator
5944 it = mHWData->mGuestProperties.begin();
5945 it != mHWData->mGuestProperties.end();
5946 ++it)
5947 {
5948 if ( strPatterns.isEmpty()
5949 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5950 RTSTR_MAX,
5951 it->first.c_str(),
5952 RTSTR_MAX,
5953 NULL)
5954 )
5955 propMap.insert(*it);
5956 }
5957
5958 alock.release();
5959
5960 /*
5961 * And build up the arrays for returning the property information.
5962 */
5963 size_t cEntries = propMap.size();
5964
5965 aNames.resize(cEntries);
5966 aValues.resize(cEntries);
5967 aTimestamps.resize(cEntries);
5968 aFlags.resize(cEntries);
5969
5970 char szFlags[MAX_FLAGS_LEN + 1];
5971 size_t i = 0;
5972 for (HWData::GuestPropertyMap::const_iterator
5973 it = propMap.begin();
5974 it != propMap.end();
5975 ++it, ++i)
5976 {
5977 aNames[i] = it->first;
5978 aValues[i] = it->second.strValue;
5979 aTimestamps[i] = it->second.mTimestamp;
5980 writeFlags(it->second.mFlags, szFlags);
5981 aFlags[i] = Utf8Str(szFlags);
5982 }
5983
5984 return S_OK;
5985}
5986
5987/**
5988 * Enumerate the properties managed by a VM.
5989 * @returns E_ACCESSDENIED if the VM process is not available or not
5990 * currently handling queries and the setting should then be done in
5991 * VBoxSVC.
5992 */
5993HRESULT Machine::i_enumerateGuestPropertiesOnVM(const com::Utf8Str &aPatterns,
5994 std::vector<com::Utf8Str> &aNames,
5995 std::vector<com::Utf8Str> &aValues,
5996 std::vector<LONG64> &aTimestamps,
5997 std::vector<com::Utf8Str> &aFlags)
5998{
5999 HRESULT rc;
6000 ComPtr<IInternalSessionControl> directControl;
6001 {
6002 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6003 if (mData->mSession.mLockType == LockType_VM)
6004 directControl = mData->mSession.mDirectControl;
6005 }
6006
6007 com::SafeArray<BSTR> bNames;
6008 com::SafeArray<BSTR> bValues;
6009 com::SafeArray<LONG64> bTimestamps;
6010 com::SafeArray<BSTR> bFlags;
6011
6012 if (!directControl)
6013 rc = E_ACCESSDENIED;
6014 else
6015 rc = directControl->EnumerateGuestProperties(Bstr(aPatterns).raw(),
6016 ComSafeArrayAsOutParam(bNames),
6017 ComSafeArrayAsOutParam(bValues),
6018 ComSafeArrayAsOutParam(bTimestamps),
6019 ComSafeArrayAsOutParam(bFlags));
6020 size_t i;
6021 aNames.resize(bNames.size());
6022 for (i = 0; i < bNames.size(); ++i)
6023 aNames[i] = Utf8Str(bNames[i]);
6024 aValues.resize(bValues.size());
6025 for (i = 0; i < bValues.size(); ++i)
6026 aValues[i] = Utf8Str(bValues[i]);
6027 aTimestamps.resize(bTimestamps.size());
6028 for (i = 0; i < bTimestamps.size(); ++i)
6029 aTimestamps[i] = bTimestamps[i];
6030 aFlags.resize(bFlags.size());
6031 for (i = 0; i < bFlags.size(); ++i)
6032 aFlags[i] = Utf8Str(bFlags[i]);
6033
6034 return rc;
6035}
6036#endif // VBOX_WITH_GUEST_PROPS
6037HRESULT Machine::enumerateGuestProperties(const com::Utf8Str &aPatterns,
6038 std::vector<com::Utf8Str> &aNames,
6039 std::vector<com::Utf8Str> &aValues,
6040 std::vector<LONG64> &aTimestamps,
6041 std::vector<com::Utf8Str> &aFlags)
6042{
6043#ifndef VBOX_WITH_GUEST_PROPS
6044 ReturnComNotImplemented();
6045#else // VBOX_WITH_GUEST_PROPS
6046
6047 HRESULT rc = i_enumerateGuestPropertiesOnVM(aPatterns, aNames, aValues, aTimestamps, aFlags);
6048
6049 if (rc == E_ACCESSDENIED)
6050 /* The VM is not running or the service is not (yet) accessible */
6051 rc = i_enumerateGuestPropertiesInService(aPatterns, aNames, aValues, aTimestamps, aFlags);
6052 return rc;
6053#endif // VBOX_WITH_GUEST_PROPS
6054}
6055
6056HRESULT Machine::getMediumAttachmentsOfController(const com::Utf8Str &aName,
6057 std::vector<ComPtr<IMediumAttachment> > &aMediumAttachments)
6058{
6059 MediumAttachmentList atts;
6060
6061 HRESULT rc = i_getMediumAttachmentsOfController(aName, atts);
6062 if (FAILED(rc)) return rc;
6063
6064 aMediumAttachments.resize(atts.size());
6065 size_t i = 0;
6066 for (MediumAttachmentList::const_iterator
6067 it = atts.begin();
6068 it != atts.end();
6069 ++it, ++i)
6070 (*it).queryInterfaceTo(aMediumAttachments[i].asOutParam());
6071
6072 return S_OK;
6073}
6074
6075HRESULT Machine::getMediumAttachment(const com::Utf8Str &aName,
6076 LONG aControllerPort,
6077 LONG aDevice,
6078 ComPtr<IMediumAttachment> &aAttachment)
6079{
6080 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
6081 aName.c_str(), aControllerPort, aDevice));
6082
6083 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6084
6085 aAttachment = NULL;
6086
6087 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(*mMediumAttachments.data(),
6088 aName,
6089 aControllerPort,
6090 aDevice);
6091 if (pAttach.isNull())
6092 return setError(VBOX_E_OBJECT_NOT_FOUND,
6093 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
6094 aDevice, aControllerPort, aName.c_str());
6095
6096 pAttach.queryInterfaceTo(aAttachment.asOutParam());
6097
6098 return S_OK;
6099}
6100
6101
6102HRESULT Machine::addStorageController(const com::Utf8Str &aName,
6103 StorageBus_T aConnectionType,
6104 ComPtr<IStorageController> &aController)
6105{
6106 if ( (aConnectionType <= StorageBus_Null)
6107 || (aConnectionType > StorageBus_PCIe))
6108 return setError(E_INVALIDARG,
6109 tr("Invalid connection type: %d"),
6110 aConnectionType);
6111
6112 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6113
6114 HRESULT rc = i_checkStateDependency(MutableStateDep);
6115 if (FAILED(rc)) return rc;
6116
6117 /* try to find one with the name first. */
6118 ComObjPtr<StorageController> ctrl;
6119
6120 rc = i_getStorageControllerByName(aName, ctrl, false /* aSetError */);
6121 if (SUCCEEDED(rc))
6122 return setError(VBOX_E_OBJECT_IN_USE,
6123 tr("Storage controller named '%s' already exists"),
6124 aName.c_str());
6125
6126 ctrl.createObject();
6127
6128 /* get a new instance number for the storage controller */
6129 ULONG ulInstance = 0;
6130 bool fBootable = true;
6131 for (StorageControllerList::const_iterator
6132 it = mStorageControllers->begin();
6133 it != mStorageControllers->end();
6134 ++it)
6135 {
6136 if ((*it)->i_getStorageBus() == aConnectionType)
6137 {
6138 ULONG ulCurInst = (*it)->i_getInstance();
6139
6140 if (ulCurInst >= ulInstance)
6141 ulInstance = ulCurInst + 1;
6142
6143 /* Only one controller of each type can be marked as bootable. */
6144 if ((*it)->i_getBootable())
6145 fBootable = false;
6146 }
6147 }
6148
6149 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
6150 if (FAILED(rc)) return rc;
6151
6152 i_setModified(IsModified_Storage);
6153 mStorageControllers.backup();
6154 mStorageControllers->push_back(ctrl);
6155
6156 ctrl.queryInterfaceTo(aController.asOutParam());
6157
6158 /* inform the direct session if any */
6159 alock.release();
6160 i_onStorageControllerChange();
6161
6162 return S_OK;
6163}
6164
6165HRESULT Machine::getStorageControllerByName(const com::Utf8Str &aName,
6166 ComPtr<IStorageController> &aStorageController)
6167{
6168 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6169
6170 ComObjPtr<StorageController> ctrl;
6171
6172 HRESULT rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6173 if (SUCCEEDED(rc))
6174 ctrl.queryInterfaceTo(aStorageController.asOutParam());
6175
6176 return rc;
6177}
6178
6179HRESULT Machine::getStorageControllerByInstance(StorageBus_T aConnectionType,
6180 ULONG aInstance,
6181 ComPtr<IStorageController> &aStorageController)
6182{
6183 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6184
6185 for (StorageControllerList::const_iterator
6186 it = mStorageControllers->begin();
6187 it != mStorageControllers->end();
6188 ++it)
6189 {
6190 if ( (*it)->i_getStorageBus() == aConnectionType
6191 && (*it)->i_getInstance() == aInstance)
6192 {
6193 (*it).queryInterfaceTo(aStorageController.asOutParam());
6194 return S_OK;
6195 }
6196 }
6197
6198 return setError(VBOX_E_OBJECT_NOT_FOUND,
6199 tr("Could not find a storage controller with instance number '%lu'"),
6200 aInstance);
6201}
6202
6203HRESULT Machine::setStorageControllerBootable(const com::Utf8Str &aName, BOOL aBootable)
6204{
6205 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6206
6207 HRESULT rc = i_checkStateDependency(MutableStateDep);
6208 if (FAILED(rc)) return rc;
6209
6210 ComObjPtr<StorageController> ctrl;
6211
6212 rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6213 if (SUCCEEDED(rc))
6214 {
6215 /* Ensure that only one controller of each type is marked as bootable. */
6216 if (aBootable == TRUE)
6217 {
6218 for (StorageControllerList::const_iterator
6219 it = mStorageControllers->begin();
6220 it != mStorageControllers->end();
6221 ++it)
6222 {
6223 ComObjPtr<StorageController> aCtrl = (*it);
6224
6225 if ( (aCtrl->i_getName() != aName)
6226 && aCtrl->i_getBootable() == TRUE
6227 && aCtrl->i_getStorageBus() == ctrl->i_getStorageBus()
6228 && aCtrl->i_getControllerType() == ctrl->i_getControllerType())
6229 {
6230 aCtrl->i_setBootable(FALSE);
6231 break;
6232 }
6233 }
6234 }
6235
6236 if (SUCCEEDED(rc))
6237 {
6238 ctrl->i_setBootable(aBootable);
6239 i_setModified(IsModified_Storage);
6240 }
6241 }
6242
6243 if (SUCCEEDED(rc))
6244 {
6245 /* inform the direct session if any */
6246 alock.release();
6247 i_onStorageControllerChange();
6248 }
6249
6250 return rc;
6251}
6252
6253HRESULT Machine::removeStorageController(const com::Utf8Str &aName)
6254{
6255 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6256
6257 HRESULT rc = i_checkStateDependency(MutableStateDep);
6258 if (FAILED(rc)) return rc;
6259
6260 ComObjPtr<StorageController> ctrl;
6261 rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6262 if (FAILED(rc)) return rc;
6263
6264 {
6265 /* find all attached devices to the appropriate storage controller and detach them all */
6266 // make a temporary list because detachDevice invalidates iterators into
6267 // mMediumAttachments
6268 MediumAttachmentList llAttachments2 = *mMediumAttachments.data();
6269
6270 for (MediumAttachmentList::const_iterator
6271 it = llAttachments2.begin();
6272 it != llAttachments2.end();
6273 ++it)
6274 {
6275 MediumAttachment *pAttachTemp = *it;
6276
6277 AutoCaller localAutoCaller(pAttachTemp);
6278 if (FAILED(localAutoCaller.rc())) return localAutoCaller.rc();
6279
6280 AutoReadLock local_alock(pAttachTemp COMMA_LOCKVAL_SRC_POS);
6281
6282 if (pAttachTemp->i_getControllerName() == aName)
6283 {
6284 rc = i_detachDevice(pAttachTemp, alock, NULL);
6285 if (FAILED(rc)) return rc;
6286 }
6287 }
6288 }
6289
6290 /* We can remove it now. */
6291 i_setModified(IsModified_Storage);
6292 mStorageControllers.backup();
6293
6294 ctrl->i_unshare();
6295
6296 mStorageControllers->remove(ctrl);
6297
6298 /* inform the direct session if any */
6299 alock.release();
6300 i_onStorageControllerChange();
6301
6302 return S_OK;
6303}
6304
6305HRESULT Machine::addUSBController(const com::Utf8Str &aName, USBControllerType_T aType,
6306 ComPtr<IUSBController> &aController)
6307{
6308 if ( (aType <= USBControllerType_Null)
6309 || (aType >= USBControllerType_Last))
6310 return setError(E_INVALIDARG,
6311 tr("Invalid USB controller type: %d"),
6312 aType);
6313
6314 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6315
6316 HRESULT rc = i_checkStateDependency(MutableStateDep);
6317 if (FAILED(rc)) return rc;
6318
6319 /* try to find one with the same type first. */
6320 ComObjPtr<USBController> ctrl;
6321
6322 rc = i_getUSBControllerByName(aName, ctrl, false /* aSetError */);
6323 if (SUCCEEDED(rc))
6324 return setError(VBOX_E_OBJECT_IN_USE,
6325 tr("USB controller named '%s' already exists"),
6326 aName.c_str());
6327
6328 /* Check that we don't exceed the maximum number of USB controllers for the given type. */
6329 ULONG maxInstances;
6330 rc = mParent->i_getSystemProperties()->GetMaxInstancesOfUSBControllerType(mHWData->mChipsetType, aType, &maxInstances);
6331 if (FAILED(rc))
6332 return rc;
6333
6334 ULONG cInstances = i_getUSBControllerCountByType(aType);
6335 if (cInstances >= maxInstances)
6336 return setError(E_INVALIDARG,
6337 tr("Too many USB controllers of this type"));
6338
6339 ctrl.createObject();
6340
6341 rc = ctrl->init(this, aName, aType);
6342 if (FAILED(rc)) return rc;
6343
6344 i_setModified(IsModified_USB);
6345 mUSBControllers.backup();
6346 mUSBControllers->push_back(ctrl);
6347
6348 ctrl.queryInterfaceTo(aController.asOutParam());
6349
6350 /* inform the direct session if any */
6351 alock.release();
6352 i_onUSBControllerChange();
6353
6354 return S_OK;
6355}
6356
6357HRESULT Machine::getUSBControllerByName(const com::Utf8Str &aName, ComPtr<IUSBController> &aController)
6358{
6359 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6360
6361 ComObjPtr<USBController> ctrl;
6362
6363 HRESULT rc = i_getUSBControllerByName(aName, ctrl, true /* aSetError */);
6364 if (SUCCEEDED(rc))
6365 ctrl.queryInterfaceTo(aController.asOutParam());
6366
6367 return rc;
6368}
6369
6370HRESULT Machine::getUSBControllerCountByType(USBControllerType_T aType,
6371 ULONG *aControllers)
6372{
6373 if ( (aType <= USBControllerType_Null)
6374 || (aType >= USBControllerType_Last))
6375 return setError(E_INVALIDARG,
6376 tr("Invalid USB controller type: %d"),
6377 aType);
6378
6379 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6380
6381 ComObjPtr<USBController> ctrl;
6382
6383 *aControllers = i_getUSBControllerCountByType(aType);
6384
6385 return S_OK;
6386}
6387
6388HRESULT Machine::removeUSBController(const com::Utf8Str &aName)
6389{
6390
6391 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6392
6393 HRESULT rc = i_checkStateDependency(MutableStateDep);
6394 if (FAILED(rc)) return rc;
6395
6396 ComObjPtr<USBController> ctrl;
6397 rc = i_getUSBControllerByName(aName, ctrl, true /* aSetError */);
6398 if (FAILED(rc)) return rc;
6399
6400 i_setModified(IsModified_USB);
6401 mUSBControllers.backup();
6402
6403 ctrl->i_unshare();
6404
6405 mUSBControllers->remove(ctrl);
6406
6407 /* inform the direct session if any */
6408 alock.release();
6409 i_onUSBControllerChange();
6410
6411 return S_OK;
6412}
6413
6414HRESULT Machine::querySavedGuestScreenInfo(ULONG aScreenId,
6415 ULONG *aOriginX,
6416 ULONG *aOriginY,
6417 ULONG *aWidth,
6418 ULONG *aHeight,
6419 BOOL *aEnabled)
6420{
6421 uint32_t u32OriginX= 0;
6422 uint32_t u32OriginY= 0;
6423 uint32_t u32Width = 0;
6424 uint32_t u32Height = 0;
6425 uint16_t u16Flags = 0;
6426
6427 int vrc = readSavedGuestScreenInfo(mSSData->strStateFilePath, aScreenId,
6428 &u32OriginX, &u32OriginY, &u32Width, &u32Height, &u16Flags);
6429 if (RT_FAILURE(vrc))
6430 {
6431#ifdef RT_OS_WINDOWS
6432 /* HACK: GUI sets *pfEnabled to 'true' and expects it to stay so if the API fails.
6433 * This works with XPCOM. But Windows COM sets all output parameters to zero.
6434 * So just assign fEnable to TRUE again.
6435 * The right fix would be to change GUI API wrappers to make sure that parameters
6436 * are changed only if API succeeds.
6437 */
6438 *aEnabled = TRUE;
6439#endif
6440 return setError(VBOX_E_IPRT_ERROR,
6441 tr("Saved guest size is not available (%Rrc)"),
6442 vrc);
6443 }
6444
6445 *aOriginX = u32OriginX;
6446 *aOriginY = u32OriginY;
6447 *aWidth = u32Width;
6448 *aHeight = u32Height;
6449 *aEnabled = (u16Flags & VBVA_SCREEN_F_DISABLED) == 0;
6450
6451 return S_OK;
6452}
6453
6454HRESULT Machine::readSavedThumbnailToArray(ULONG aScreenId, BitmapFormat_T aBitmapFormat,
6455 ULONG *aWidth, ULONG *aHeight, std::vector<BYTE> &aData)
6456{
6457 if (aScreenId != 0)
6458 return E_NOTIMPL;
6459
6460 if ( aBitmapFormat != BitmapFormat_BGR0
6461 && aBitmapFormat != BitmapFormat_BGRA
6462 && aBitmapFormat != BitmapFormat_RGBA
6463 && aBitmapFormat != BitmapFormat_PNG)
6464 return setError(E_NOTIMPL,
6465 tr("Unsupported saved thumbnail format 0x%08X"), aBitmapFormat);
6466
6467 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6468
6469 uint8_t *pu8Data = NULL;
6470 uint32_t cbData = 0;
6471 uint32_t u32Width = 0;
6472 uint32_t u32Height = 0;
6473
6474 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6475
6476 if (RT_FAILURE(vrc))
6477 return setError(VBOX_E_IPRT_ERROR,
6478 tr("Saved thumbnail data is not available (%Rrc)"),
6479 vrc);
6480
6481 HRESULT hr = S_OK;
6482
6483 *aWidth = u32Width;
6484 *aHeight = u32Height;
6485
6486 if (cbData > 0)
6487 {
6488 /* Convert pixels to the format expected by the API caller. */
6489 if (aBitmapFormat == BitmapFormat_BGR0)
6490 {
6491 /* [0] B, [1] G, [2] R, [3] 0. */
6492 aData.resize(cbData);
6493 memcpy(&aData.front(), pu8Data, cbData);
6494 }
6495 else if (aBitmapFormat == BitmapFormat_BGRA)
6496 {
6497 /* [0] B, [1] G, [2] R, [3] A. */
6498 aData.resize(cbData);
6499 for (uint32_t i = 0; i < cbData; i += 4)
6500 {
6501 aData[i] = pu8Data[i];
6502 aData[i + 1] = pu8Data[i + 1];
6503 aData[i + 2] = pu8Data[i + 2];
6504 aData[i + 3] = 0xff;
6505 }
6506 }
6507 else if (aBitmapFormat == BitmapFormat_RGBA)
6508 {
6509 /* [0] R, [1] G, [2] B, [3] A. */
6510 aData.resize(cbData);
6511 for (uint32_t i = 0; i < cbData; i += 4)
6512 {
6513 aData[i] = pu8Data[i + 2];
6514 aData[i + 1] = pu8Data[i + 1];
6515 aData[i + 2] = pu8Data[i];
6516 aData[i + 3] = 0xff;
6517 }
6518 }
6519 else if (aBitmapFormat == BitmapFormat_PNG)
6520 {
6521 uint8_t *pu8PNG = NULL;
6522 uint32_t cbPNG = 0;
6523 uint32_t cxPNG = 0;
6524 uint32_t cyPNG = 0;
6525
6526 vrc = DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
6527
6528 if (RT_SUCCESS(vrc))
6529 {
6530 aData.resize(cbPNG);
6531 if (cbPNG)
6532 memcpy(&aData.front(), pu8PNG, cbPNG);
6533 }
6534 else
6535 hr = setError(VBOX_E_IPRT_ERROR,
6536 tr("Could not convert saved thumbnail to PNG (%Rrc)"),
6537 vrc);
6538
6539 RTMemFree(pu8PNG);
6540 }
6541 }
6542
6543 freeSavedDisplayScreenshot(pu8Data);
6544
6545 return hr;
6546}
6547
6548HRESULT Machine::querySavedScreenshotInfo(ULONG aScreenId,
6549 ULONG *aWidth,
6550 ULONG *aHeight,
6551 std::vector<BitmapFormat_T> &aBitmapFormats)
6552{
6553 if (aScreenId != 0)
6554 return E_NOTIMPL;
6555
6556 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6557
6558 uint8_t *pu8Data = NULL;
6559 uint32_t cbData = 0;
6560 uint32_t u32Width = 0;
6561 uint32_t u32Height = 0;
6562
6563 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6564
6565 if (RT_FAILURE(vrc))
6566 return setError(VBOX_E_IPRT_ERROR,
6567 tr("Saved screenshot data is not available (%Rrc)"),
6568 vrc);
6569
6570 *aWidth = u32Width;
6571 *aHeight = u32Height;
6572 aBitmapFormats.resize(1);
6573 aBitmapFormats[0] = BitmapFormat_PNG;
6574
6575 freeSavedDisplayScreenshot(pu8Data);
6576
6577 return S_OK;
6578}
6579
6580HRESULT Machine::readSavedScreenshotToArray(ULONG aScreenId,
6581 BitmapFormat_T aBitmapFormat,
6582 ULONG *aWidth,
6583 ULONG *aHeight,
6584 std::vector<BYTE> &aData)
6585{
6586 if (aScreenId != 0)
6587 return E_NOTIMPL;
6588
6589 if (aBitmapFormat != BitmapFormat_PNG)
6590 return E_NOTIMPL;
6591
6592 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6593
6594 uint8_t *pu8Data = NULL;
6595 uint32_t cbData = 0;
6596 uint32_t u32Width = 0;
6597 uint32_t u32Height = 0;
6598
6599 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6600
6601 if (RT_FAILURE(vrc))
6602 return setError(VBOX_E_IPRT_ERROR,
6603 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
6604 vrc);
6605
6606 *aWidth = u32Width;
6607 *aHeight = u32Height;
6608
6609 aData.resize(cbData);
6610 if (cbData)
6611 memcpy(&aData.front(), pu8Data, cbData);
6612
6613 freeSavedDisplayScreenshot(pu8Data);
6614
6615 return S_OK;
6616}
6617
6618HRESULT Machine::hotPlugCPU(ULONG aCpu)
6619{
6620 HRESULT rc = S_OK;
6621 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6622
6623 if (!mHWData->mCPUHotPlugEnabled)
6624 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6625
6626 if (aCpu >= mHWData->mCPUCount)
6627 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
6628
6629 if (mHWData->mCPUAttached[aCpu])
6630 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
6631
6632 alock.release();
6633 rc = i_onCPUChange(aCpu, false);
6634 alock.acquire();
6635 if (FAILED(rc)) return rc;
6636
6637 i_setModified(IsModified_MachineData);
6638 mHWData.backup();
6639 mHWData->mCPUAttached[aCpu] = true;
6640
6641 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
6642 if (Global::IsOnline(mData->mMachineState))
6643 i_saveSettings(NULL);
6644
6645 return S_OK;
6646}
6647
6648HRESULT Machine::hotUnplugCPU(ULONG aCpu)
6649{
6650 HRESULT rc = S_OK;
6651
6652 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6653
6654 if (!mHWData->mCPUHotPlugEnabled)
6655 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6656
6657 if (aCpu >= SchemaDefs::MaxCPUCount)
6658 return setError(E_INVALIDARG,
6659 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
6660 SchemaDefs::MaxCPUCount);
6661
6662 if (!mHWData->mCPUAttached[aCpu])
6663 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
6664
6665 /* CPU 0 can't be detached */
6666 if (aCpu == 0)
6667 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
6668
6669 alock.release();
6670 rc = i_onCPUChange(aCpu, true);
6671 alock.acquire();
6672 if (FAILED(rc)) return rc;
6673
6674 i_setModified(IsModified_MachineData);
6675 mHWData.backup();
6676 mHWData->mCPUAttached[aCpu] = false;
6677
6678 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
6679 if (Global::IsOnline(mData->mMachineState))
6680 i_saveSettings(NULL);
6681
6682 return S_OK;
6683}
6684
6685HRESULT Machine::getCPUStatus(ULONG aCpu, BOOL *aAttached)
6686{
6687 *aAttached = false;
6688
6689 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6690
6691 /* If hotplug is enabled the CPU is always enabled. */
6692 if (!mHWData->mCPUHotPlugEnabled)
6693 {
6694 if (aCpu < mHWData->mCPUCount)
6695 *aAttached = true;
6696 }
6697 else
6698 {
6699 if (aCpu < SchemaDefs::MaxCPUCount)
6700 *aAttached = mHWData->mCPUAttached[aCpu];
6701 }
6702
6703 return S_OK;
6704}
6705
6706HRESULT Machine::queryLogFilename(ULONG aIdx, com::Utf8Str &aFilename)
6707{
6708 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6709
6710 Utf8Str log = i_getLogFilename(aIdx);
6711 if (!RTFileExists(log.c_str()))
6712 log.setNull();
6713 aFilename = log;
6714
6715 return S_OK;
6716}
6717
6718HRESULT Machine::readLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, std::vector<BYTE> &aData)
6719{
6720 if (aSize < 0)
6721 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
6722
6723 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6724
6725 HRESULT rc = S_OK;
6726 Utf8Str log = i_getLogFilename(aIdx);
6727
6728 /* do not unnecessarily hold the lock while doing something which does
6729 * not need the lock and potentially takes a long time. */
6730 alock.release();
6731
6732 /* Limit the chunk size to 32K for now, as that gives better performance
6733 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
6734 * One byte expands to approx. 25 bytes of breathtaking XML. */
6735 size_t cbData = (size_t)RT_MIN(aSize, 32768);
6736 aData.resize(cbData);
6737
6738 RTFILE LogFile;
6739 int vrc = RTFileOpen(&LogFile, log.c_str(),
6740 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
6741 if (RT_SUCCESS(vrc))
6742 {
6743 vrc = RTFileReadAt(LogFile, aOffset, cbData? &aData.front(): NULL, cbData, &cbData);
6744 if (RT_SUCCESS(vrc))
6745 aData.resize(cbData);
6746 else
6747 rc = setError(VBOX_E_IPRT_ERROR,
6748 tr("Could not read log file '%s' (%Rrc)"),
6749 log.c_str(), vrc);
6750 RTFileClose(LogFile);
6751 }
6752 else
6753 rc = setError(VBOX_E_IPRT_ERROR,
6754 tr("Could not open log file '%s' (%Rrc)"),
6755 log.c_str(), vrc);
6756
6757 if (FAILED(rc))
6758 aData.resize(0);
6759
6760 return rc;
6761}
6762
6763
6764/**
6765 * Currently this method doesn't attach device to the running VM,
6766 * just makes sure it's plugged on next VM start.
6767 */
6768HRESULT Machine::attachHostPCIDevice(LONG aHostAddress, LONG aDesiredGuestAddress, BOOL /* aTryToUnbind */)
6769{
6770 // lock scope
6771 {
6772 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6773
6774 HRESULT rc = i_checkStateDependency(MutableStateDep);
6775 if (FAILED(rc)) return rc;
6776
6777 ChipsetType_T aChipset = ChipsetType_PIIX3;
6778 COMGETTER(ChipsetType)(&aChipset);
6779
6780 if (aChipset != ChipsetType_ICH9)
6781 {
6782 return setError(E_INVALIDARG,
6783 tr("Host PCI attachment only supported with ICH9 chipset"));
6784 }
6785
6786 // check if device with this host PCI address already attached
6787 for (HWData::PCIDeviceAssignmentList::const_iterator
6788 it = mHWData->mPCIDeviceAssignments.begin();
6789 it != mHWData->mPCIDeviceAssignments.end();
6790 ++it)
6791 {
6792 LONG iHostAddress = -1;
6793 ComPtr<PCIDeviceAttachment> pAttach;
6794 pAttach = *it;
6795 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6796 if (iHostAddress == aHostAddress)
6797 return setError(E_INVALIDARG,
6798 tr("Device with host PCI address already attached to this VM"));
6799 }
6800
6801 ComObjPtr<PCIDeviceAttachment> pda;
6802 char name[32];
6803
6804 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (aHostAddress>>8) & 0xff,
6805 (aHostAddress & 0xf8) >> 3, aHostAddress & 7);
6806 pda.createObject();
6807 pda->init(this, name, aHostAddress, aDesiredGuestAddress, TRUE);
6808 i_setModified(IsModified_MachineData);
6809 mHWData.backup();
6810 mHWData->mPCIDeviceAssignments.push_back(pda);
6811 }
6812
6813 return S_OK;
6814}
6815
6816/**
6817 * Currently this method doesn't detach device from the running VM,
6818 * just makes sure it's not plugged on next VM start.
6819 */
6820HRESULT Machine::detachHostPCIDevice(LONG aHostAddress)
6821{
6822 ComObjPtr<PCIDeviceAttachment> pAttach;
6823 bool fRemoved = false;
6824 HRESULT rc;
6825
6826 // lock scope
6827 {
6828 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6829
6830 rc = i_checkStateDependency(MutableStateDep);
6831 if (FAILED(rc)) return rc;
6832
6833 for (HWData::PCIDeviceAssignmentList::const_iterator
6834 it = mHWData->mPCIDeviceAssignments.begin();
6835 it != mHWData->mPCIDeviceAssignments.end();
6836 ++it)
6837 {
6838 LONG iHostAddress = -1;
6839 pAttach = *it;
6840 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6841 if (iHostAddress != -1 && iHostAddress == aHostAddress)
6842 {
6843 i_setModified(IsModified_MachineData);
6844 mHWData.backup();
6845 mHWData->mPCIDeviceAssignments.remove(pAttach);
6846 fRemoved = true;
6847 break;
6848 }
6849 }
6850 }
6851
6852
6853 /* Fire event outside of the lock */
6854 if (fRemoved)
6855 {
6856 Assert(!pAttach.isNull());
6857 ComPtr<IEventSource> es;
6858 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
6859 Assert(SUCCEEDED(rc));
6860 Bstr mid;
6861 rc = this->COMGETTER(Id)(mid.asOutParam());
6862 Assert(SUCCEEDED(rc));
6863 fireHostPCIDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
6864 }
6865
6866 return fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
6867 tr("No host PCI device %08x attached"),
6868 aHostAddress
6869 );
6870}
6871
6872HRESULT Machine::getPCIDeviceAssignments(std::vector<ComPtr<IPCIDeviceAttachment> > &aPCIDeviceAssignments)
6873{
6874 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6875
6876 aPCIDeviceAssignments.resize(mHWData->mPCIDeviceAssignments.size());
6877 size_t i = 0;
6878 for (std::list<ComObjPtr<PCIDeviceAttachment> >::const_iterator
6879 it = mHWData->mPCIDeviceAssignments.begin();
6880 it != mHWData->mPCIDeviceAssignments.end();
6881 ++it, ++i)
6882 (*it).queryInterfaceTo(aPCIDeviceAssignments[i].asOutParam());
6883
6884 return S_OK;
6885}
6886
6887HRESULT Machine::getBandwidthControl(ComPtr<IBandwidthControl> &aBandwidthControl)
6888{
6889 mBandwidthControl.queryInterfaceTo(aBandwidthControl.asOutParam());
6890
6891 return S_OK;
6892}
6893
6894HRESULT Machine::getTracingEnabled(BOOL *aTracingEnabled)
6895{
6896 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6897
6898 *aTracingEnabled = mHWData->mDebugging.fTracingEnabled;
6899
6900 return S_OK;
6901}
6902
6903HRESULT Machine::setTracingEnabled(BOOL aTracingEnabled)
6904{
6905 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6906 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6907 if (SUCCEEDED(hrc))
6908 {
6909 hrc = mHWData.backupEx();
6910 if (SUCCEEDED(hrc))
6911 {
6912 i_setModified(IsModified_MachineData);
6913 mHWData->mDebugging.fTracingEnabled = aTracingEnabled != FALSE;
6914 }
6915 }
6916 return hrc;
6917}
6918
6919HRESULT Machine::getTracingConfig(com::Utf8Str &aTracingConfig)
6920{
6921 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6922 aTracingConfig = mHWData->mDebugging.strTracingConfig;
6923 return S_OK;
6924}
6925
6926HRESULT Machine::setTracingConfig(const com::Utf8Str &aTracingConfig)
6927{
6928 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6929 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6930 if (SUCCEEDED(hrc))
6931 {
6932 hrc = mHWData.backupEx();
6933 if (SUCCEEDED(hrc))
6934 {
6935 mHWData->mDebugging.strTracingConfig = aTracingConfig;
6936 if (SUCCEEDED(hrc))
6937 i_setModified(IsModified_MachineData);
6938 }
6939 }
6940 return hrc;
6941}
6942
6943HRESULT Machine::getAllowTracingToAccessVM(BOOL *aAllowTracingToAccessVM)
6944{
6945 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6946
6947 *aAllowTracingToAccessVM = mHWData->mDebugging.fAllowTracingToAccessVM;
6948
6949 return S_OK;
6950}
6951
6952HRESULT Machine::setAllowTracingToAccessVM(BOOL aAllowTracingToAccessVM)
6953{
6954 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6955 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6956 if (SUCCEEDED(hrc))
6957 {
6958 hrc = mHWData.backupEx();
6959 if (SUCCEEDED(hrc))
6960 {
6961 i_setModified(IsModified_MachineData);
6962 mHWData->mDebugging.fAllowTracingToAccessVM = aAllowTracingToAccessVM != FALSE;
6963 }
6964 }
6965 return hrc;
6966}
6967
6968HRESULT Machine::getAutostartEnabled(BOOL *aAutostartEnabled)
6969{
6970 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6971
6972 *aAutostartEnabled = mHWData->mAutostart.fAutostartEnabled;
6973
6974 return S_OK;
6975}
6976
6977HRESULT Machine::setAutostartEnabled(BOOL aAutostartEnabled)
6978{
6979 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6980
6981 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
6982 if ( SUCCEEDED(hrc)
6983 && mHWData->mAutostart.fAutostartEnabled != !!aAutostartEnabled)
6984 {
6985 AutostartDb *autostartDb = mParent->i_getAutostartDb();
6986 int vrc;
6987
6988 if (aAutostartEnabled)
6989 vrc = autostartDb->addAutostartVM(mUserData->s.strName.c_str());
6990 else
6991 vrc = autostartDb->removeAutostartVM(mUserData->s.strName.c_str());
6992
6993 if (RT_SUCCESS(vrc))
6994 {
6995 hrc = mHWData.backupEx();
6996 if (SUCCEEDED(hrc))
6997 {
6998 i_setModified(IsModified_MachineData);
6999 mHWData->mAutostart.fAutostartEnabled = aAutostartEnabled != FALSE;
7000 }
7001 }
7002 else if (vrc == VERR_NOT_SUPPORTED)
7003 hrc = setError(VBOX_E_NOT_SUPPORTED,
7004 tr("The VM autostart feature is not supported on this platform"));
7005 else if (vrc == VERR_PATH_NOT_FOUND)
7006 hrc = setError(E_FAIL,
7007 tr("The path to the autostart database is not set"));
7008 else
7009 hrc = setError(E_UNEXPECTED,
7010 tr("%s machine '%s' to the autostart database failed with %Rrc"),
7011 aAutostartEnabled ? "Adding" : "Removing",
7012 mUserData->s.strName.c_str(), vrc);
7013 }
7014 return hrc;
7015}
7016
7017HRESULT Machine::getAutostartDelay(ULONG *aAutostartDelay)
7018{
7019 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7020
7021 *aAutostartDelay = mHWData->mAutostart.uAutostartDelay;
7022
7023 return S_OK;
7024}
7025
7026HRESULT Machine::setAutostartDelay(ULONG aAutostartDelay)
7027{
7028 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7029 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7030 if (SUCCEEDED(hrc))
7031 {
7032 hrc = mHWData.backupEx();
7033 if (SUCCEEDED(hrc))
7034 {
7035 i_setModified(IsModified_MachineData);
7036 mHWData->mAutostart.uAutostartDelay = aAutostartDelay;
7037 }
7038 }
7039 return hrc;
7040}
7041
7042HRESULT Machine::getAutostopType(AutostopType_T *aAutostopType)
7043{
7044 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7045
7046 *aAutostopType = mHWData->mAutostart.enmAutostopType;
7047
7048 return S_OK;
7049}
7050
7051HRESULT Machine::setAutostopType(AutostopType_T aAutostopType)
7052{
7053 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7054 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7055 if ( SUCCEEDED(hrc)
7056 && mHWData->mAutostart.enmAutostopType != aAutostopType)
7057 {
7058 AutostartDb *autostartDb = mParent->i_getAutostartDb();
7059 int vrc;
7060
7061 if (aAutostopType != AutostopType_Disabled)
7062 vrc = autostartDb->addAutostopVM(mUserData->s.strName.c_str());
7063 else
7064 vrc = autostartDb->removeAutostopVM(mUserData->s.strName.c_str());
7065
7066 if (RT_SUCCESS(vrc))
7067 {
7068 hrc = mHWData.backupEx();
7069 if (SUCCEEDED(hrc))
7070 {
7071 i_setModified(IsModified_MachineData);
7072 mHWData->mAutostart.enmAutostopType = aAutostopType;
7073 }
7074 }
7075 else if (vrc == VERR_NOT_SUPPORTED)
7076 hrc = setError(VBOX_E_NOT_SUPPORTED,
7077 tr("The VM autostop feature is not supported on this platform"));
7078 else if (vrc == VERR_PATH_NOT_FOUND)
7079 hrc = setError(E_FAIL,
7080 tr("The path to the autostart database is not set"));
7081 else
7082 hrc = setError(E_UNEXPECTED,
7083 tr("%s machine '%s' to the autostop database failed with %Rrc"),
7084 aAutostopType != AutostopType_Disabled ? "Adding" : "Removing",
7085 mUserData->s.strName.c_str(), vrc);
7086 }
7087 return hrc;
7088}
7089
7090HRESULT Machine::getDefaultFrontend(com::Utf8Str &aDefaultFrontend)
7091{
7092 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7093
7094 aDefaultFrontend = mHWData->mDefaultFrontend;
7095
7096 return S_OK;
7097}
7098
7099HRESULT Machine::setDefaultFrontend(const com::Utf8Str &aDefaultFrontend)
7100{
7101 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7102 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
7103 if (SUCCEEDED(hrc))
7104 {
7105 hrc = mHWData.backupEx();
7106 if (SUCCEEDED(hrc))
7107 {
7108 i_setModified(IsModified_MachineData);
7109 mHWData->mDefaultFrontend = aDefaultFrontend;
7110 }
7111 }
7112 return hrc;
7113}
7114
7115HRESULT Machine::getIcon(std::vector<BYTE> &aIcon)
7116{
7117 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7118 size_t cbIcon = mUserData->s.ovIcon.size();
7119 aIcon.resize(cbIcon);
7120 if (cbIcon)
7121 memcpy(&aIcon.front(), &mUserData->s.ovIcon[0], cbIcon);
7122 return S_OK;
7123}
7124
7125HRESULT Machine::setIcon(const std::vector<BYTE> &aIcon)
7126{
7127 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7128 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
7129 if (SUCCEEDED(hrc))
7130 {
7131 i_setModified(IsModified_MachineData);
7132 mUserData.backup();
7133 size_t cbIcon = aIcon.size();
7134 mUserData->s.ovIcon.resize(cbIcon);
7135 if (cbIcon)
7136 memcpy(&mUserData->s.ovIcon[0], &aIcon.front(), cbIcon);
7137 }
7138 return hrc;
7139}
7140
7141HRESULT Machine::getUSBProxyAvailable(BOOL *aUSBProxyAvailable)
7142{
7143#ifdef VBOX_WITH_USB
7144 *aUSBProxyAvailable = true;
7145#else
7146 *aUSBProxyAvailable = false;
7147#endif
7148 return S_OK;
7149}
7150
7151HRESULT Machine::getVMProcessPriority(com::Utf8Str &aVMProcessPriority)
7152{
7153 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7154
7155 aVMProcessPriority = mUserData->s.strVMPriority;
7156
7157 return S_OK;
7158}
7159
7160HRESULT Machine::setVMProcessPriority(const com::Utf8Str &aVMProcessPriority)
7161{
7162 RT_NOREF(aVMProcessPriority);
7163 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7164 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7165 if (SUCCEEDED(hrc))
7166 {
7167 /** @todo r=klaus: currently this is marked as not implemented, as
7168 * the code for setting the priority of the process is not there
7169 * (neither when starting the VM nor at runtime). */
7170 ReturnComNotImplemented();
7171#if 0
7172 hrc = mUserData.backupEx();
7173 if (SUCCEEDED(hrc))
7174 {
7175 i_setModified(IsModified_MachineData);
7176 mUserData->s.strVMPriority = aVMProcessPriority;
7177 }
7178#endif
7179 }
7180 return hrc;
7181}
7182
7183HRESULT Machine::getUnattended(ComPtr<IUnattended> &aUnattended)
7184{
7185#ifdef VBOX_WITH_UNATTENDED
7186 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7187
7188 aUnattended = mUnattended;
7189
7190 return S_OK;
7191#else
7192 NOREF(aUnattended);
7193 return E_NOTIMPL;
7194#endif
7195}
7196
7197HRESULT Machine::cloneTo(const ComPtr<IMachine> &aTarget, CloneMode_T aMode, const std::vector<CloneOptions_T> &aOptions,
7198 ComPtr<IProgress> &aProgress)
7199{
7200 ComObjPtr<Progress> pP;
7201 Progress *ppP = pP;
7202 IProgress *iP = static_cast<IProgress *>(ppP);
7203 IProgress **pProgress = &iP;
7204
7205 IMachine *pTarget = aTarget;
7206
7207 /* Convert the options. */
7208 RTCList<CloneOptions_T> optList;
7209 if (aOptions.size())
7210 for (size_t i = 0; i < aOptions.size(); ++i)
7211 optList.append(aOptions[i]);
7212
7213 if (optList.contains(CloneOptions_Link))
7214 {
7215 if (!i_isSnapshotMachine())
7216 return setError(E_INVALIDARG,
7217 tr("Linked clone can only be created from a snapshot"));
7218 if (aMode != CloneMode_MachineState)
7219 return setError(E_INVALIDARG,
7220 tr("Linked clone can only be created for a single machine state"));
7221 }
7222 AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_INVALIDARG);
7223
7224 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), aMode, optList);
7225
7226 HRESULT rc = pWorker->start(pProgress);
7227
7228 pP = static_cast<Progress *>(*pProgress);
7229 pP.queryInterfaceTo(aProgress.asOutParam());
7230
7231 return rc;
7232
7233}
7234
7235HRESULT Machine::saveState(ComPtr<IProgress> &aProgress)
7236{
7237 NOREF(aProgress);
7238 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7239
7240 // This check should always fail.
7241 HRESULT rc = i_checkStateDependency(MutableStateDep);
7242 if (FAILED(rc)) return rc;
7243
7244 AssertFailedReturn(E_NOTIMPL);
7245}
7246
7247HRESULT Machine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
7248{
7249 NOREF(aSavedStateFile);
7250 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7251
7252 // This check should always fail.
7253 HRESULT rc = i_checkStateDependency(MutableStateDep);
7254 if (FAILED(rc)) return rc;
7255
7256 AssertFailedReturn(E_NOTIMPL);
7257}
7258
7259HRESULT Machine::discardSavedState(BOOL aFRemoveFile)
7260{
7261 NOREF(aFRemoveFile);
7262 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7263
7264 // This check should always fail.
7265 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
7266 if (FAILED(rc)) return rc;
7267
7268 AssertFailedReturn(E_NOTIMPL);
7269}
7270
7271// public methods for internal purposes
7272/////////////////////////////////////////////////////////////////////////////
7273
7274/**
7275 * Adds the given IsModified_* flag to the dirty flags of the machine.
7276 * This must be called either during i_loadSettings or under the machine write lock.
7277 * @param fl Flag
7278 * @param fAllowStateModification If state modifications are allowed.
7279 */
7280void Machine::i_setModified(uint32_t fl, bool fAllowStateModification /* = true */)
7281{
7282 mData->flModifications |= fl;
7283 if (fAllowStateModification && i_isStateModificationAllowed())
7284 mData->mCurrentStateModified = true;
7285}
7286
7287/**
7288 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
7289 * care of the write locking.
7290 *
7291 * @param fModification The flag to add.
7292 * @param fAllowStateModification If state modifications are allowed.
7293 */
7294void Machine::i_setModifiedLock(uint32_t fModification, bool fAllowStateModification /* = true */)
7295{
7296 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7297 i_setModified(fModification, fAllowStateModification);
7298}
7299
7300/**
7301 * Saves the registry entry of this machine to the given configuration node.
7302 *
7303 * @param data Machine registry data.
7304 *
7305 * @note locks this object for reading.
7306 */
7307HRESULT Machine::i_saveRegistryEntry(settings::MachineRegistryEntry &data)
7308{
7309 AutoLimitedCaller autoCaller(this);
7310 AssertComRCReturnRC(autoCaller.rc());
7311
7312 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7313
7314 data.uuid = mData->mUuid;
7315 data.strSettingsFile = mData->m_strConfigFile;
7316
7317 return S_OK;
7318}
7319
7320/**
7321 * Calculates the absolute path of the given path taking the directory of the
7322 * machine settings file as the current directory.
7323 *
7324 * @param strPath Path to calculate the absolute path for.
7325 * @param aResult Where to put the result (used only on success, can be the
7326 * same Utf8Str instance as passed in @a aPath).
7327 * @return IPRT result.
7328 *
7329 * @note Locks this object for reading.
7330 */
7331int Machine::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
7332{
7333 AutoCaller autoCaller(this);
7334 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7335
7336 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7337
7338 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
7339
7340 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
7341
7342 strSettingsDir.stripFilename();
7343 char folder[RTPATH_MAX];
7344 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
7345 if (RT_SUCCESS(vrc))
7346 aResult = folder;
7347
7348 return vrc;
7349}
7350
7351/**
7352 * Copies strSource to strTarget, making it relative to the machine folder
7353 * if it is a subdirectory thereof, or simply copying it otherwise.
7354 *
7355 * @param strSource Path to evaluate and copy.
7356 * @param strTarget Buffer to receive target path.
7357 *
7358 * @note Locks this object for reading.
7359 */
7360void Machine::i_copyPathRelativeToMachine(const Utf8Str &strSource,
7361 Utf8Str &strTarget)
7362{
7363 AutoCaller autoCaller(this);
7364 AssertComRCReturn(autoCaller.rc(), (void)0);
7365
7366 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7367
7368 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
7369 // use strTarget as a temporary buffer to hold the machine settings dir
7370 strTarget = mData->m_strConfigFileFull;
7371 strTarget.stripFilename();
7372 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
7373 {
7374 // is relative: then append what's left
7375 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
7376 // for empty paths (only possible for subdirs) use "." to avoid
7377 // triggering default settings for not present config attributes.
7378 if (strTarget.isEmpty())
7379 strTarget = ".";
7380 }
7381 else
7382 // is not relative: then overwrite
7383 strTarget = strSource;
7384}
7385
7386/**
7387 * Returns the full path to the machine's log folder in the
7388 * \a aLogFolder argument.
7389 */
7390void Machine::i_getLogFolder(Utf8Str &aLogFolder)
7391{
7392 AutoCaller autoCaller(this);
7393 AssertComRCReturnVoid(autoCaller.rc());
7394
7395 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7396
7397 char szTmp[RTPATH_MAX];
7398 int vrc = RTEnvGetEx(RTENV_DEFAULT, "VBOX_USER_VMLOGDIR", szTmp, sizeof(szTmp), NULL);
7399 if (RT_SUCCESS(vrc))
7400 {
7401 if (szTmp[0] && !mUserData.isNull())
7402 {
7403 char szTmp2[RTPATH_MAX];
7404 vrc = RTPathAbs(szTmp, szTmp2, sizeof(szTmp2));
7405 if (RT_SUCCESS(vrc))
7406 aLogFolder = Utf8StrFmt("%s%c%s",
7407 szTmp2,
7408 RTPATH_DELIMITER,
7409 mUserData->s.strName.c_str()); // path/to/logfolder/vmname
7410 }
7411 else
7412 vrc = VERR_PATH_IS_RELATIVE;
7413 }
7414
7415 if (RT_FAILURE(vrc))
7416 {
7417 // fallback if VBOX_USER_LOGHOME is not set or invalid
7418 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7419 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
7420 aLogFolder.append(RTPATH_DELIMITER);
7421 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
7422 }
7423}
7424
7425/**
7426 * Returns the full path to the machine's log file for an given index.
7427 */
7428Utf8Str Machine::i_getLogFilename(ULONG idx)
7429{
7430 Utf8Str logFolder;
7431 getLogFolder(logFolder);
7432 Assert(logFolder.length());
7433
7434 Utf8Str log;
7435 if (idx == 0)
7436 log = Utf8StrFmt("%s%cVBox.log", logFolder.c_str(), RTPATH_DELIMITER);
7437#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7438 else if (idx == 1)
7439 log = Utf8StrFmt("%s%cVBoxHardening.log", logFolder.c_str(), RTPATH_DELIMITER);
7440 else
7441 log = Utf8StrFmt("%s%cVBox.log.%u", logFolder.c_str(), RTPATH_DELIMITER, idx - 1);
7442#else
7443 else
7444 log = Utf8StrFmt("%s%cVBox.log.%u", logFolder.c_str(), RTPATH_DELIMITER, idx);
7445#endif
7446 return log;
7447}
7448
7449/**
7450 * Returns the full path to the machine's hardened log file.
7451 */
7452Utf8Str Machine::i_getHardeningLogFilename(void)
7453{
7454 Utf8Str strFilename;
7455 getLogFolder(strFilename);
7456 Assert(strFilename.length());
7457 strFilename.append(RTPATH_SLASH_STR "VBoxHardening.log");
7458 return strFilename;
7459}
7460
7461
7462/**
7463 * Composes a unique saved state filename based on the current system time. The filename is
7464 * granular to the second so this will work so long as no more than one snapshot is taken on
7465 * a machine per second.
7466 *
7467 * Before version 4.1, we used this formula for saved state files:
7468 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
7469 * which no longer works because saved state files can now be shared between the saved state of the
7470 * "saved" machine and an online snapshot, and the following would cause problems:
7471 * 1) save machine
7472 * 2) create online snapshot from that machine state --> reusing saved state file
7473 * 3) save machine again --> filename would be reused, breaking the online snapshot
7474 *
7475 * So instead we now use a timestamp.
7476 *
7477 * @param strStateFilePath
7478 */
7479
7480void Machine::i_composeSavedStateFilename(Utf8Str &strStateFilePath)
7481{
7482 AutoCaller autoCaller(this);
7483 AssertComRCReturnVoid(autoCaller.rc());
7484
7485 {
7486 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7487 i_calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
7488 }
7489
7490 RTTIMESPEC ts;
7491 RTTimeNow(&ts);
7492 RTTIME time;
7493 RTTimeExplode(&time, &ts);
7494
7495 strStateFilePath += RTPATH_DELIMITER;
7496 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
7497 time.i32Year, time.u8Month, time.u8MonthDay,
7498 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
7499}
7500
7501/**
7502 * Returns the full path to the default video capture file.
7503 */
7504void Machine::i_getDefaultVideoCaptureFile(Utf8Str &strFile)
7505{
7506 AutoCaller autoCaller(this);
7507 AssertComRCReturnVoid(autoCaller.rc());
7508
7509 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7510
7511 strFile = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7512 strFile.stripSuffix(); // path/to/machinesfolder/vmname/vmname
7513 strFile.append(".webm"); // path/to/machinesfolder/vmname/vmname.webm
7514}
7515
7516/**
7517 * Returns whether at least one USB controller is present for the VM.
7518 */
7519bool Machine::i_isUSBControllerPresent()
7520{
7521 AutoCaller autoCaller(this);
7522 AssertComRCReturn(autoCaller.rc(), false);
7523
7524 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7525
7526 return (mUSBControllers->size() > 0);
7527}
7528
7529/**
7530 * @note Locks this object for writing, calls the client process
7531 * (inside the lock).
7532 */
7533HRESULT Machine::i_launchVMProcess(IInternalSessionControl *aControl,
7534 const Utf8Str &strFrontend,
7535 const Utf8Str &strEnvironment,
7536 ProgressProxy *aProgress)
7537{
7538 LogFlowThisFuncEnter();
7539
7540 AssertReturn(aControl, E_FAIL);
7541 AssertReturn(aProgress, E_FAIL);
7542 AssertReturn(!strFrontend.isEmpty(), E_FAIL);
7543
7544 AutoCaller autoCaller(this);
7545 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7546
7547 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7548
7549 if (!mData->mRegistered)
7550 return setError(E_UNEXPECTED,
7551 tr("The machine '%s' is not registered"),
7552 mUserData->s.strName.c_str());
7553
7554 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
7555
7556 /* The process started when launching a VM with separate UI/VM processes is always
7557 * the UI process, i.e. needs special handling as it won't claim the session. */
7558 bool fSeparate = strFrontend.endsWith("separate", Utf8Str::CaseInsensitive);
7559
7560 if (fSeparate)
7561 {
7562 if (mData->mSession.mState != SessionState_Unlocked && mData->mSession.mName != "headless")
7563 return setError(VBOX_E_INVALID_OBJECT_STATE,
7564 tr("The machine '%s' is in a state which is incompatible with launching a separate UI process"),
7565 mUserData->s.strName.c_str());
7566 }
7567 else
7568 {
7569 if ( mData->mSession.mState == SessionState_Locked
7570 || mData->mSession.mState == SessionState_Spawning
7571 || mData->mSession.mState == SessionState_Unlocking)
7572 return setError(VBOX_E_INVALID_OBJECT_STATE,
7573 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
7574 mUserData->s.strName.c_str());
7575
7576 /* may not be busy */
7577 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
7578 }
7579
7580 /* get the path to the executable */
7581 char szPath[RTPATH_MAX];
7582 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
7583 size_t cchBufLeft = strlen(szPath);
7584 szPath[cchBufLeft++] = RTPATH_DELIMITER;
7585 szPath[cchBufLeft] = 0;
7586 char *pszNamePart = szPath + cchBufLeft;
7587 cchBufLeft = sizeof(szPath) - cchBufLeft;
7588
7589 int vrc = VINF_SUCCESS;
7590 RTPROCESS pid = NIL_RTPROCESS;
7591
7592 RTENV env = RTENV_DEFAULT;
7593
7594 if (!strEnvironment.isEmpty())
7595 {
7596 char *newEnvStr = NULL;
7597
7598 do
7599 {
7600 /* clone the current environment */
7601 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
7602 AssertRCBreakStmt(vrc2, vrc = vrc2);
7603
7604 newEnvStr = RTStrDup(strEnvironment.c_str());
7605 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
7606
7607 /* put new variables to the environment
7608 * (ignore empty variable names here since RTEnv API
7609 * intentionally doesn't do that) */
7610 char *var = newEnvStr;
7611 for (char *p = newEnvStr; *p; ++p)
7612 {
7613 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
7614 {
7615 *p = '\0';
7616 if (*var)
7617 {
7618 char *val = strchr(var, '=');
7619 if (val)
7620 {
7621 *val++ = '\0';
7622 vrc2 = RTEnvSetEx(env, var, val);
7623 }
7624 else
7625 vrc2 = RTEnvUnsetEx(env, var);
7626 if (RT_FAILURE(vrc2))
7627 break;
7628 }
7629 var = p + 1;
7630 }
7631 }
7632 if (RT_SUCCESS(vrc2) && *var)
7633 vrc2 = RTEnvPutEx(env, var);
7634
7635 AssertRCBreakStmt(vrc2, vrc = vrc2);
7636 }
7637 while (0);
7638
7639 if (newEnvStr != NULL)
7640 RTStrFree(newEnvStr);
7641 }
7642
7643 /* Hardening logging */
7644#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7645 Utf8Str strSupHardeningLogArg("--sup-hardening-log=");
7646 {
7647 Utf8Str strHardeningLogFile = i_getHardeningLogFilename();
7648 int vrc2 = RTFileDelete(strHardeningLogFile.c_str());
7649 if (vrc2 == VERR_PATH_NOT_FOUND || vrc2 == VERR_FILE_NOT_FOUND)
7650 {
7651 Utf8Str strStartupLogDir = strHardeningLogFile;
7652 strStartupLogDir.stripFilename();
7653 RTDirCreateFullPath(strStartupLogDir.c_str(), 0755); /** @todo add a variant for creating the path to a
7654 file without stripping the file. */
7655 }
7656 strSupHardeningLogArg.append(strHardeningLogFile);
7657
7658 /* Remove legacy log filename to avoid confusion. */
7659 Utf8Str strOldStartupLogFile;
7660 getLogFolder(strOldStartupLogFile);
7661 strOldStartupLogFile.append(RTPATH_SLASH_STR "VBoxStartup.log");
7662 RTFileDelete(strOldStartupLogFile.c_str());
7663 }
7664 const char *pszSupHardeningLogArg = strSupHardeningLogArg.c_str();
7665#else
7666 const char *pszSupHardeningLogArg = NULL;
7667#endif
7668
7669 Utf8Str strCanonicalName;
7670
7671#ifdef VBOX_WITH_QTGUI
7672 if ( !strFrontend.compare("gui", Utf8Str::CaseInsensitive)
7673 || !strFrontend.compare("GUI/Qt", Utf8Str::CaseInsensitive)
7674 || !strFrontend.compare("separate", Utf8Str::CaseInsensitive)
7675 || !strFrontend.compare("gui/separate", Utf8Str::CaseInsensitive)
7676 || !strFrontend.compare("GUI/Qt/separate", Utf8Str::CaseInsensitive))
7677 {
7678 strCanonicalName = "GUI/Qt";
7679# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
7680 /* Modify the base path so that we don't need to use ".." below. */
7681 RTPathStripTrailingSlash(szPath);
7682 RTPathStripFilename(szPath);
7683 cchBufLeft = strlen(szPath);
7684 pszNamePart = szPath + cchBufLeft;
7685 cchBufLeft = sizeof(szPath) - cchBufLeft;
7686
7687# define OSX_APP_NAME "VirtualBoxVM"
7688# define OSX_APP_PATH_FMT "/Resources/%s.app/Contents/MacOS/VirtualBoxVM"
7689
7690 Utf8Str strAppOverride = i_getExtraData(Utf8Str("VBoxInternal2/VirtualBoxVMAppOverride"));
7691 if ( strAppOverride.contains(".")
7692 || strAppOverride.contains("/")
7693 || strAppOverride.contains("\\")
7694 || strAppOverride.contains(":"))
7695 strAppOverride.setNull();
7696 Utf8Str strAppPath;
7697 if (!strAppOverride.isEmpty())
7698 {
7699 strAppPath = Utf8StrFmt(OSX_APP_PATH_FMT, strAppOverride.c_str());
7700 Utf8Str strFullPath(szPath);
7701 strFullPath.append(strAppPath);
7702 /* there is a race, but people using this deserve the failure */
7703 if (!RTFileExists(strFullPath.c_str()))
7704 strAppOverride.setNull();
7705 }
7706 if (strAppOverride.isEmpty())
7707 strAppPath = Utf8StrFmt(OSX_APP_PATH_FMT, OSX_APP_NAME);
7708 AssertReturn(cchBufLeft > strAppPath.length(), E_UNEXPECTED);
7709 strcpy(pszNamePart, strAppPath.c_str());
7710# else
7711 static const char s_szVirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
7712 Assert(cchBufLeft >= sizeof(s_szVirtualBox_exe));
7713 strcpy(pszNamePart, s_szVirtualBox_exe);
7714# endif
7715
7716 Utf8Str idStr = mData->mUuid.toString();
7717 const char *apszArgs[] =
7718 {
7719 szPath,
7720 "--comment", mUserData->s.strName.c_str(),
7721 "--startvm", idStr.c_str(),
7722 "--no-startvm-errormsgbox",
7723 NULL, /* For "--separate". */
7724 NULL, /* For "--sup-startup-log". */
7725 NULL
7726 };
7727 unsigned iArg = 6;
7728 if (fSeparate)
7729 apszArgs[iArg++] = "--separate";
7730 apszArgs[iArg++] = pszSupHardeningLogArg;
7731
7732 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7733 }
7734#else /* !VBOX_WITH_QTGUI */
7735 if (0)
7736 ;
7737#endif /* VBOX_WITH_QTGUI */
7738
7739 else
7740
7741#ifdef VBOX_WITH_VBOXSDL
7742 if ( !strFrontend.compare("sdl", Utf8Str::CaseInsensitive)
7743 || !strFrontend.compare("GUI/SDL", Utf8Str::CaseInsensitive)
7744 || !strFrontend.compare("sdl/separate", Utf8Str::CaseInsensitive)
7745 || !strFrontend.compare("GUI/SDL/separate", Utf8Str::CaseInsensitive))
7746 {
7747 strCanonicalName = "GUI/SDL";
7748 static const char s_szVBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
7749 Assert(cchBufLeft >= sizeof(s_szVBoxSDL_exe));
7750 strcpy(pszNamePart, s_szVBoxSDL_exe);
7751
7752 Utf8Str idStr = mData->mUuid.toString();
7753 const char *apszArgs[] =
7754 {
7755 szPath,
7756 "--comment", mUserData->s.strName.c_str(),
7757 "--startvm", idStr.c_str(),
7758 NULL, /* For "--separate". */
7759 NULL, /* For "--sup-startup-log". */
7760 NULL
7761 };
7762 unsigned iArg = 5;
7763 if (fSeparate)
7764 apszArgs[iArg++] = "--separate";
7765 apszArgs[iArg++] = pszSupHardeningLogArg;
7766
7767 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7768 }
7769#else /* !VBOX_WITH_VBOXSDL */
7770 if (0)
7771 ;
7772#endif /* !VBOX_WITH_VBOXSDL */
7773
7774 else
7775
7776#ifdef VBOX_WITH_HEADLESS
7777 if ( !strFrontend.compare("headless", Utf8Str::CaseInsensitive)
7778 || !strFrontend.compare("capture", Utf8Str::CaseInsensitive)
7779 || !strFrontend.compare("vrdp", Utf8Str::CaseInsensitive) /* Deprecated. Same as headless. */
7780 )
7781 {
7782 strCanonicalName = "headless";
7783 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
7784 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
7785 * and a VM works even if the server has not been installed.
7786 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
7787 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
7788 * differently in 4.0 and 3.x.
7789 */
7790 static const char s_szVBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
7791 Assert(cchBufLeft >= sizeof(s_szVBoxHeadless_exe));
7792 strcpy(pszNamePart, s_szVBoxHeadless_exe);
7793
7794 Utf8Str idStr = mData->mUuid.toString();
7795 const char *apszArgs[] =
7796 {
7797 szPath,
7798 "--comment", mUserData->s.strName.c_str(),
7799 "--startvm", idStr.c_str(),
7800 "--vrde", "config",
7801 NULL, /* For "--capture". */
7802 NULL, /* For "--sup-startup-log". */
7803 NULL
7804 };
7805 unsigned iArg = 7;
7806 if (!strFrontend.compare("capture", Utf8Str::CaseInsensitive))
7807 apszArgs[iArg++] = "--capture";
7808 apszArgs[iArg++] = pszSupHardeningLogArg;
7809
7810# ifdef RT_OS_WINDOWS
7811 vrc = RTProcCreate(szPath, apszArgs, env, RTPROC_FLAGS_NO_WINDOW, &pid);
7812# else
7813 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7814# endif
7815 }
7816#else /* !VBOX_WITH_HEADLESS */
7817 if (0)
7818 ;
7819#endif /* !VBOX_WITH_HEADLESS */
7820 else
7821 {
7822 RTEnvDestroy(env);
7823 return setError(E_INVALIDARG,
7824 tr("Invalid frontend name: '%s'"),
7825 strFrontend.c_str());
7826 }
7827
7828 RTEnvDestroy(env);
7829
7830 if (RT_FAILURE(vrc))
7831 return setError(VBOX_E_IPRT_ERROR,
7832 tr("Could not launch a process for the machine '%s' (%Rrc)"),
7833 mUserData->s.strName.c_str(), vrc);
7834
7835 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
7836
7837 if (!fSeparate)
7838 {
7839 /*
7840 * Note that we don't release the lock here before calling the client,
7841 * because it doesn't need to call us back if called with a NULL argument.
7842 * Releasing the lock here is dangerous because we didn't prepare the
7843 * launch data yet, but the client we've just started may happen to be
7844 * too fast and call LockMachine() that will fail (because of PID, etc.),
7845 * so that the Machine will never get out of the Spawning session state.
7846 */
7847
7848 /* inform the session that it will be a remote one */
7849 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
7850#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
7851 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write, Bstr::Empty.raw());
7852#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
7853 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write, NULL);
7854#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
7855 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
7856
7857 if (FAILED(rc))
7858 {
7859 /* restore the session state */
7860 mData->mSession.mState = SessionState_Unlocked;
7861 alock.release();
7862 mParent->i_addProcessToReap(pid);
7863 /* The failure may occur w/o any error info (from RPC), so provide one */
7864 return setError(VBOX_E_VM_ERROR,
7865 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
7866 }
7867
7868 /* attach launch data to the machine */
7869 Assert(mData->mSession.mPID == NIL_RTPROCESS);
7870 mData->mSession.mRemoteControls.push_back(aControl);
7871 mData->mSession.mProgress = aProgress;
7872 mData->mSession.mPID = pid;
7873 mData->mSession.mState = SessionState_Spawning;
7874 Assert(strCanonicalName.isNotEmpty());
7875 mData->mSession.mName = strCanonicalName;
7876 }
7877 else
7878 {
7879 /* For separate UI process we declare the launch as completed instantly, as the
7880 * actual headless VM start may or may not come. No point in remembering anything
7881 * yet, as what matters for us is when the headless VM gets started. */
7882 aProgress->i_notifyComplete(S_OK);
7883 }
7884
7885 alock.release();
7886 mParent->i_addProcessToReap(pid);
7887
7888 LogFlowThisFuncLeave();
7889 return S_OK;
7890}
7891
7892/**
7893 * Returns @c true if the given session machine instance has an open direct
7894 * session (and optionally also for direct sessions which are closing) and
7895 * returns the session control machine instance if so.
7896 *
7897 * Note that when the method returns @c false, the arguments remain unchanged.
7898 *
7899 * @param aMachine Session machine object.
7900 * @param aControl Direct session control object (optional).
7901 * @param aRequireVM If true then only allow VM sessions.
7902 * @param aAllowClosing If true then additionally a session which is currently
7903 * being closed will also be allowed.
7904 *
7905 * @note locks this object for reading.
7906 */
7907bool Machine::i_isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7908 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7909 bool aRequireVM /*= false*/,
7910 bool aAllowClosing /*= false*/)
7911{
7912 AutoLimitedCaller autoCaller(this);
7913 AssertComRCReturn(autoCaller.rc(), false);
7914
7915 /* just return false for inaccessible machines */
7916 if (getObjectState().getState() != ObjectState::Ready)
7917 return false;
7918
7919 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7920
7921 if ( ( mData->mSession.mState == SessionState_Locked
7922 && (!aRequireVM || mData->mSession.mLockType == LockType_VM))
7923 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
7924 )
7925 {
7926 AssertReturn(!mData->mSession.mMachine.isNull(), false);
7927
7928 aMachine = mData->mSession.mMachine;
7929
7930 if (aControl != NULL)
7931 *aControl = mData->mSession.mDirectControl;
7932
7933 return true;
7934 }
7935
7936 return false;
7937}
7938
7939/**
7940 * Returns @c true if the given machine has an spawning direct session.
7941 *
7942 * @note locks this object for reading.
7943 */
7944bool Machine::i_isSessionSpawning()
7945{
7946 AutoLimitedCaller autoCaller(this);
7947 AssertComRCReturn(autoCaller.rc(), false);
7948
7949 /* just return false for inaccessible machines */
7950 if (getObjectState().getState() != ObjectState::Ready)
7951 return false;
7952
7953 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7954
7955 if (mData->mSession.mState == SessionState_Spawning)
7956 return true;
7957
7958 return false;
7959}
7960
7961/**
7962 * Called from the client watcher thread to check for unexpected client process
7963 * death during Session_Spawning state (e.g. before it successfully opened a
7964 * direct session).
7965 *
7966 * On Win32 and on OS/2, this method is called only when we've got the
7967 * direct client's process termination notification, so it always returns @c
7968 * true.
7969 *
7970 * On other platforms, this method returns @c true if the client process is
7971 * terminated and @c false if it's still alive.
7972 *
7973 * @note Locks this object for writing.
7974 */
7975bool Machine::i_checkForSpawnFailure()
7976{
7977 AutoCaller autoCaller(this);
7978 if (!autoCaller.isOk())
7979 {
7980 /* nothing to do */
7981 LogFlowThisFunc(("Already uninitialized!\n"));
7982 return true;
7983 }
7984
7985 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7986
7987 if (mData->mSession.mState != SessionState_Spawning)
7988 {
7989 /* nothing to do */
7990 LogFlowThisFunc(("Not spawning any more!\n"));
7991 return true;
7992 }
7993
7994 HRESULT rc = S_OK;
7995
7996 /* PID not yet initialized, skip check. */
7997 if (mData->mSession.mPID == NIL_RTPROCESS)
7998 return false;
7999
8000 RTPROCSTATUS status;
8001 int vrc = RTProcWait(mData->mSession.mPID, RTPROCWAIT_FLAGS_NOBLOCK, &status);
8002
8003 if (vrc != VERR_PROCESS_RUNNING)
8004 {
8005 Utf8Str strExtraInfo;
8006
8007#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
8008 /* If the startup logfile exists and is of non-zero length, tell the
8009 user to look there for more details to encourage them to attach it
8010 when reporting startup issues. */
8011 Utf8Str strHardeningLogFile = i_getHardeningLogFilename();
8012 uint64_t cbStartupLogFile = 0;
8013 int vrc2 = RTFileQuerySize(strHardeningLogFile.c_str(), &cbStartupLogFile);
8014 if (RT_SUCCESS(vrc2) && cbStartupLogFile > 0)
8015 strExtraInfo.append(Utf8StrFmt(tr(". More details may be available in '%s'"), strHardeningLogFile.c_str()));
8016#endif
8017
8018 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
8019 rc = setError(E_FAIL,
8020 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d (%#x)%s"),
8021 i_getName().c_str(), status.iStatus, status.iStatus, strExtraInfo.c_str());
8022 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
8023 rc = setError(E_FAIL,
8024 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d%s"),
8025 i_getName().c_str(), status.iStatus, strExtraInfo.c_str());
8026 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
8027 rc = setError(E_FAIL,
8028 tr("The virtual machine '%s' has terminated abnormally (iStatus=%#x)%s"),
8029 i_getName().c_str(), status.iStatus, strExtraInfo.c_str());
8030 else
8031 rc = setError(E_FAIL,
8032 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)%s"),
8033 i_getName().c_str(), vrc, strExtraInfo.c_str());
8034 }
8035
8036 if (FAILED(rc))
8037 {
8038 /* Close the remote session, remove the remote control from the list
8039 * and reset session state to Closed (@note keep the code in sync with
8040 * the relevant part in LockMachine()). */
8041
8042 Assert(mData->mSession.mRemoteControls.size() == 1);
8043 if (mData->mSession.mRemoteControls.size() == 1)
8044 {
8045 ErrorInfoKeeper eik;
8046 mData->mSession.mRemoteControls.front()->Uninitialize();
8047 }
8048
8049 mData->mSession.mRemoteControls.clear();
8050 mData->mSession.mState = SessionState_Unlocked;
8051
8052 /* finalize the progress after setting the state */
8053 if (!mData->mSession.mProgress.isNull())
8054 {
8055 mData->mSession.mProgress->notifyComplete(rc);
8056 mData->mSession.mProgress.setNull();
8057 }
8058
8059 mData->mSession.mPID = NIL_RTPROCESS;
8060
8061 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
8062 return true;
8063 }
8064
8065 return false;
8066}
8067
8068/**
8069 * Checks whether the machine can be registered. If so, commits and saves
8070 * all settings.
8071 *
8072 * @note Must be called from mParent's write lock. Locks this object and
8073 * children for writing.
8074 */
8075HRESULT Machine::i_prepareRegister()
8076{
8077 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
8078
8079 AutoLimitedCaller autoCaller(this);
8080 AssertComRCReturnRC(autoCaller.rc());
8081
8082 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8083
8084 /* wait for state dependents to drop to zero */
8085 i_ensureNoStateDependencies();
8086
8087 if (!mData->mAccessible)
8088 return setError(VBOX_E_INVALID_OBJECT_STATE,
8089 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
8090 mUserData->s.strName.c_str(),
8091 mData->mUuid.toString().c_str());
8092
8093 AssertReturn(getObjectState().getState() == ObjectState::Ready, E_FAIL);
8094
8095 if (mData->mRegistered)
8096 return setError(VBOX_E_INVALID_OBJECT_STATE,
8097 tr("The machine '%s' with UUID {%s} is already registered"),
8098 mUserData->s.strName.c_str(),
8099 mData->mUuid.toString().c_str());
8100
8101 HRESULT rc = S_OK;
8102
8103 // Ensure the settings are saved. If we are going to be registered and
8104 // no config file exists yet, create it by calling i_saveSettings() too.
8105 if ( (mData->flModifications)
8106 || (!mData->pMachineConfigFile->fileExists())
8107 )
8108 {
8109 rc = i_saveSettings(NULL);
8110 // no need to check whether VirtualBox.xml needs saving too since
8111 // we can't have a machine XML file rename pending
8112 if (FAILED(rc)) return rc;
8113 }
8114
8115 /* more config checking goes here */
8116
8117 if (SUCCEEDED(rc))
8118 {
8119 /* we may have had implicit modifications we want to fix on success */
8120 i_commit();
8121
8122 mData->mRegistered = true;
8123 }
8124 else
8125 {
8126 /* we may have had implicit modifications we want to cancel on failure*/
8127 i_rollback(false /* aNotify */);
8128 }
8129
8130 return rc;
8131}
8132
8133/**
8134 * Increases the number of objects dependent on the machine state or on the
8135 * registered state. Guarantees that these two states will not change at least
8136 * until #i_releaseStateDependency() is called.
8137 *
8138 * Depending on the @a aDepType value, additional state checks may be made.
8139 * These checks will set extended error info on failure. See
8140 * #i_checkStateDependency() for more info.
8141 *
8142 * If this method returns a failure, the dependency is not added and the caller
8143 * is not allowed to rely on any particular machine state or registration state
8144 * value and may return the failed result code to the upper level.
8145 *
8146 * @param aDepType Dependency type to add.
8147 * @param aState Current machine state (NULL if not interested).
8148 * @param aRegistered Current registered state (NULL if not interested).
8149 *
8150 * @note Locks this object for writing.
8151 */
8152HRESULT Machine::i_addStateDependency(StateDependency aDepType /* = AnyStateDep */,
8153 MachineState_T *aState /* = NULL */,
8154 BOOL *aRegistered /* = NULL */)
8155{
8156 AutoCaller autoCaller(this);
8157 AssertComRCReturnRC(autoCaller.rc());
8158
8159 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8160
8161 HRESULT rc = i_checkStateDependency(aDepType);
8162 if (FAILED(rc)) return rc;
8163
8164 {
8165 if (mData->mMachineStateChangePending != 0)
8166 {
8167 /* i_ensureNoStateDependencies() is waiting for state dependencies to
8168 * drop to zero so don't add more. It may make sense to wait a bit
8169 * and retry before reporting an error (since the pending state
8170 * transition should be really quick) but let's just assert for
8171 * now to see if it ever happens on practice. */
8172
8173 AssertFailed();
8174
8175 return setError(E_ACCESSDENIED,
8176 tr("Machine state change is in progress. Please retry the operation later."));
8177 }
8178
8179 ++mData->mMachineStateDeps;
8180 Assert(mData->mMachineStateDeps != 0 /* overflow */);
8181 }
8182
8183 if (aState)
8184 *aState = mData->mMachineState;
8185 if (aRegistered)
8186 *aRegistered = mData->mRegistered;
8187
8188 return S_OK;
8189}
8190
8191/**
8192 * Decreases the number of objects dependent on the machine state.
8193 * Must always complete the #i_addStateDependency() call after the state
8194 * dependency is no more necessary.
8195 */
8196void Machine::i_releaseStateDependency()
8197{
8198 AutoCaller autoCaller(this);
8199 AssertComRCReturnVoid(autoCaller.rc());
8200
8201 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8202
8203 /* releaseStateDependency() w/o addStateDependency()? */
8204 AssertReturnVoid(mData->mMachineStateDeps != 0);
8205 -- mData->mMachineStateDeps;
8206
8207 if (mData->mMachineStateDeps == 0)
8208 {
8209 /* inform i_ensureNoStateDependencies() that there are no more deps */
8210 if (mData->mMachineStateChangePending != 0)
8211 {
8212 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
8213 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
8214 }
8215 }
8216}
8217
8218Utf8Str Machine::i_getExtraData(const Utf8Str &strKey)
8219{
8220 /* start with nothing found */
8221 Utf8Str strResult("");
8222
8223 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8224
8225 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
8226 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
8227 // found:
8228 strResult = it->second; // source is a Utf8Str
8229
8230 return strResult;
8231}
8232
8233// protected methods
8234/////////////////////////////////////////////////////////////////////////////
8235
8236/**
8237 * Performs machine state checks based on the @a aDepType value. If a check
8238 * fails, this method will set extended error info, otherwise it will return
8239 * S_OK. It is supposed, that on failure, the caller will immediately return
8240 * the return value of this method to the upper level.
8241 *
8242 * When @a aDepType is AnyStateDep, this method always returns S_OK.
8243 *
8244 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
8245 * current state of this machine object allows to change settings of the
8246 * machine (i.e. the machine is not registered, or registered but not running
8247 * and not saved). It is useful to call this method from Machine setters
8248 * before performing any change.
8249 *
8250 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
8251 * as for MutableStateDep except that if the machine is saved, S_OK is also
8252 * returned. This is useful in setters which allow changing machine
8253 * properties when it is in the saved state.
8254 *
8255 * When @a aDepType is MutableOrRunningStateDep, this method returns S_OK only
8256 * if the current state of this machine object allows to change runtime
8257 * changeable settings of the machine (i.e. the machine is not registered, or
8258 * registered but either running or not running and not saved). It is useful
8259 * to call this method from Machine setters before performing any changes to
8260 * runtime changeable settings.
8261 *
8262 * When @a aDepType is MutableOrSavedOrRunningStateDep, this method behaves
8263 * the same as for MutableOrRunningStateDep except that if the machine is
8264 * saved, S_OK is also returned. This is useful in setters which allow
8265 * changing runtime and saved state changeable machine properties.
8266 *
8267 * @param aDepType Dependency type to check.
8268 *
8269 * @note Non Machine based classes should use #i_addStateDependency() and
8270 * #i_releaseStateDependency() methods or the smart AutoStateDependency
8271 * template.
8272 *
8273 * @note This method must be called from under this object's read or write
8274 * lock.
8275 */
8276HRESULT Machine::i_checkStateDependency(StateDependency aDepType)
8277{
8278 switch (aDepType)
8279 {
8280 case AnyStateDep:
8281 {
8282 break;
8283 }
8284 case MutableStateDep:
8285 {
8286 if ( mData->mRegistered
8287 && ( !i_isSessionMachine()
8288 || ( mData->mMachineState != MachineState_Aborted
8289 && mData->mMachineState != MachineState_Teleported
8290 && mData->mMachineState != MachineState_PoweredOff
8291 )
8292 )
8293 )
8294 return setError(VBOX_E_INVALID_VM_STATE,
8295 tr("The machine is not mutable (state is %s)"),
8296 Global::stringifyMachineState(mData->mMachineState));
8297 break;
8298 }
8299 case MutableOrSavedStateDep:
8300 {
8301 if ( mData->mRegistered
8302 && ( !i_isSessionMachine()
8303 || ( mData->mMachineState != MachineState_Aborted
8304 && mData->mMachineState != MachineState_Teleported
8305 && mData->mMachineState != MachineState_Saved
8306 && mData->mMachineState != MachineState_PoweredOff
8307 )
8308 )
8309 )
8310 return setError(VBOX_E_INVALID_VM_STATE,
8311 tr("The machine is not mutable or saved (state is %s)"),
8312 Global::stringifyMachineState(mData->mMachineState));
8313 break;
8314 }
8315 case MutableOrRunningStateDep:
8316 {
8317 if ( mData->mRegistered
8318 && ( !i_isSessionMachine()
8319 || ( mData->mMachineState != MachineState_Aborted
8320 && mData->mMachineState != MachineState_Teleported
8321 && mData->mMachineState != MachineState_PoweredOff
8322 && !Global::IsOnline(mData->mMachineState)
8323 )
8324 )
8325 )
8326 return setError(VBOX_E_INVALID_VM_STATE,
8327 tr("The machine is not mutable or running (state is %s)"),
8328 Global::stringifyMachineState(mData->mMachineState));
8329 break;
8330 }
8331 case MutableOrSavedOrRunningStateDep:
8332 {
8333 if ( mData->mRegistered
8334 && ( !i_isSessionMachine()
8335 || ( mData->mMachineState != MachineState_Aborted
8336 && mData->mMachineState != MachineState_Teleported
8337 && mData->mMachineState != MachineState_Saved
8338 && mData->mMachineState != MachineState_PoweredOff
8339 && !Global::IsOnline(mData->mMachineState)
8340 )
8341 )
8342 )
8343 return setError(VBOX_E_INVALID_VM_STATE,
8344 tr("The machine is not mutable, saved or running (state is %s)"),
8345 Global::stringifyMachineState(mData->mMachineState));
8346 break;
8347 }
8348 }
8349
8350 return S_OK;
8351}
8352
8353/**
8354 * Helper to initialize all associated child objects and allocate data
8355 * structures.
8356 *
8357 * This method must be called as a part of the object's initialization procedure
8358 * (usually done in the #init() method).
8359 *
8360 * @note Must be called only from #init() or from #i_registeredInit().
8361 */
8362HRESULT Machine::initDataAndChildObjects()
8363{
8364 AutoCaller autoCaller(this);
8365 AssertComRCReturnRC(autoCaller.rc());
8366 AssertComRCReturn( getObjectState().getState() == ObjectState::InInit
8367 || getObjectState().getState() == ObjectState::Limited, E_FAIL);
8368
8369 AssertReturn(!mData->mAccessible, E_FAIL);
8370
8371 /* allocate data structures */
8372 mSSData.allocate();
8373 mUserData.allocate();
8374 mHWData.allocate();
8375 mMediumAttachments.allocate();
8376 mStorageControllers.allocate();
8377 mUSBControllers.allocate();
8378
8379 /* initialize mOSTypeId */
8380 mUserData->s.strOsType = mParent->i_getUnknownOSType()->i_id();
8381
8382 /* create associated BIOS settings object */
8383 unconst(mBIOSSettings).createObject();
8384 mBIOSSettings->init(this);
8385
8386 /* create an associated VRDE object (default is disabled) */
8387 unconst(mVRDEServer).createObject();
8388 mVRDEServer->init(this);
8389
8390 /* create associated serial port objects */
8391 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8392 {
8393 unconst(mSerialPorts[slot]).createObject();
8394 mSerialPorts[slot]->init(this, slot);
8395 }
8396
8397 /* create associated parallel port objects */
8398 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8399 {
8400 unconst(mParallelPorts[slot]).createObject();
8401 mParallelPorts[slot]->init(this, slot);
8402 }
8403
8404 /* create the audio adapter object (always present, default is disabled) */
8405 unconst(mAudioAdapter).createObject();
8406 mAudioAdapter->init(this);
8407
8408 /* create the USB device filters object (always present) */
8409 unconst(mUSBDeviceFilters).createObject();
8410 mUSBDeviceFilters->init(this);
8411
8412 /* create associated network adapter objects */
8413 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
8414 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8415 {
8416 unconst(mNetworkAdapters[slot]).createObject();
8417 mNetworkAdapters[slot]->init(this, slot);
8418 }
8419
8420 /* create the bandwidth control */
8421 unconst(mBandwidthControl).createObject();
8422 mBandwidthControl->init(this);
8423
8424#ifdef VBOX_WITH_UNATTENDED
8425 /* create the unattended object (always present) */
8426 /** @todo r=bird: Why don't we create this when the IUnattended instance
8427 * is queried? */
8428 unconst(mUnattended).createObject();
8429 mUnattended->init(this);
8430#endif
8431
8432 return S_OK;
8433}
8434
8435/**
8436 * Helper to uninitialize all associated child objects and to free all data
8437 * structures.
8438 *
8439 * This method must be called as a part of the object's uninitialization
8440 * procedure (usually done in the #uninit() method).
8441 *
8442 * @note Must be called only from #uninit() or from #i_registeredInit().
8443 */
8444void Machine::uninitDataAndChildObjects()
8445{
8446 AutoCaller autoCaller(this);
8447 AssertComRCReturnVoid(autoCaller.rc());
8448 AssertComRCReturnVoid( getObjectState().getState() == ObjectState::InUninit
8449 || getObjectState().getState() == ObjectState::Limited);
8450
8451 /* tell all our other child objects we've been uninitialized */
8452 if (mBandwidthControl)
8453 {
8454 mBandwidthControl->uninit();
8455 unconst(mBandwidthControl).setNull();
8456 }
8457
8458 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8459 {
8460 if (mNetworkAdapters[slot])
8461 {
8462 mNetworkAdapters[slot]->uninit();
8463 unconst(mNetworkAdapters[slot]).setNull();
8464 }
8465 }
8466
8467 if (mUSBDeviceFilters)
8468 {
8469 mUSBDeviceFilters->uninit();
8470 unconst(mUSBDeviceFilters).setNull();
8471 }
8472
8473 if (mAudioAdapter)
8474 {
8475 mAudioAdapter->uninit();
8476 unconst(mAudioAdapter).setNull();
8477 }
8478
8479 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8480 {
8481 if (mParallelPorts[slot])
8482 {
8483 mParallelPorts[slot]->uninit();
8484 unconst(mParallelPorts[slot]).setNull();
8485 }
8486 }
8487
8488 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8489 {
8490 if (mSerialPorts[slot])
8491 {
8492 mSerialPorts[slot]->uninit();
8493 unconst(mSerialPorts[slot]).setNull();
8494 }
8495 }
8496
8497 if (mVRDEServer)
8498 {
8499 mVRDEServer->uninit();
8500 unconst(mVRDEServer).setNull();
8501 }
8502
8503 if (mBIOSSettings)
8504 {
8505 mBIOSSettings->uninit();
8506 unconst(mBIOSSettings).setNull();
8507 }
8508
8509#ifdef VBOX_WITH_UNATTENDED
8510 if (mUnattended)
8511 {
8512 mUnattended->uninit();
8513 unconst(mUnattended).setNull();
8514 }
8515#endif
8516
8517 /* Deassociate media (only when a real Machine or a SnapshotMachine
8518 * instance is uninitialized; SessionMachine instances refer to real
8519 * Machine media). This is necessary for a clean re-initialization of
8520 * the VM after successfully re-checking the accessibility state. Note
8521 * that in case of normal Machine or SnapshotMachine uninitialization (as
8522 * a result of unregistering or deleting the snapshot), outdated media
8523 * attachments will already be uninitialized and deleted, so this
8524 * code will not affect them. */
8525 if ( !mMediumAttachments.isNull()
8526 && !i_isSessionMachine()
8527 )
8528 {
8529 for (MediumAttachmentList::const_iterator
8530 it = mMediumAttachments->begin();
8531 it != mMediumAttachments->end();
8532 ++it)
8533 {
8534 ComObjPtr<Medium> pMedium = (*it)->i_getMedium();
8535 if (pMedium.isNull())
8536 continue;
8537 HRESULT rc = pMedium->i_removeBackReference(mData->mUuid, i_getSnapshotId());
8538 AssertComRC(rc);
8539 }
8540 }
8541
8542 if (!i_isSessionMachine() && !i_isSnapshotMachine())
8543 {
8544 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
8545 if (mData->mFirstSnapshot)
8546 {
8547 // snapshots tree is protected by machine write lock; strictly
8548 // this isn't necessary here since we're deleting the entire
8549 // machine, but otherwise we assert in Snapshot::uninit()
8550 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8551 mData->mFirstSnapshot->uninit();
8552 mData->mFirstSnapshot.setNull();
8553 }
8554
8555 mData->mCurrentSnapshot.setNull();
8556 }
8557
8558 /* free data structures (the essential mData structure is not freed here
8559 * since it may be still in use) */
8560 mMediumAttachments.free();
8561 mStorageControllers.free();
8562 mUSBControllers.free();
8563 mHWData.free();
8564 mUserData.free();
8565 mSSData.free();
8566}
8567
8568/**
8569 * Returns a pointer to the Machine object for this machine that acts like a
8570 * parent for complex machine data objects such as shared folders, etc.
8571 *
8572 * For primary Machine objects and for SnapshotMachine objects, returns this
8573 * object's pointer itself. For SessionMachine objects, returns the peer
8574 * (primary) machine pointer.
8575 */
8576Machine *Machine::i_getMachine()
8577{
8578 if (i_isSessionMachine())
8579 return (Machine*)mPeer;
8580 return this;
8581}
8582
8583/**
8584 * Makes sure that there are no machine state dependents. If necessary, waits
8585 * for the number of dependents to drop to zero.
8586 *
8587 * Make sure this method is called from under this object's write lock to
8588 * guarantee that no new dependents may be added when this method returns
8589 * control to the caller.
8590 *
8591 * @note Locks this object for writing. The lock will be released while waiting
8592 * (if necessary).
8593 *
8594 * @warning To be used only in methods that change the machine state!
8595 */
8596void Machine::i_ensureNoStateDependencies()
8597{
8598 AssertReturnVoid(isWriteLockOnCurrentThread());
8599
8600 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8601
8602 /* Wait for all state dependents if necessary */
8603 if (mData->mMachineStateDeps != 0)
8604 {
8605 /* lazy semaphore creation */
8606 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
8607 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
8608
8609 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
8610 mData->mMachineStateDeps));
8611
8612 ++mData->mMachineStateChangePending;
8613
8614 /* reset the semaphore before waiting, the last dependent will signal
8615 * it */
8616 RTSemEventMultiReset(mData->mMachineStateDepsSem);
8617
8618 alock.release();
8619
8620 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
8621
8622 alock.acquire();
8623
8624 -- mData->mMachineStateChangePending;
8625 }
8626}
8627
8628/**
8629 * Changes the machine state and informs callbacks.
8630 *
8631 * This method is not intended to fail so it either returns S_OK or asserts (and
8632 * returns a failure).
8633 *
8634 * @note Locks this object for writing.
8635 */
8636HRESULT Machine::i_setMachineState(MachineState_T aMachineState)
8637{
8638 LogFlowThisFuncEnter();
8639 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
8640 Assert(aMachineState != MachineState_Null);
8641
8642 AutoCaller autoCaller(this);
8643 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8644
8645 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8646
8647 /* wait for state dependents to drop to zero */
8648 i_ensureNoStateDependencies();
8649
8650 MachineState_T const enmOldState = mData->mMachineState;
8651 if (enmOldState != aMachineState)
8652 {
8653 mData->mMachineState = aMachineState;
8654 RTTimeNow(&mData->mLastStateChange);
8655
8656#ifdef VBOX_WITH_DTRACE_R3_MAIN
8657 VBOXAPI_MACHINE_STATE_CHANGED(this, aMachineState, enmOldState, mData->mUuid.toStringCurly().c_str());
8658#endif
8659 mParent->i_onMachineStateChange(mData->mUuid, aMachineState);
8660 }
8661
8662 LogFlowThisFuncLeave();
8663 return S_OK;
8664}
8665
8666/**
8667 * Searches for a shared folder with the given logical name
8668 * in the collection of shared folders.
8669 *
8670 * @param aName logical name of the shared folder
8671 * @param aSharedFolder where to return the found object
8672 * @param aSetError whether to set the error info if the folder is
8673 * not found
8674 * @return
8675 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
8676 *
8677 * @note
8678 * must be called from under the object's lock!
8679 */
8680HRESULT Machine::i_findSharedFolder(const Utf8Str &aName,
8681 ComObjPtr<SharedFolder> &aSharedFolder,
8682 bool aSetError /* = false */)
8683{
8684 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
8685 for (HWData::SharedFolderList::const_iterator
8686 it = mHWData->mSharedFolders.begin();
8687 it != mHWData->mSharedFolders.end();
8688 ++it)
8689 {
8690 SharedFolder *pSF = *it;
8691 AutoCaller autoCaller(pSF);
8692 if (pSF->i_getName() == aName)
8693 {
8694 aSharedFolder = pSF;
8695 rc = S_OK;
8696 break;
8697 }
8698 }
8699
8700 if (aSetError && FAILED(rc))
8701 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
8702
8703 return rc;
8704}
8705
8706/**
8707 * Initializes all machine instance data from the given settings structures
8708 * from XML. The exception is the machine UUID which needs special handling
8709 * depending on the caller's use case, so the caller needs to set that herself.
8710 *
8711 * This gets called in several contexts during machine initialization:
8712 *
8713 * -- When machine XML exists on disk already and needs to be loaded into memory,
8714 * for example, from #i_registeredInit() to load all registered machines on
8715 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
8716 * attached to the machine should be part of some media registry already.
8717 *
8718 * -- During OVF import, when a machine config has been constructed from an
8719 * OVF file. In this case, puuidRegistry is set to the machine UUID to
8720 * ensure that the media listed as attachments in the config (which have
8721 * been imported from the OVF) receive the correct registry ID.
8722 *
8723 * -- During VM cloning.
8724 *
8725 * @param config Machine settings from XML.
8726 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID
8727 * for each attached medium in the config.
8728 * @return
8729 */
8730HRESULT Machine::i_loadMachineDataFromSettings(const settings::MachineConfigFile &config,
8731 const Guid *puuidRegistry)
8732{
8733 // copy name, description, OS type, teleporter, UTC etc.
8734 mUserData->s = config.machineUserData;
8735
8736 // look up the object by Id to check it is valid
8737 ComObjPtr<GuestOSType> pGuestOSType;
8738 HRESULT rc = mParent->i_findGuestOSType(mUserData->s.strOsType,
8739 pGuestOSType);
8740 if (FAILED(rc)) return rc;
8741 mUserData->s.strOsType = pGuestOSType->i_id();
8742
8743 // stateFile (optional)
8744 if (config.strStateFile.isEmpty())
8745 mSSData->strStateFilePath.setNull();
8746 else
8747 {
8748 Utf8Str stateFilePathFull(config.strStateFile);
8749 int vrc = i_calculateFullPath(stateFilePathFull, stateFilePathFull);
8750 if (RT_FAILURE(vrc))
8751 return setError(E_FAIL,
8752 tr("Invalid saved state file path '%s' (%Rrc)"),
8753 config.strStateFile.c_str(),
8754 vrc);
8755 mSSData->strStateFilePath = stateFilePathFull;
8756 }
8757
8758 // snapshot folder needs special processing so set it again
8759 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
8760 if (FAILED(rc)) return rc;
8761
8762 /* Copy the extra data items (config may or may not be the same as
8763 * mData->pMachineConfigFile) if necessary. When loading the XML files
8764 * from disk they are the same, but not for OVF import. */
8765 if (mData->pMachineConfigFile != &config)
8766 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
8767
8768 /* currentStateModified (optional, default is true) */
8769 mData->mCurrentStateModified = config.fCurrentStateModified;
8770
8771 mData->mLastStateChange = config.timeLastStateChange;
8772
8773 /*
8774 * note: all mUserData members must be assigned prior this point because
8775 * we need to commit changes in order to let mUserData be shared by all
8776 * snapshot machine instances.
8777 */
8778 mUserData.commitCopy();
8779
8780 // machine registry, if present (must be loaded before snapshots)
8781 if (config.canHaveOwnMediaRegistry())
8782 {
8783 // determine machine folder
8784 Utf8Str strMachineFolder = i_getSettingsFileFull();
8785 strMachineFolder.stripFilename();
8786 rc = mParent->initMedia(i_getId(), // media registry ID == machine UUID
8787 config.mediaRegistry,
8788 strMachineFolder);
8789 if (FAILED(rc)) return rc;
8790 }
8791
8792 /* Snapshot node (optional) */
8793 size_t cRootSnapshots;
8794 if ((cRootSnapshots = config.llFirstSnapshot.size()))
8795 {
8796 // there must be only one root snapshot
8797 Assert(cRootSnapshots == 1);
8798
8799 const settings::Snapshot &snap = config.llFirstSnapshot.front();
8800
8801 rc = i_loadSnapshot(snap,
8802 config.uuidCurrentSnapshot,
8803 NULL); // no parent == first snapshot
8804 if (FAILED(rc)) return rc;
8805 }
8806
8807 // hardware data
8808 rc = i_loadHardware(puuidRegistry, NULL, config.hardwareMachine, &config.debugging, &config.autostart);
8809 if (FAILED(rc)) return rc;
8810
8811 /*
8812 * NOTE: the assignment below must be the last thing to do,
8813 * otherwise it will be not possible to change the settings
8814 * somewhere in the code above because all setters will be
8815 * blocked by i_checkStateDependency(MutableStateDep).
8816 */
8817
8818 /* set the machine state to Aborted or Saved when appropriate */
8819 if (config.fAborted)
8820 {
8821 mSSData->strStateFilePath.setNull();
8822
8823 /* no need to use i_setMachineState() during init() */
8824 mData->mMachineState = MachineState_Aborted;
8825 }
8826 else if (!mSSData->strStateFilePath.isEmpty())
8827 {
8828 /* no need to use i_setMachineState() during init() */
8829 mData->mMachineState = MachineState_Saved;
8830 }
8831
8832 // after loading settings, we are no longer different from the XML on disk
8833 mData->flModifications = 0;
8834
8835 return S_OK;
8836}
8837
8838/**
8839 * Recursively loads all snapshots starting from the given.
8840 *
8841 * @param data snapshot settings.
8842 * @param aCurSnapshotId Current snapshot ID from the settings file.
8843 * @param aParentSnapshot Parent snapshot.
8844 */
8845HRESULT Machine::i_loadSnapshot(const settings::Snapshot &data,
8846 const Guid &aCurSnapshotId,
8847 Snapshot *aParentSnapshot)
8848{
8849 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
8850 AssertReturn(!i_isSessionMachine(), E_FAIL);
8851
8852 HRESULT rc = S_OK;
8853
8854 Utf8Str strStateFile;
8855 if (!data.strStateFile.isEmpty())
8856 {
8857 /* optional */
8858 strStateFile = data.strStateFile;
8859 int vrc = i_calculateFullPath(strStateFile, strStateFile);
8860 if (RT_FAILURE(vrc))
8861 return setError(E_FAIL,
8862 tr("Invalid saved state file path '%s' (%Rrc)"),
8863 strStateFile.c_str(),
8864 vrc);
8865 }
8866
8867 /* create a snapshot machine object */
8868 ComObjPtr<SnapshotMachine> pSnapshotMachine;
8869 pSnapshotMachine.createObject();
8870 rc = pSnapshotMachine->initFromSettings(this,
8871 data.hardware,
8872 &data.debugging,
8873 &data.autostart,
8874 data.uuid.ref(),
8875 strStateFile);
8876 if (FAILED(rc)) return rc;
8877
8878 /* create a snapshot object */
8879 ComObjPtr<Snapshot> pSnapshot;
8880 pSnapshot.createObject();
8881 /* initialize the snapshot */
8882 rc = pSnapshot->init(mParent, // VirtualBox object
8883 data.uuid,
8884 data.strName,
8885 data.strDescription,
8886 data.timestamp,
8887 pSnapshotMachine,
8888 aParentSnapshot);
8889 if (FAILED(rc)) return rc;
8890
8891 /* memorize the first snapshot if necessary */
8892 if (!mData->mFirstSnapshot)
8893 mData->mFirstSnapshot = pSnapshot;
8894
8895 /* memorize the current snapshot when appropriate */
8896 if ( !mData->mCurrentSnapshot
8897 && pSnapshot->i_getId() == aCurSnapshotId
8898 )
8899 mData->mCurrentSnapshot = pSnapshot;
8900
8901 // now create the children
8902 for (settings::SnapshotsList::const_iterator
8903 it = data.llChildSnapshots.begin();
8904 it != data.llChildSnapshots.end();
8905 ++it)
8906 {
8907 const settings::Snapshot &childData = *it;
8908 // recurse
8909 rc = i_loadSnapshot(childData,
8910 aCurSnapshotId,
8911 pSnapshot); // parent = the one we created above
8912 if (FAILED(rc)) return rc;
8913 }
8914
8915 return rc;
8916}
8917
8918/**
8919 * Loads settings into mHWData.
8920 *
8921 * @param puuidRegistry Registry ID.
8922 * @param puuidSnapshot Snapshot ID
8923 * @param data Reference to the hardware settings.
8924 * @param pDbg Pointer to the debugging settings.
8925 * @param pAutostart Pointer to the autostart settings.
8926 */
8927HRESULT Machine::i_loadHardware(const Guid *puuidRegistry,
8928 const Guid *puuidSnapshot,
8929 const settings::Hardware &data,
8930 const settings::Debugging *pDbg,
8931 const settings::Autostart *pAutostart)
8932{
8933 AssertReturn(!i_isSessionMachine(), E_FAIL);
8934
8935 HRESULT rc = S_OK;
8936
8937 try
8938 {
8939 ComObjPtr<GuestOSType> pGuestOSType;
8940 rc = mParent->i_findGuestOSType(Bstr(mUserData->s.strOsType).raw(),
8941 pGuestOSType);
8942 if (FAILED(rc))
8943 return rc;
8944
8945 /* The hardware version attribute (optional). */
8946 mHWData->mHWVersion = data.strVersion;
8947 mHWData->mHardwareUUID = data.uuid;
8948
8949 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
8950 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
8951 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
8952 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
8953 mHWData->mHWVirtExUXEnabled = data.fUnrestrictedExecution;
8954 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
8955 mHWData->mPAEEnabled = data.fPAE;
8956 mHWData->mLongMode = data.enmLongMode;
8957 mHWData->mTripleFaultReset = data.fTripleFaultReset;
8958 mHWData->mAPIC = data.fAPIC;
8959 mHWData->mX2APIC = data.fX2APIC;
8960 mHWData->mCPUCount = data.cCPUs;
8961 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
8962 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
8963 mHWData->mCpuIdPortabilityLevel = data.uCpuIdPortabilityLevel;
8964 mHWData->mCpuProfile = data.strCpuProfile;
8965
8966 // cpu
8967 if (mHWData->mCPUHotPlugEnabled)
8968 {
8969 for (settings::CpuList::const_iterator
8970 it = data.llCpus.begin();
8971 it != data.llCpus.end();
8972 ++it)
8973 {
8974 const settings::Cpu &cpu = *it;
8975
8976 mHWData->mCPUAttached[cpu.ulId] = true;
8977 }
8978 }
8979
8980 // cpuid leafs
8981 for (settings::CpuIdLeafsList::const_iterator
8982 it = data.llCpuIdLeafs.begin();
8983 it != data.llCpuIdLeafs.end();
8984 ++it)
8985 {
8986 const settings::CpuIdLeaf &leaf = *it;
8987
8988 switch (leaf.ulId)
8989 {
8990 case 0x0:
8991 case 0x1:
8992 case 0x2:
8993 case 0x3:
8994 case 0x4:
8995 case 0x5:
8996 case 0x6:
8997 case 0x7:
8998 case 0x8:
8999 case 0x9:
9000 case 0xA:
9001 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
9002 break;
9003
9004 case 0x80000000:
9005 case 0x80000001:
9006 case 0x80000002:
9007 case 0x80000003:
9008 case 0x80000004:
9009 case 0x80000005:
9010 case 0x80000006:
9011 case 0x80000007:
9012 case 0x80000008:
9013 case 0x80000009:
9014 case 0x8000000A:
9015 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
9016 break;
9017
9018 default:
9019 /* just ignore */
9020 break;
9021 }
9022 }
9023
9024 mHWData->mMemorySize = data.ulMemorySizeMB;
9025 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
9026
9027 // boot order
9028 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
9029 {
9030 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
9031 if (it == data.mapBootOrder.end())
9032 mHWData->mBootOrder[i] = DeviceType_Null;
9033 else
9034 mHWData->mBootOrder[i] = it->second;
9035 }
9036
9037 mHWData->mGraphicsControllerType = data.graphicsControllerType;
9038 mHWData->mVRAMSize = data.ulVRAMSizeMB;
9039 mHWData->mMonitorCount = data.cMonitors;
9040 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
9041 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
9042 mHWData->mVideoCaptureWidth = data.ulVideoCaptureHorzRes;
9043 mHWData->mVideoCaptureHeight = data.ulVideoCaptureVertRes;
9044 mHWData->mVideoCaptureEnabled = data.fVideoCaptureEnabled;
9045 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->maVideoCaptureScreens); ++i)
9046 mHWData->maVideoCaptureScreens[i] = ASMBitTest(&data.u64VideoCaptureScreens, i);
9047 AssertCompile(RT_ELEMENTS(mHWData->maVideoCaptureScreens) == sizeof(data.u64VideoCaptureScreens) * 8);
9048 mHWData->mVideoCaptureRate = data.ulVideoCaptureRate;
9049 mHWData->mVideoCaptureFPS = data.ulVideoCaptureFPS;
9050 if (!data.strVideoCaptureFile.isEmpty())
9051 i_calculateFullPath(data.strVideoCaptureFile, mHWData->mVideoCaptureFile);
9052 else
9053 mHWData->mVideoCaptureFile.setNull();
9054 mHWData->mFirmwareType = data.firmwareType;
9055 mHWData->mPointingHIDType = data.pointingHIDType;
9056 mHWData->mKeyboardHIDType = data.keyboardHIDType;
9057 mHWData->mChipsetType = data.chipsetType;
9058 mHWData->mParavirtProvider = data.paravirtProvider;
9059 mHWData->mParavirtDebug = data.strParavirtDebug;
9060 mHWData->mEmulatedUSBCardReaderEnabled = data.fEmulatedUSBCardReader;
9061 mHWData->mHPETEnabled = data.fHPETEnabled;
9062
9063 /* VRDEServer */
9064 rc = mVRDEServer->i_loadSettings(data.vrdeSettings);
9065 if (FAILED(rc)) return rc;
9066
9067 /* BIOS */
9068 rc = mBIOSSettings->i_loadSettings(data.biosSettings);
9069 if (FAILED(rc)) return rc;
9070
9071 // Bandwidth control (must come before network adapters)
9072 rc = mBandwidthControl->i_loadSettings(data.ioSettings);
9073 if (FAILED(rc)) return rc;
9074
9075 /* Shared folders */
9076 for (settings::USBControllerList::const_iterator
9077 it = data.usbSettings.llUSBControllers.begin();
9078 it != data.usbSettings.llUSBControllers.end();
9079 ++it)
9080 {
9081 const settings::USBController &settingsCtrl = *it;
9082 ComObjPtr<USBController> newCtrl;
9083
9084 newCtrl.createObject();
9085 newCtrl->init(this, settingsCtrl.strName, settingsCtrl.enmType);
9086 mUSBControllers->push_back(newCtrl);
9087 }
9088
9089 /* USB device filters */
9090 rc = mUSBDeviceFilters->i_loadSettings(data.usbSettings);
9091 if (FAILED(rc)) return rc;
9092
9093 // network adapters (establish array size first and apply defaults, to
9094 // ensure reading the same settings as we saved, since the list skips
9095 // adapters having defaults)
9096 size_t newCount = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
9097 size_t oldCount = mNetworkAdapters.size();
9098 if (newCount > oldCount)
9099 {
9100 mNetworkAdapters.resize(newCount);
9101 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); ++slot)
9102 {
9103 unconst(mNetworkAdapters[slot]).createObject();
9104 mNetworkAdapters[slot]->init(this, (ULONG)slot);
9105 }
9106 }
9107 else if (newCount < oldCount)
9108 mNetworkAdapters.resize(newCount);
9109 for (unsigned i = 0; i < mNetworkAdapters.size(); i++)
9110 mNetworkAdapters[i]->i_applyDefaults(pGuestOSType);
9111 for (settings::NetworkAdaptersList::const_iterator
9112 it = data.llNetworkAdapters.begin();
9113 it != data.llNetworkAdapters.end();
9114 ++it)
9115 {
9116 const settings::NetworkAdapter &nic = *it;
9117
9118 /* slot uniqueness is guaranteed by XML Schema */
9119 AssertBreak(nic.ulSlot < mNetworkAdapters.size());
9120 rc = mNetworkAdapters[nic.ulSlot]->i_loadSettings(mBandwidthControl, nic);
9121 if (FAILED(rc)) return rc;
9122 }
9123
9124 // serial ports (establish defaults first, to ensure reading the same
9125 // settings as we saved, since the list skips ports having defaults)
9126 for (unsigned i = 0; i < RT_ELEMENTS(mSerialPorts); i++)
9127 mSerialPorts[i]->i_applyDefaults(pGuestOSType);
9128 for (settings::SerialPortsList::const_iterator
9129 it = data.llSerialPorts.begin();
9130 it != data.llSerialPorts.end();
9131 ++it)
9132 {
9133 const settings::SerialPort &s = *it;
9134
9135 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
9136 rc = mSerialPorts[s.ulSlot]->i_loadSettings(s);
9137 if (FAILED(rc)) return rc;
9138 }
9139
9140 // parallel ports (establish defaults first, to ensure reading the same
9141 // settings as we saved, since the list skips ports having defaults)
9142 for (unsigned i = 0; i < RT_ELEMENTS(mParallelPorts); i++)
9143 mParallelPorts[i]->i_applyDefaults();
9144 for (settings::ParallelPortsList::const_iterator
9145 it = data.llParallelPorts.begin();
9146 it != data.llParallelPorts.end();
9147 ++it)
9148 {
9149 const settings::ParallelPort &p = *it;
9150
9151 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
9152 rc = mParallelPorts[p.ulSlot]->i_loadSettings(p);
9153 if (FAILED(rc)) return rc;
9154 }
9155
9156 /* AudioAdapter */
9157 rc = mAudioAdapter->i_loadSettings(data.audioAdapter);
9158 if (FAILED(rc)) return rc;
9159
9160 /* storage controllers */
9161 rc = i_loadStorageControllers(data.storage,
9162 puuidRegistry,
9163 puuidSnapshot);
9164 if (FAILED(rc)) return rc;
9165
9166 /* Shared folders */
9167 for (settings::SharedFoldersList::const_iterator
9168 it = data.llSharedFolders.begin();
9169 it != data.llSharedFolders.end();
9170 ++it)
9171 {
9172 const settings::SharedFolder &sf = *it;
9173
9174 ComObjPtr<SharedFolder> sharedFolder;
9175 /* Check for double entries. Not allowed! */
9176 rc = i_findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
9177 if (SUCCEEDED(rc))
9178 return setError(VBOX_E_OBJECT_IN_USE,
9179 tr("Shared folder named '%s' already exists"),
9180 sf.strName.c_str());
9181
9182 /* Create the new shared folder. Don't break on error. This will be
9183 * reported when the machine starts. */
9184 sharedFolder.createObject();
9185 rc = sharedFolder->init(i_getMachine(),
9186 sf.strName,
9187 sf.strHostPath,
9188 RT_BOOL(sf.fWritable),
9189 RT_BOOL(sf.fAutoMount),
9190 false /* fFailOnError */);
9191 if (FAILED(rc)) return rc;
9192 mHWData->mSharedFolders.push_back(sharedFolder);
9193 }
9194
9195 // Clipboard
9196 mHWData->mClipboardMode = data.clipboardMode;
9197
9198 // drag'n'drop
9199 mHWData->mDnDMode = data.dndMode;
9200
9201 // guest settings
9202 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
9203
9204 // IO settings
9205 mHWData->mIOCacheEnabled = data.ioSettings.fIOCacheEnabled;
9206 mHWData->mIOCacheSize = data.ioSettings.ulIOCacheSize;
9207
9208 // Host PCI devices
9209 for (settings::HostPCIDeviceAttachmentList::const_iterator
9210 it = data.pciAttachments.begin();
9211 it != data.pciAttachments.end();
9212 ++it)
9213 {
9214 const settings::HostPCIDeviceAttachment &hpda = *it;
9215 ComObjPtr<PCIDeviceAttachment> pda;
9216
9217 pda.createObject();
9218 pda->i_loadSettings(this, hpda);
9219 mHWData->mPCIDeviceAssignments.push_back(pda);
9220 }
9221
9222 /*
9223 * (The following isn't really real hardware, but it lives in HWData
9224 * for reasons of convenience.)
9225 */
9226
9227#ifdef VBOX_WITH_GUEST_PROPS
9228 /* Guest properties (optional) */
9229
9230 /* Only load transient guest properties for configs which have saved
9231 * state, because there shouldn't be any for powered off VMs. The same
9232 * logic applies for snapshots, as offline snapshots shouldn't have
9233 * any such properties. They confuse the code in various places.
9234 * Note: can't rely on the machine state, as it isn't set yet. */
9235 bool fSkipTransientGuestProperties = mSSData->strStateFilePath.isEmpty();
9236 /* apologies for the hacky unconst() usage, but this needs hacking
9237 * actually inconsistent settings into consistency, otherwise there
9238 * will be some corner cases where the inconsistency survives
9239 * surprisingly long without getting fixed, especially for snapshots
9240 * as there are no config changes. */
9241 settings::GuestPropertiesList &llGuestProperties = unconst(data.llGuestProperties);
9242 for (settings::GuestPropertiesList::iterator
9243 it = llGuestProperties.begin();
9244 it != llGuestProperties.end();
9245 /*nothing*/)
9246 {
9247 const settings::GuestProperty &prop = *it;
9248 uint32_t fFlags = guestProp::NILFLAG;
9249 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
9250 if ( fSkipTransientGuestProperties
9251 && ( fFlags & guestProp::TRANSIENT
9252 || fFlags & guestProp::TRANSRESET))
9253 {
9254 it = llGuestProperties.erase(it);
9255 continue;
9256 }
9257 HWData::GuestProperty property = { prop.strValue, (LONG64) prop.timestamp, fFlags };
9258 mHWData->mGuestProperties[prop.strName] = property;
9259 ++it;
9260 }
9261#endif /* VBOX_WITH_GUEST_PROPS defined */
9262
9263 rc = i_loadDebugging(pDbg);
9264 if (FAILED(rc))
9265 return rc;
9266
9267 mHWData->mAutostart = *pAutostart;
9268
9269 /* default frontend */
9270 mHWData->mDefaultFrontend = data.strDefaultFrontend;
9271 }
9272 catch (std::bad_alloc &)
9273 {
9274 return E_OUTOFMEMORY;
9275 }
9276
9277 AssertComRC(rc);
9278 return rc;
9279}
9280
9281/**
9282 * Called from i_loadHardware() to load the debugging settings of the
9283 * machine.
9284 *
9285 * @param pDbg Pointer to the settings.
9286 */
9287HRESULT Machine::i_loadDebugging(const settings::Debugging *pDbg)
9288{
9289 mHWData->mDebugging = *pDbg;
9290 /* no more processing currently required, this will probably change. */
9291 return S_OK;
9292}
9293
9294/**
9295 * Called from i_loadMachineDataFromSettings() for the storage controller data, including media.
9296 *
9297 * @param data storage settings.
9298 * @param puuidRegistry media registry ID to set media to or NULL;
9299 * see Machine::i_loadMachineDataFromSettings()
9300 * @param puuidSnapshot snapshot ID
9301 * @return
9302 */
9303HRESULT Machine::i_loadStorageControllers(const settings::Storage &data,
9304 const Guid *puuidRegistry,
9305 const Guid *puuidSnapshot)
9306{
9307 AssertReturn(!i_isSessionMachine(), E_FAIL);
9308
9309 HRESULT rc = S_OK;
9310
9311 for (settings::StorageControllersList::const_iterator
9312 it = data.llStorageControllers.begin();
9313 it != data.llStorageControllers.end();
9314 ++it)
9315 {
9316 const settings::StorageController &ctlData = *it;
9317
9318 ComObjPtr<StorageController> pCtl;
9319 /* Try to find one with the name first. */
9320 rc = i_getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
9321 if (SUCCEEDED(rc))
9322 return setError(VBOX_E_OBJECT_IN_USE,
9323 tr("Storage controller named '%s' already exists"),
9324 ctlData.strName.c_str());
9325
9326 pCtl.createObject();
9327 rc = pCtl->init(this,
9328 ctlData.strName,
9329 ctlData.storageBus,
9330 ctlData.ulInstance,
9331 ctlData.fBootable);
9332 if (FAILED(rc)) return rc;
9333
9334 mStorageControllers->push_back(pCtl);
9335
9336 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
9337 if (FAILED(rc)) return rc;
9338
9339 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
9340 if (FAILED(rc)) return rc;
9341
9342 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
9343 if (FAILED(rc)) return rc;
9344
9345 /* Load the attached devices now. */
9346 rc = i_loadStorageDevices(pCtl,
9347 ctlData,
9348 puuidRegistry,
9349 puuidSnapshot);
9350 if (FAILED(rc)) return rc;
9351 }
9352
9353 return S_OK;
9354}
9355
9356/**
9357 * Called from i_loadStorageControllers for a controller's devices.
9358 *
9359 * @param aStorageController
9360 * @param data
9361 * @param puuidRegistry media registry ID to set media to or NULL; see
9362 * Machine::i_loadMachineDataFromSettings()
9363 * @param puuidSnapshot pointer to the snapshot ID if this is a snapshot machine
9364 * @return
9365 */
9366HRESULT Machine::i_loadStorageDevices(StorageController *aStorageController,
9367 const settings::StorageController &data,
9368 const Guid *puuidRegistry,
9369 const Guid *puuidSnapshot)
9370{
9371 HRESULT rc = S_OK;
9372
9373 /* paranoia: detect duplicate attachments */
9374 for (settings::AttachedDevicesList::const_iterator
9375 it = data.llAttachedDevices.begin();
9376 it != data.llAttachedDevices.end();
9377 ++it)
9378 {
9379 const settings::AttachedDevice &ad = *it;
9380
9381 for (settings::AttachedDevicesList::const_iterator it2 = it;
9382 it2 != data.llAttachedDevices.end();
9383 ++it2)
9384 {
9385 if (it == it2)
9386 continue;
9387
9388 const settings::AttachedDevice &ad2 = *it2;
9389
9390 if ( ad.lPort == ad2.lPort
9391 && ad.lDevice == ad2.lDevice)
9392 {
9393 return setError(E_FAIL,
9394 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
9395 aStorageController->i_getName().c_str(),
9396 ad.lPort,
9397 ad.lDevice,
9398 mUserData->s.strName.c_str());
9399 }
9400 }
9401 }
9402
9403 for (settings::AttachedDevicesList::const_iterator
9404 it = data.llAttachedDevices.begin();
9405 it != data.llAttachedDevices.end();
9406 ++it)
9407 {
9408 const settings::AttachedDevice &dev = *it;
9409 ComObjPtr<Medium> medium;
9410
9411 switch (dev.deviceType)
9412 {
9413 case DeviceType_Floppy:
9414 case DeviceType_DVD:
9415 if (dev.strHostDriveSrc.isNotEmpty())
9416 rc = mParent->i_host()->i_findHostDriveByName(dev.deviceType, dev.strHostDriveSrc,
9417 false /* fRefresh */, medium);
9418 else
9419 rc = mParent->i_findRemoveableMedium(dev.deviceType,
9420 dev.uuid,
9421 false /* fRefresh */,
9422 false /* aSetError */,
9423 medium);
9424 if (rc == VBOX_E_OBJECT_NOT_FOUND)
9425 // This is not an error. The host drive or UUID might have vanished, so just go
9426 // ahead without this removeable medium attachment
9427 rc = S_OK;
9428 break;
9429
9430 case DeviceType_HardDisk:
9431 {
9432 /* find a hard disk by UUID */
9433 rc = mParent->i_findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
9434 if (FAILED(rc))
9435 {
9436 if (i_isSnapshotMachine())
9437 {
9438 // wrap another error message around the "cannot find hard disk" set by findHardDisk
9439 // so the user knows that the bad disk is in a snapshot somewhere
9440 com::ErrorInfo info;
9441 return setError(E_FAIL,
9442 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
9443 puuidSnapshot->raw(),
9444 info.getText().raw());
9445 }
9446 else
9447 return rc;
9448 }
9449
9450 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
9451
9452 if (medium->i_getType() == MediumType_Immutable)
9453 {
9454 if (i_isSnapshotMachine())
9455 return setError(E_FAIL,
9456 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9457 "of the virtual machine '%s' ('%s')"),
9458 medium->i_getLocationFull().c_str(),
9459 dev.uuid.raw(),
9460 puuidSnapshot->raw(),
9461 mUserData->s.strName.c_str(),
9462 mData->m_strConfigFileFull.c_str());
9463
9464 return setError(E_FAIL,
9465 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9466 medium->i_getLocationFull().c_str(),
9467 dev.uuid.raw(),
9468 mUserData->s.strName.c_str(),
9469 mData->m_strConfigFileFull.c_str());
9470 }
9471
9472 if (medium->i_getType() == MediumType_MultiAttach)
9473 {
9474 if (i_isSnapshotMachine())
9475 return setError(E_FAIL,
9476 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9477 "of the virtual machine '%s' ('%s')"),
9478 medium->i_getLocationFull().c_str(),
9479 dev.uuid.raw(),
9480 puuidSnapshot->raw(),
9481 mUserData->s.strName.c_str(),
9482 mData->m_strConfigFileFull.c_str());
9483
9484 return setError(E_FAIL,
9485 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9486 medium->i_getLocationFull().c_str(),
9487 dev.uuid.raw(),
9488 mUserData->s.strName.c_str(),
9489 mData->m_strConfigFileFull.c_str());
9490 }
9491
9492 if ( !i_isSnapshotMachine()
9493 && medium->i_getChildren().size() != 0
9494 )
9495 return setError(E_FAIL,
9496 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
9497 "because it has %d differencing child hard disks"),
9498 medium->i_getLocationFull().c_str(),
9499 dev.uuid.raw(),
9500 mUserData->s.strName.c_str(),
9501 mData->m_strConfigFileFull.c_str(),
9502 medium->i_getChildren().size());
9503
9504 if (i_findAttachment(*mMediumAttachments.data(),
9505 medium))
9506 return setError(E_FAIL,
9507 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
9508 medium->i_getLocationFull().c_str(),
9509 dev.uuid.raw(),
9510 mUserData->s.strName.c_str(),
9511 mData->m_strConfigFileFull.c_str());
9512
9513 break;
9514 }
9515
9516 default:
9517 return setError(E_FAIL,
9518 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
9519 medium->i_getLocationFull().c_str(),
9520 mUserData->s.strName.c_str(),
9521 mData->m_strConfigFileFull.c_str());
9522 }
9523
9524 if (FAILED(rc))
9525 break;
9526
9527 /* Bandwidth groups are loaded at this point. */
9528 ComObjPtr<BandwidthGroup> pBwGroup;
9529
9530 if (!dev.strBwGroup.isEmpty())
9531 {
9532 rc = mBandwidthControl->i_getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
9533 if (FAILED(rc))
9534 return setError(E_FAIL,
9535 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
9536 medium->i_getLocationFull().c_str(),
9537 dev.strBwGroup.c_str(),
9538 mUserData->s.strName.c_str(),
9539 mData->m_strConfigFileFull.c_str());
9540 pBwGroup->i_reference();
9541 }
9542
9543 const Utf8Str controllerName = aStorageController->i_getName();
9544 ComObjPtr<MediumAttachment> pAttachment;
9545 pAttachment.createObject();
9546 rc = pAttachment->init(this,
9547 medium,
9548 controllerName,
9549 dev.lPort,
9550 dev.lDevice,
9551 dev.deviceType,
9552 false,
9553 dev.fPassThrough,
9554 dev.fTempEject,
9555 dev.fNonRotational,
9556 dev.fDiscard,
9557 dev.fHotPluggable,
9558 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->i_getName());
9559 if (FAILED(rc)) break;
9560
9561 /* associate the medium with this machine and snapshot */
9562 if (!medium.isNull())
9563 {
9564 AutoCaller medCaller(medium);
9565 if (FAILED(medCaller.rc())) return medCaller.rc();
9566 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
9567
9568 if (i_isSnapshotMachine())
9569 rc = medium->i_addBackReference(mData->mUuid, *puuidSnapshot);
9570 else
9571 rc = medium->i_addBackReference(mData->mUuid);
9572 /* If the medium->addBackReference fails it sets an appropriate
9573 * error message, so no need to do any guesswork here. */
9574
9575 if (puuidRegistry)
9576 // caller wants registry ID to be set on all attached media (OVF import case)
9577 medium->i_addRegistry(*puuidRegistry);
9578 }
9579
9580 if (FAILED(rc))
9581 break;
9582
9583 /* back up mMediumAttachments to let registeredInit() properly rollback
9584 * on failure (= limited accessibility) */
9585 i_setModified(IsModified_Storage);
9586 mMediumAttachments.backup();
9587 mMediumAttachments->push_back(pAttachment);
9588 }
9589
9590 return rc;
9591}
9592
9593/**
9594 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
9595 *
9596 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
9597 * @param aSnapshot where to return the found snapshot
9598 * @param aSetError true to set extended error info on failure
9599 */
9600HRESULT Machine::i_findSnapshotById(const Guid &aId,
9601 ComObjPtr<Snapshot> &aSnapshot,
9602 bool aSetError /* = false */)
9603{
9604 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9605
9606 if (!mData->mFirstSnapshot)
9607 {
9608 if (aSetError)
9609 return setError(E_FAIL, tr("This machine does not have any snapshots"));
9610 return E_FAIL;
9611 }
9612
9613 if (aId.isZero())
9614 aSnapshot = mData->mFirstSnapshot;
9615 else
9616 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(aId.ref());
9617
9618 if (!aSnapshot)
9619 {
9620 if (aSetError)
9621 return setError(E_FAIL,
9622 tr("Could not find a snapshot with UUID {%s}"),
9623 aId.toString().c_str());
9624 return E_FAIL;
9625 }
9626
9627 return S_OK;
9628}
9629
9630/**
9631 * Returns the snapshot with the given name or fails of no such snapshot.
9632 *
9633 * @param strName snapshot name to find
9634 * @param aSnapshot where to return the found snapshot
9635 * @param aSetError true to set extended error info on failure
9636 */
9637HRESULT Machine::i_findSnapshotByName(const Utf8Str &strName,
9638 ComObjPtr<Snapshot> &aSnapshot,
9639 bool aSetError /* = false */)
9640{
9641 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
9642
9643 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9644
9645 if (!mData->mFirstSnapshot)
9646 {
9647 if (aSetError)
9648 return setError(VBOX_E_OBJECT_NOT_FOUND,
9649 tr("This machine does not have any snapshots"));
9650 return VBOX_E_OBJECT_NOT_FOUND;
9651 }
9652
9653 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(strName);
9654
9655 if (!aSnapshot)
9656 {
9657 if (aSetError)
9658 return setError(VBOX_E_OBJECT_NOT_FOUND,
9659 tr("Could not find a snapshot named '%s'"), strName.c_str());
9660 return VBOX_E_OBJECT_NOT_FOUND;
9661 }
9662
9663 return S_OK;
9664}
9665
9666/**
9667 * Returns a storage controller object with the given name.
9668 *
9669 * @param aName storage controller name to find
9670 * @param aStorageController where to return the found storage controller
9671 * @param aSetError true to set extended error info on failure
9672 */
9673HRESULT Machine::i_getStorageControllerByName(const Utf8Str &aName,
9674 ComObjPtr<StorageController> &aStorageController,
9675 bool aSetError /* = false */)
9676{
9677 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9678
9679 for (StorageControllerList::const_iterator
9680 it = mStorageControllers->begin();
9681 it != mStorageControllers->end();
9682 ++it)
9683 {
9684 if ((*it)->i_getName() == aName)
9685 {
9686 aStorageController = (*it);
9687 return S_OK;
9688 }
9689 }
9690
9691 if (aSetError)
9692 return setError(VBOX_E_OBJECT_NOT_FOUND,
9693 tr("Could not find a storage controller named '%s'"),
9694 aName.c_str());
9695 return VBOX_E_OBJECT_NOT_FOUND;
9696}
9697
9698/**
9699 * Returns a USB controller object with the given name.
9700 *
9701 * @param aName USB controller name to find
9702 * @param aUSBController where to return the found USB controller
9703 * @param aSetError true to set extended error info on failure
9704 */
9705HRESULT Machine::i_getUSBControllerByName(const Utf8Str &aName,
9706 ComObjPtr<USBController> &aUSBController,
9707 bool aSetError /* = false */)
9708{
9709 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9710
9711 for (USBControllerList::const_iterator
9712 it = mUSBControllers->begin();
9713 it != mUSBControllers->end();
9714 ++it)
9715 {
9716 if ((*it)->i_getName() == aName)
9717 {
9718 aUSBController = (*it);
9719 return S_OK;
9720 }
9721 }
9722
9723 if (aSetError)
9724 return setError(VBOX_E_OBJECT_NOT_FOUND,
9725 tr("Could not find a storage controller named '%s'"),
9726 aName.c_str());
9727 return VBOX_E_OBJECT_NOT_FOUND;
9728}
9729
9730/**
9731 * Returns the number of USB controller instance of the given type.
9732 *
9733 * @param enmType USB controller type.
9734 */
9735ULONG Machine::i_getUSBControllerCountByType(USBControllerType_T enmType)
9736{
9737 ULONG cCtrls = 0;
9738
9739 for (USBControllerList::const_iterator
9740 it = mUSBControllers->begin();
9741 it != mUSBControllers->end();
9742 ++it)
9743 {
9744 if ((*it)->i_getControllerType() == enmType)
9745 cCtrls++;
9746 }
9747
9748 return cCtrls;
9749}
9750
9751HRESULT Machine::i_getMediumAttachmentsOfController(const Utf8Str &aName,
9752 MediumAttachmentList &atts)
9753{
9754 AutoCaller autoCaller(this);
9755 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9756
9757 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9758
9759 for (MediumAttachmentList::const_iterator
9760 it = mMediumAttachments->begin();
9761 it != mMediumAttachments->end();
9762 ++it)
9763 {
9764 const ComObjPtr<MediumAttachment> &pAtt = *it;
9765 // should never happen, but deal with NULL pointers in the list.
9766 AssertContinue(!pAtt.isNull());
9767
9768 // getControllerName() needs caller+read lock
9769 AutoCaller autoAttCaller(pAtt);
9770 if (FAILED(autoAttCaller.rc()))
9771 {
9772 atts.clear();
9773 return autoAttCaller.rc();
9774 }
9775 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
9776
9777 if (pAtt->i_getControllerName() == aName)
9778 atts.push_back(pAtt);
9779 }
9780
9781 return S_OK;
9782}
9783
9784
9785/**
9786 * Helper for #i_saveSettings. Cares about renaming the settings directory and
9787 * file if the machine name was changed and about creating a new settings file
9788 * if this is a new machine.
9789 *
9790 * @note Must be never called directly but only from #saveSettings().
9791 */
9792HRESULT Machine::i_prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
9793{
9794 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9795
9796 HRESULT rc = S_OK;
9797
9798 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
9799
9800 /// @todo need to handle primary group change, too
9801
9802 /* attempt to rename the settings file if machine name is changed */
9803 if ( mUserData->s.fNameSync
9804 && mUserData.isBackedUp()
9805 && ( mUserData.backedUpData()->s.strName != mUserData->s.strName
9806 || mUserData.backedUpData()->s.llGroups.front() != mUserData->s.llGroups.front())
9807 )
9808 {
9809 bool dirRenamed = false;
9810 bool fileRenamed = false;
9811
9812 Utf8Str configFile, newConfigFile;
9813 Utf8Str configFilePrev, newConfigFilePrev;
9814 Utf8Str configDir, newConfigDir;
9815
9816 do
9817 {
9818 int vrc = VINF_SUCCESS;
9819
9820 Utf8Str name = mUserData.backedUpData()->s.strName;
9821 Utf8Str newName = mUserData->s.strName;
9822 Utf8Str group = mUserData.backedUpData()->s.llGroups.front();
9823 if (group == "/")
9824 group.setNull();
9825 Utf8Str newGroup = mUserData->s.llGroups.front();
9826 if (newGroup == "/")
9827 newGroup.setNull();
9828
9829 configFile = mData->m_strConfigFileFull;
9830
9831 /* first, rename the directory if it matches the group and machine name */
9832 Utf8Str groupPlusName = Utf8StrFmt("%s%c%s",
9833 group.c_str(), RTPATH_DELIMITER, name.c_str());
9834 /** @todo hack, make somehow use of ComposeMachineFilename */
9835 if (mUserData->s.fDirectoryIncludesUUID)
9836 groupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9837 Utf8Str newGroupPlusName = Utf8StrFmt("%s%c%s",
9838 newGroup.c_str(), RTPATH_DELIMITER, newName.c_str());
9839 /** @todo hack, make somehow use of ComposeMachineFilename */
9840 if (mUserData->s.fDirectoryIncludesUUID)
9841 newGroupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9842 configDir = configFile;
9843 configDir.stripFilename();
9844 newConfigDir = configDir;
9845 if ( configDir.length() >= groupPlusName.length()
9846 && !RTPathCompare(configDir.substr(configDir.length() - groupPlusName.length(), groupPlusName.length()).c_str(),
9847 groupPlusName.c_str()))
9848 {
9849 newConfigDir = newConfigDir.substr(0, configDir.length() - groupPlusName.length());
9850 Utf8Str newConfigBaseDir(newConfigDir);
9851 newConfigDir.append(newGroupPlusName);
9852 /* consistency: use \ if appropriate on the platform */
9853 RTPathChangeToDosSlashes(newConfigDir.mutableRaw(), false);
9854 /* new dir and old dir cannot be equal here because of 'if'
9855 * above and because name != newName */
9856 Assert(configDir != newConfigDir);
9857 if (!fSettingsFileIsNew)
9858 {
9859 /* perform real rename only if the machine is not new */
9860 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9861 if ( vrc == VERR_FILE_NOT_FOUND
9862 || vrc == VERR_PATH_NOT_FOUND)
9863 {
9864 /* create the parent directory, then retry renaming */
9865 Utf8Str parent(newConfigDir);
9866 parent.stripFilename();
9867 (void)RTDirCreateFullPath(parent.c_str(), 0700);
9868 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9869 }
9870 if (RT_FAILURE(vrc))
9871 {
9872 rc = setError(E_FAIL,
9873 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
9874 configDir.c_str(),
9875 newConfigDir.c_str(),
9876 vrc);
9877 break;
9878 }
9879 /* delete subdirectories which are no longer needed */
9880 Utf8Str dir(configDir);
9881 dir.stripFilename();
9882 while (dir != newConfigBaseDir && dir != ".")
9883 {
9884 vrc = RTDirRemove(dir.c_str());
9885 if (RT_FAILURE(vrc))
9886 break;
9887 dir.stripFilename();
9888 }
9889 dirRenamed = true;
9890 }
9891 }
9892
9893 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
9894 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
9895
9896 /* then try to rename the settings file itself */
9897 if (newConfigFile != configFile)
9898 {
9899 /* get the path to old settings file in renamed directory */
9900 configFile = Utf8StrFmt("%s%c%s",
9901 newConfigDir.c_str(),
9902 RTPATH_DELIMITER,
9903 RTPathFilename(configFile.c_str()));
9904 if (!fSettingsFileIsNew)
9905 {
9906 /* perform real rename only if the machine is not new */
9907 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
9908 if (RT_FAILURE(vrc))
9909 {
9910 rc = setError(E_FAIL,
9911 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
9912 configFile.c_str(),
9913 newConfigFile.c_str(),
9914 vrc);
9915 break;
9916 }
9917 fileRenamed = true;
9918 configFilePrev = configFile;
9919 configFilePrev += "-prev";
9920 newConfigFilePrev = newConfigFile;
9921 newConfigFilePrev += "-prev";
9922 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
9923 }
9924 }
9925
9926 // update m_strConfigFileFull amd mConfigFile
9927 mData->m_strConfigFileFull = newConfigFile;
9928 // compute the relative path too
9929 mParent->i_copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
9930
9931 // store the old and new so that VirtualBox::i_saveSettings() can update
9932 // the media registry
9933 if ( mData->mRegistered
9934 && (configDir != newConfigDir || configFile != newConfigFile))
9935 {
9936 mParent->i_rememberMachineNameChangeForMedia(configDir, newConfigDir);
9937
9938 if (pfNeedsGlobalSaveSettings)
9939 *pfNeedsGlobalSaveSettings = true;
9940 }
9941
9942 // in the saved state file path, replace the old directory with the new directory
9943 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
9944 {
9945 Utf8Str strStateFileName = mSSData->strStateFilePath.c_str() + configDir.length();
9946 mSSData->strStateFilePath = newConfigDir + strStateFileName;
9947 }
9948
9949 // and do the same thing for the saved state file paths of all the online snapshots
9950 if (mData->mFirstSnapshot)
9951 mData->mFirstSnapshot->i_updateSavedStatePaths(configDir.c_str(),
9952 newConfigDir.c_str());
9953 }
9954 while (0);
9955
9956 if (FAILED(rc))
9957 {
9958 /* silently try to rename everything back */
9959 if (fileRenamed)
9960 {
9961 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
9962 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
9963 }
9964 if (dirRenamed)
9965 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
9966 }
9967
9968 if (FAILED(rc)) return rc;
9969 }
9970
9971 if (fSettingsFileIsNew)
9972 {
9973 /* create a virgin config file */
9974 int vrc = VINF_SUCCESS;
9975
9976 /* ensure the settings directory exists */
9977 Utf8Str path(mData->m_strConfigFileFull);
9978 path.stripFilename();
9979 if (!RTDirExists(path.c_str()))
9980 {
9981 vrc = RTDirCreateFullPath(path.c_str(), 0700);
9982 if (RT_FAILURE(vrc))
9983 {
9984 return setError(E_FAIL,
9985 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
9986 path.c_str(),
9987 vrc);
9988 }
9989 }
9990
9991 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
9992 path = Utf8Str(mData->m_strConfigFileFull);
9993 RTFILE f = NIL_RTFILE;
9994 vrc = RTFileOpen(&f, path.c_str(),
9995 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
9996 if (RT_FAILURE(vrc))
9997 return setError(E_FAIL,
9998 tr("Could not create the settings file '%s' (%Rrc)"),
9999 path.c_str(),
10000 vrc);
10001 RTFileClose(f);
10002 }
10003
10004 return rc;
10005}
10006
10007/**
10008 * Saves and commits machine data, user data and hardware data.
10009 *
10010 * Note that on failure, the data remains uncommitted.
10011 *
10012 * @a aFlags may combine the following flags:
10013 *
10014 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
10015 * Used when saving settings after an operation that makes them 100%
10016 * correspond to the settings from the current snapshot.
10017 * - SaveS_Force: settings will be saved without doing a deep compare of the
10018 * settings structures. This is used when this is called because snapshots
10019 * have changed to avoid the overhead of the deep compare.
10020 *
10021 * @note Must be called from under this object's write lock. Locks children for
10022 * writing.
10023 *
10024 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
10025 * initialized to false and that will be set to true by this function if
10026 * the caller must invoke VirtualBox::i_saveSettings() because the global
10027 * settings have changed. This will happen if a machine rename has been
10028 * saved and the global machine and media registries will therefore need
10029 * updating.
10030 * @param aFlags Flags.
10031 */
10032HRESULT Machine::i_saveSettings(bool *pfNeedsGlobalSaveSettings,
10033 int aFlags /*= 0*/)
10034{
10035 LogFlowThisFuncEnter();
10036
10037 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10038
10039 /* make sure child objects are unable to modify the settings while we are
10040 * saving them */
10041 i_ensureNoStateDependencies();
10042
10043 AssertReturn(!i_isSnapshotMachine(),
10044 E_FAIL);
10045
10046 HRESULT rc = S_OK;
10047 bool fNeedsWrite = false;
10048
10049 /* First, prepare to save settings. It will care about renaming the
10050 * settings directory and file if the machine name was changed and about
10051 * creating a new settings file if this is a new machine. */
10052 rc = i_prepareSaveSettings(pfNeedsGlobalSaveSettings);
10053 if (FAILED(rc)) return rc;
10054
10055 // keep a pointer to the current settings structures
10056 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
10057 settings::MachineConfigFile *pNewConfig = NULL;
10058
10059 try
10060 {
10061 // make a fresh one to have everyone write stuff into
10062 pNewConfig = new settings::MachineConfigFile(NULL);
10063 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
10064
10065 // now go and copy all the settings data from COM to the settings structures
10066 // (this calls i_saveSettings() on all the COM objects in the machine)
10067 i_copyMachineDataToSettings(*pNewConfig);
10068
10069 if (aFlags & SaveS_ResetCurStateModified)
10070 {
10071 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
10072 mData->mCurrentStateModified = FALSE;
10073 fNeedsWrite = true; // always, no need to compare
10074 }
10075 else if (aFlags & SaveS_Force)
10076 {
10077 fNeedsWrite = true; // always, no need to compare
10078 }
10079 else
10080 {
10081 if (!mData->mCurrentStateModified)
10082 {
10083 // do a deep compare of the settings that we just saved with the settings
10084 // previously stored in the config file; this invokes MachineConfigFile::operator==
10085 // which does a deep compare of all the settings, which is expensive but less expensive
10086 // than writing out XML in vain
10087 bool fAnySettingsChanged = !(*pNewConfig == *pOldConfig);
10088
10089 // could still be modified if any settings changed
10090 mData->mCurrentStateModified = fAnySettingsChanged;
10091
10092 fNeedsWrite = fAnySettingsChanged;
10093 }
10094 else
10095 fNeedsWrite = true;
10096 }
10097
10098 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
10099
10100 if (fNeedsWrite)
10101 // now spit it all out!
10102 pNewConfig->write(mData->m_strConfigFileFull);
10103
10104 mData->pMachineConfigFile = pNewConfig;
10105 delete pOldConfig;
10106 i_commit();
10107
10108 // after saving settings, we are no longer different from the XML on disk
10109 mData->flModifications = 0;
10110 }
10111 catch (HRESULT err)
10112 {
10113 // we assume that error info is set by the thrower
10114 rc = err;
10115
10116 // restore old config
10117 delete pNewConfig;
10118 mData->pMachineConfigFile = pOldConfig;
10119 }
10120 catch (...)
10121 {
10122 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10123 }
10124
10125 if (fNeedsWrite)
10126 {
10127 /* Fire the data change event, even on failure (since we've already
10128 * committed all data). This is done only for SessionMachines because
10129 * mutable Machine instances are always not registered (i.e. private
10130 * to the client process that creates them) and thus don't need to
10131 * inform callbacks. */
10132 if (i_isSessionMachine())
10133 mParent->i_onMachineDataChange(mData->mUuid);
10134 }
10135
10136 LogFlowThisFunc(("rc=%08X\n", rc));
10137 LogFlowThisFuncLeave();
10138 return rc;
10139}
10140
10141/**
10142 * Implementation for saving the machine settings into the given
10143 * settings::MachineConfigFile instance. This copies machine extradata
10144 * from the previous machine config file in the instance data, if any.
10145 *
10146 * This gets called from two locations:
10147 *
10148 * -- Machine::i_saveSettings(), during the regular XML writing;
10149 *
10150 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
10151 * exported to OVF and we write the VirtualBox proprietary XML
10152 * into a <vbox:Machine> tag.
10153 *
10154 * This routine fills all the fields in there, including snapshots, *except*
10155 * for the following:
10156 *
10157 * -- fCurrentStateModified. There is some special logic associated with that.
10158 *
10159 * The caller can then call MachineConfigFile::write() or do something else
10160 * with it.
10161 *
10162 * Caller must hold the machine lock!
10163 *
10164 * This throws XML errors and HRESULT, so the caller must have a catch block!
10165 */
10166void Machine::i_copyMachineDataToSettings(settings::MachineConfigFile &config)
10167{
10168 // deep copy extradata, being extra careful with self assignment (the STL
10169 // map assignment on Mac OS X clang based Xcode isn't checking)
10170 if (&config != mData->pMachineConfigFile)
10171 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
10172
10173 config.uuid = mData->mUuid;
10174
10175 // copy name, description, OS type, teleport, UTC etc.
10176 config.machineUserData = mUserData->s;
10177
10178 if ( mData->mMachineState == MachineState_Saved
10179 || mData->mMachineState == MachineState_Restoring
10180 // when doing certain snapshot operations we may or may not have
10181 // a saved state in the current state, so keep everything as is
10182 || ( ( mData->mMachineState == MachineState_Snapshotting
10183 || mData->mMachineState == MachineState_DeletingSnapshot
10184 || mData->mMachineState == MachineState_RestoringSnapshot)
10185 && (!mSSData->strStateFilePath.isEmpty())
10186 )
10187 )
10188 {
10189 Assert(!mSSData->strStateFilePath.isEmpty());
10190 /* try to make the file name relative to the settings file dir */
10191 i_copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
10192 }
10193 else
10194 {
10195 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
10196 config.strStateFile.setNull();
10197 }
10198
10199 if (mData->mCurrentSnapshot)
10200 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->i_getId();
10201 else
10202 config.uuidCurrentSnapshot.clear();
10203
10204 config.timeLastStateChange = mData->mLastStateChange;
10205 config.fAborted = (mData->mMachineState == MachineState_Aborted);
10206 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
10207
10208 HRESULT rc = i_saveHardware(config.hardwareMachine, &config.debugging, &config.autostart);
10209 if (FAILED(rc)) throw rc;
10210
10211 // save machine's media registry if this is VirtualBox 4.0 or later
10212 if (config.canHaveOwnMediaRegistry())
10213 {
10214 // determine machine folder
10215 Utf8Str strMachineFolder = i_getSettingsFileFull();
10216 strMachineFolder.stripFilename();
10217 mParent->i_saveMediaRegistry(config.mediaRegistry,
10218 i_getId(), // only media with registry ID == machine UUID
10219 strMachineFolder);
10220 // this throws HRESULT
10221 }
10222
10223 // save snapshots
10224 rc = i_saveAllSnapshots(config);
10225 if (FAILED(rc)) throw rc;
10226}
10227
10228/**
10229 * Saves all snapshots of the machine into the given machine config file. Called
10230 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
10231 * @param config
10232 * @return
10233 */
10234HRESULT Machine::i_saveAllSnapshots(settings::MachineConfigFile &config)
10235{
10236 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10237
10238 HRESULT rc = S_OK;
10239
10240 try
10241 {
10242 config.llFirstSnapshot.clear();
10243
10244 if (mData->mFirstSnapshot)
10245 {
10246 // the settings use a list for "the first snapshot"
10247 config.llFirstSnapshot.push_back(settings::Snapshot::Empty);
10248
10249 // get reference to the snapshot on the list and work on that
10250 // element straight in the list to avoid excessive copying later
10251 rc = mData->mFirstSnapshot->i_saveSnapshot(config.llFirstSnapshot.back());
10252 if (FAILED(rc)) throw rc;
10253 }
10254
10255// if (mType == IsSessionMachine)
10256// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
10257
10258 }
10259 catch (HRESULT err)
10260 {
10261 /* we assume that error info is set by the thrower */
10262 rc = err;
10263 }
10264 catch (...)
10265 {
10266 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10267 }
10268
10269 return rc;
10270}
10271
10272/**
10273 * Saves the VM hardware configuration. It is assumed that the
10274 * given node is empty.
10275 *
10276 * @param data Reference to the settings object for the hardware config.
10277 * @param pDbg Pointer to the settings object for the debugging config
10278 * which happens to live in mHWData.
10279 * @param pAutostart Pointer to the settings object for the autostart config
10280 * which happens to live in mHWData.
10281 */
10282HRESULT Machine::i_saveHardware(settings::Hardware &data, settings::Debugging *pDbg,
10283 settings::Autostart *pAutostart)
10284{
10285 HRESULT rc = S_OK;
10286
10287 try
10288 {
10289 /* The hardware version attribute (optional).
10290 Automatically upgrade from 1 to current default hardware version
10291 when there is no saved state. (ugly!) */
10292 if ( mHWData->mHWVersion == "1"
10293 && mSSData->strStateFilePath.isEmpty()
10294 )
10295 mHWData->mHWVersion = Utf8StrFmt("%d", SchemaDefs::DefaultHardwareVersion);
10296
10297 data.strVersion = mHWData->mHWVersion;
10298 data.uuid = mHWData->mHardwareUUID;
10299
10300 // CPU
10301 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
10302 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
10303 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
10304 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
10305 data.fUnrestrictedExecution = !!mHWData->mHWVirtExUXEnabled;
10306 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
10307 data.fPAE = !!mHWData->mPAEEnabled;
10308 data.enmLongMode = mHWData->mLongMode;
10309 data.fTripleFaultReset = !!mHWData->mTripleFaultReset;
10310 data.fAPIC = !!mHWData->mAPIC;
10311 data.fX2APIC = !!mHWData->mX2APIC;
10312 data.cCPUs = mHWData->mCPUCount;
10313 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
10314 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
10315 data.uCpuIdPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
10316 data.strCpuProfile = mHWData->mCpuProfile;
10317
10318 data.llCpus.clear();
10319 if (data.fCpuHotPlug)
10320 {
10321 for (unsigned idx = 0; idx < data.cCPUs; ++idx)
10322 {
10323 if (mHWData->mCPUAttached[idx])
10324 {
10325 settings::Cpu cpu;
10326 cpu.ulId = idx;
10327 data.llCpus.push_back(cpu);
10328 }
10329 }
10330 }
10331
10332 /* Standard and Extended CPUID leafs. */
10333 data.llCpuIdLeafs.clear();
10334 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++idx)
10335 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
10336 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
10337 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++idx)
10338 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
10339 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
10340
10341 // memory
10342 data.ulMemorySizeMB = mHWData->mMemorySize;
10343 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
10344
10345 // firmware
10346 data.firmwareType = mHWData->mFirmwareType;
10347
10348 // HID
10349 data.pointingHIDType = mHWData->mPointingHIDType;
10350 data.keyboardHIDType = mHWData->mKeyboardHIDType;
10351
10352 // chipset
10353 data.chipsetType = mHWData->mChipsetType;
10354
10355 // paravirt
10356 data.paravirtProvider = mHWData->mParavirtProvider;
10357 data.strParavirtDebug = mHWData->mParavirtDebug;
10358
10359 // emulated USB card reader
10360 data.fEmulatedUSBCardReader = !!mHWData->mEmulatedUSBCardReaderEnabled;
10361
10362 // HPET
10363 data.fHPETEnabled = !!mHWData->mHPETEnabled;
10364
10365 // boot order
10366 data.mapBootOrder.clear();
10367 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
10368 data.mapBootOrder[i] = mHWData->mBootOrder[i];
10369
10370 // display
10371 data.graphicsControllerType = mHWData->mGraphicsControllerType;
10372 data.ulVRAMSizeMB = mHWData->mVRAMSize;
10373 data.cMonitors = mHWData->mMonitorCount;
10374 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
10375 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
10376 data.ulVideoCaptureHorzRes = mHWData->mVideoCaptureWidth;
10377 data.ulVideoCaptureVertRes = mHWData->mVideoCaptureHeight;
10378 data.ulVideoCaptureRate = mHWData->mVideoCaptureRate;
10379 data.ulVideoCaptureFPS = mHWData->mVideoCaptureFPS;
10380 data.fVideoCaptureEnabled = !!mHWData->mVideoCaptureEnabled;
10381 for (unsigned i = 0; i < sizeof(data.u64VideoCaptureScreens) * 8; ++i)
10382 {
10383 if (mHWData->maVideoCaptureScreens[i])
10384 ASMBitSet(&data.u64VideoCaptureScreens, i);
10385 else
10386 ASMBitClear(&data.u64VideoCaptureScreens, i);
10387 }
10388 /* store relative video capture file if possible */
10389 i_copyPathRelativeToMachine(mHWData->mVideoCaptureFile, data.strVideoCaptureFile);
10390
10391 /* VRDEServer settings (optional) */
10392 rc = mVRDEServer->i_saveSettings(data.vrdeSettings);
10393 if (FAILED(rc)) throw rc;
10394
10395 /* BIOS (required) */
10396 rc = mBIOSSettings->i_saveSettings(data.biosSettings);
10397 if (FAILED(rc)) throw rc;
10398
10399 /* USB Controller (required) */
10400 data.usbSettings.llUSBControllers.clear();
10401 for (USBControllerList::const_iterator
10402 it = mUSBControllers->begin();
10403 it != mUSBControllers->end();
10404 ++it)
10405 {
10406 ComObjPtr<USBController> ctrl = *it;
10407 settings::USBController settingsCtrl;
10408
10409 settingsCtrl.strName = ctrl->i_getName();
10410 settingsCtrl.enmType = ctrl->i_getControllerType();
10411
10412 data.usbSettings.llUSBControllers.push_back(settingsCtrl);
10413 }
10414
10415 /* USB device filters (required) */
10416 rc = mUSBDeviceFilters->i_saveSettings(data.usbSettings);
10417 if (FAILED(rc)) throw rc;
10418
10419 /* Network adapters (required) */
10420 size_t uMaxNICs = RT_MIN(Global::getMaxNetworkAdapters(mHWData->mChipsetType), mNetworkAdapters.size());
10421 data.llNetworkAdapters.clear();
10422 /* Write out only the nominal number of network adapters for this
10423 * chipset type. Since Machine::commit() hasn't been called there
10424 * may be extra NIC settings in the vector. */
10425 for (size_t slot = 0; slot < uMaxNICs; ++slot)
10426 {
10427 settings::NetworkAdapter nic;
10428 nic.ulSlot = (uint32_t)slot;
10429 /* paranoia check... must not be NULL, but must not crash either. */
10430 if (mNetworkAdapters[slot])
10431 {
10432 if (mNetworkAdapters[slot]->i_hasDefaults())
10433 continue;
10434
10435 rc = mNetworkAdapters[slot]->i_saveSettings(nic);
10436 if (FAILED(rc)) throw rc;
10437
10438 data.llNetworkAdapters.push_back(nic);
10439 }
10440 }
10441
10442 /* Serial ports */
10443 data.llSerialPorts.clear();
10444 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
10445 {
10446 if (mSerialPorts[slot]->i_hasDefaults())
10447 continue;
10448
10449 settings::SerialPort s;
10450 s.ulSlot = slot;
10451 rc = mSerialPorts[slot]->i_saveSettings(s);
10452 if (FAILED(rc)) return rc;
10453
10454 data.llSerialPorts.push_back(s);
10455 }
10456
10457 /* Parallel ports */
10458 data.llParallelPorts.clear();
10459 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
10460 {
10461 if (mParallelPorts[slot]->i_hasDefaults())
10462 continue;
10463
10464 settings::ParallelPort p;
10465 p.ulSlot = slot;
10466 rc = mParallelPorts[slot]->i_saveSettings(p);
10467 if (FAILED(rc)) return rc;
10468
10469 data.llParallelPorts.push_back(p);
10470 }
10471
10472 /* Audio adapter */
10473 rc = mAudioAdapter->i_saveSettings(data.audioAdapter);
10474 if (FAILED(rc)) return rc;
10475
10476 rc = i_saveStorageControllers(data.storage);
10477 if (FAILED(rc)) return rc;
10478
10479 /* Shared folders */
10480 data.llSharedFolders.clear();
10481 for (HWData::SharedFolderList::const_iterator
10482 it = mHWData->mSharedFolders.begin();
10483 it != mHWData->mSharedFolders.end();
10484 ++it)
10485 {
10486 SharedFolder *pSF = *it;
10487 AutoCaller sfCaller(pSF);
10488 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
10489 settings::SharedFolder sf;
10490 sf.strName = pSF->i_getName();
10491 sf.strHostPath = pSF->i_getHostPath();
10492 sf.fWritable = !!pSF->i_isWritable();
10493 sf.fAutoMount = !!pSF->i_isAutoMounted();
10494
10495 data.llSharedFolders.push_back(sf);
10496 }
10497
10498 // clipboard
10499 data.clipboardMode = mHWData->mClipboardMode;
10500
10501 // drag'n'drop
10502 data.dndMode = mHWData->mDnDMode;
10503
10504 /* Guest */
10505 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
10506
10507 // IO settings
10508 data.ioSettings.fIOCacheEnabled = !!mHWData->mIOCacheEnabled;
10509 data.ioSettings.ulIOCacheSize = mHWData->mIOCacheSize;
10510
10511 /* BandwidthControl (required) */
10512 rc = mBandwidthControl->i_saveSettings(data.ioSettings);
10513 if (FAILED(rc)) throw rc;
10514
10515 /* Host PCI devices */
10516 data.pciAttachments.clear();
10517 for (HWData::PCIDeviceAssignmentList::const_iterator
10518 it = mHWData->mPCIDeviceAssignments.begin();
10519 it != mHWData->mPCIDeviceAssignments.end();
10520 ++it)
10521 {
10522 ComObjPtr<PCIDeviceAttachment> pda = *it;
10523 settings::HostPCIDeviceAttachment hpda;
10524
10525 rc = pda->i_saveSettings(hpda);
10526 if (FAILED(rc)) throw rc;
10527
10528 data.pciAttachments.push_back(hpda);
10529 }
10530
10531 // guest properties
10532 data.llGuestProperties.clear();
10533#ifdef VBOX_WITH_GUEST_PROPS
10534 for (HWData::GuestPropertyMap::const_iterator
10535 it = mHWData->mGuestProperties.begin();
10536 it != mHWData->mGuestProperties.end();
10537 ++it)
10538 {
10539 HWData::GuestProperty property = it->second;
10540
10541 /* Remove transient guest properties at shutdown unless we
10542 * are saving state. Note that restoring snapshot intentionally
10543 * keeps them, they will be removed if appropriate once the final
10544 * machine state is set (as crashes etc. need to work). */
10545 if ( ( mData->mMachineState == MachineState_PoweredOff
10546 || mData->mMachineState == MachineState_Aborted
10547 || mData->mMachineState == MachineState_Teleported)
10548 && ( property.mFlags & guestProp::TRANSIENT
10549 || property.mFlags & guestProp::TRANSRESET))
10550 continue;
10551 settings::GuestProperty prop;
10552 prop.strName = it->first;
10553 prop.strValue = property.strValue;
10554 prop.timestamp = property.mTimestamp;
10555 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
10556 guestProp::writeFlags(property.mFlags, szFlags);
10557 prop.strFlags = szFlags;
10558
10559 data.llGuestProperties.push_back(prop);
10560 }
10561
10562 /* I presume this doesn't require a backup(). */
10563 mData->mGuestPropertiesModified = FALSE;
10564#endif /* VBOX_WITH_GUEST_PROPS defined */
10565
10566 *pDbg = mHWData->mDebugging;
10567 *pAutostart = mHWData->mAutostart;
10568
10569 data.strDefaultFrontend = mHWData->mDefaultFrontend;
10570 }
10571 catch (std::bad_alloc &)
10572 {
10573 return E_OUTOFMEMORY;
10574 }
10575
10576 AssertComRC(rc);
10577 return rc;
10578}
10579
10580/**
10581 * Saves the storage controller configuration.
10582 *
10583 * @param data storage settings.
10584 */
10585HRESULT Machine::i_saveStorageControllers(settings::Storage &data)
10586{
10587 data.llStorageControllers.clear();
10588
10589 for (StorageControllerList::const_iterator
10590 it = mStorageControllers->begin();
10591 it != mStorageControllers->end();
10592 ++it)
10593 {
10594 HRESULT rc;
10595 ComObjPtr<StorageController> pCtl = *it;
10596
10597 settings::StorageController ctl;
10598 ctl.strName = pCtl->i_getName();
10599 ctl.controllerType = pCtl->i_getControllerType();
10600 ctl.storageBus = pCtl->i_getStorageBus();
10601 ctl.ulInstance = pCtl->i_getInstance();
10602 ctl.fBootable = pCtl->i_getBootable();
10603
10604 /* Save the port count. */
10605 ULONG portCount;
10606 rc = pCtl->COMGETTER(PortCount)(&portCount);
10607 ComAssertComRCRet(rc, rc);
10608 ctl.ulPortCount = portCount;
10609
10610 /* Save fUseHostIOCache */
10611 BOOL fUseHostIOCache;
10612 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
10613 ComAssertComRCRet(rc, rc);
10614 ctl.fUseHostIOCache = !!fUseHostIOCache;
10615
10616 /* save the devices now. */
10617 rc = i_saveStorageDevices(pCtl, ctl);
10618 ComAssertComRCRet(rc, rc);
10619
10620 data.llStorageControllers.push_back(ctl);
10621 }
10622
10623 return S_OK;
10624}
10625
10626/**
10627 * Saves the hard disk configuration.
10628 */
10629HRESULT Machine::i_saveStorageDevices(ComObjPtr<StorageController> aStorageController,
10630 settings::StorageController &data)
10631{
10632 MediumAttachmentList atts;
10633
10634 HRESULT rc = i_getMediumAttachmentsOfController(aStorageController->i_getName(), atts);
10635 if (FAILED(rc)) return rc;
10636
10637 data.llAttachedDevices.clear();
10638 for (MediumAttachmentList::const_iterator
10639 it = atts.begin();
10640 it != atts.end();
10641 ++it)
10642 {
10643 settings::AttachedDevice dev;
10644 IMediumAttachment *iA = *it;
10645 MediumAttachment *pAttach = static_cast<MediumAttachment *>(iA);
10646 Medium *pMedium = pAttach->i_getMedium();
10647
10648 dev.deviceType = pAttach->i_getType();
10649 dev.lPort = pAttach->i_getPort();
10650 dev.lDevice = pAttach->i_getDevice();
10651 dev.fPassThrough = pAttach->i_getPassthrough();
10652 dev.fHotPluggable = pAttach->i_getHotPluggable();
10653 if (pMedium)
10654 {
10655 if (pMedium->i_isHostDrive())
10656 dev.strHostDriveSrc = pMedium->i_getLocationFull();
10657 else
10658 dev.uuid = pMedium->i_getId();
10659 dev.fTempEject = pAttach->i_getTempEject();
10660 dev.fNonRotational = pAttach->i_getNonRotational();
10661 dev.fDiscard = pAttach->i_getDiscard();
10662 }
10663
10664 dev.strBwGroup = pAttach->i_getBandwidthGroup();
10665
10666 data.llAttachedDevices.push_back(dev);
10667 }
10668
10669 return S_OK;
10670}
10671
10672/**
10673 * Saves machine state settings as defined by aFlags
10674 * (SaveSTS_* values).
10675 *
10676 * @param aFlags Combination of SaveSTS_* flags.
10677 *
10678 * @note Locks objects for writing.
10679 */
10680HRESULT Machine::i_saveStateSettings(int aFlags)
10681{
10682 if (aFlags == 0)
10683 return S_OK;
10684
10685 AutoCaller autoCaller(this);
10686 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10687
10688 /* This object's write lock is also necessary to serialize file access
10689 * (prevent concurrent reads and writes) */
10690 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10691
10692 HRESULT rc = S_OK;
10693
10694 Assert(mData->pMachineConfigFile);
10695
10696 try
10697 {
10698 if (aFlags & SaveSTS_CurStateModified)
10699 mData->pMachineConfigFile->fCurrentStateModified = true;
10700
10701 if (aFlags & SaveSTS_StateFilePath)
10702 {
10703 if (!mSSData->strStateFilePath.isEmpty())
10704 /* try to make the file name relative to the settings file dir */
10705 i_copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
10706 else
10707 mData->pMachineConfigFile->strStateFile.setNull();
10708 }
10709
10710 if (aFlags & SaveSTS_StateTimeStamp)
10711 {
10712 Assert( mData->mMachineState != MachineState_Aborted
10713 || mSSData->strStateFilePath.isEmpty());
10714
10715 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
10716
10717 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
10718/// @todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
10719 }
10720
10721 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
10722 }
10723 catch (...)
10724 {
10725 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10726 }
10727
10728 return rc;
10729}
10730
10731/**
10732 * Ensures that the given medium is added to a media registry. If this machine
10733 * was created with 4.0 or later, then the machine registry is used. Otherwise
10734 * the global VirtualBox media registry is used.
10735 *
10736 * Caller must NOT hold machine lock, media tree or any medium locks!
10737 *
10738 * @param pMedium
10739 */
10740void Machine::i_addMediumToRegistry(ComObjPtr<Medium> &pMedium)
10741{
10742 /* Paranoia checks: do not hold machine or media tree locks. */
10743 AssertReturnVoid(!isWriteLockOnCurrentThread());
10744 AssertReturnVoid(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
10745
10746 ComObjPtr<Medium> pBase;
10747 {
10748 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10749 pBase = pMedium->i_getBase();
10750 }
10751
10752 /* Paranoia checks: do not hold medium locks. */
10753 AssertReturnVoid(!pMedium->isWriteLockOnCurrentThread());
10754 AssertReturnVoid(!pBase->isWriteLockOnCurrentThread());
10755
10756 // decide which medium registry to use now that the medium is attached:
10757 Guid uuid;
10758 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
10759 // machine XML is VirtualBox 4.0 or higher:
10760 uuid = i_getId(); // machine UUID
10761 else
10762 uuid = mParent->i_getGlobalRegistryId(); // VirtualBox global registry UUID
10763
10764 if (pMedium->i_addRegistry(uuid))
10765 mParent->i_markRegistryModified(uuid);
10766
10767 /* For more complex hard disk structures it can happen that the base
10768 * medium isn't yet associated with any medium registry. Do that now. */
10769 if (pMedium != pBase)
10770 {
10771 /* Tree lock needed by Medium::addRegistry when recursing. */
10772 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10773 if (pBase->i_addRegistryRecursive(uuid))
10774 {
10775 treeLock.release();
10776 mParent->i_markRegistryModified(uuid);
10777 }
10778 }
10779}
10780
10781/**
10782 * Creates differencing hard disks for all normal hard disks attached to this
10783 * machine and a new set of attachments to refer to created disks.
10784 *
10785 * Used when taking a snapshot or when deleting the current state. Gets called
10786 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
10787 *
10788 * This method assumes that mMediumAttachments contains the original hard disk
10789 * attachments it needs to create diffs for. On success, these attachments will
10790 * be replaced with the created diffs.
10791 *
10792 * Attachments with non-normal hard disks are left as is.
10793 *
10794 * If @a aOnline is @c false then the original hard disks that require implicit
10795 * diffs will be locked for reading. Otherwise it is assumed that they are
10796 * already locked for writing (when the VM was started). Note that in the latter
10797 * case it is responsibility of the caller to lock the newly created diffs for
10798 * writing if this method succeeds.
10799 *
10800 * @param aProgress Progress object to run (must contain at least as
10801 * many operations left as the number of hard disks
10802 * attached).
10803 * @param aWeight Weight of this operation.
10804 * @param aOnline Whether the VM was online prior to this operation.
10805 *
10806 * @note The progress object is not marked as completed, neither on success nor
10807 * on failure. This is a responsibility of the caller.
10808 *
10809 * @note Locks this object and the media tree for writing.
10810 */
10811HRESULT Machine::i_createImplicitDiffs(IProgress *aProgress,
10812 ULONG aWeight,
10813 bool aOnline)
10814{
10815 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10816
10817 AutoCaller autoCaller(this);
10818 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10819
10820 AutoMultiWriteLock2 alock(this->lockHandle(),
10821 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10822
10823 /* must be in a protective state because we release the lock below */
10824 AssertReturn( mData->mMachineState == MachineState_Snapshotting
10825 || mData->mMachineState == MachineState_OnlineSnapshotting
10826 || mData->mMachineState == MachineState_LiveSnapshotting
10827 || mData->mMachineState == MachineState_RestoringSnapshot
10828 || mData->mMachineState == MachineState_DeletingSnapshot
10829 , E_FAIL);
10830
10831 HRESULT rc = S_OK;
10832
10833 // use appropriate locked media map (online or offline)
10834 MediumLockListMap lockedMediaOffline;
10835 MediumLockListMap *lockedMediaMap;
10836 if (aOnline)
10837 lockedMediaMap = &mData->mSession.mLockedMedia;
10838 else
10839 lockedMediaMap = &lockedMediaOffline;
10840
10841 try
10842 {
10843 if (!aOnline)
10844 {
10845 /* lock all attached hard disks early to detect "in use"
10846 * situations before creating actual diffs */
10847 for (MediumAttachmentList::const_iterator
10848 it = mMediumAttachments->begin();
10849 it != mMediumAttachments->end();
10850 ++it)
10851 {
10852 MediumAttachment *pAtt = *it;
10853 if (pAtt->i_getType() == DeviceType_HardDisk)
10854 {
10855 Medium *pMedium = pAtt->i_getMedium();
10856 Assert(pMedium);
10857
10858 MediumLockList *pMediumLockList(new MediumLockList());
10859 alock.release();
10860 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
10861 NULL /* pToLockWrite */,
10862 false /* fMediumLockWriteAll */,
10863 NULL,
10864 *pMediumLockList);
10865 alock.acquire();
10866 if (FAILED(rc))
10867 {
10868 delete pMediumLockList;
10869 throw rc;
10870 }
10871 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10872 if (FAILED(rc))
10873 {
10874 throw setError(rc,
10875 tr("Collecting locking information for all attached media failed"));
10876 }
10877 }
10878 }
10879
10880 /* Now lock all media. If this fails, nothing is locked. */
10881 alock.release();
10882 rc = lockedMediaMap->Lock();
10883 alock.acquire();
10884 if (FAILED(rc))
10885 {
10886 throw setError(rc,
10887 tr("Locking of attached media failed"));
10888 }
10889 }
10890
10891 /* remember the current list (note that we don't use backup() since
10892 * mMediumAttachments may be already backed up) */
10893 MediumAttachmentList atts = *mMediumAttachments.data();
10894
10895 /* start from scratch */
10896 mMediumAttachments->clear();
10897
10898 /* go through remembered attachments and create diffs for normal hard
10899 * disks and attach them */
10900 for (MediumAttachmentList::const_iterator
10901 it = atts.begin();
10902 it != atts.end();
10903 ++it)
10904 {
10905 MediumAttachment *pAtt = *it;
10906
10907 DeviceType_T devType = pAtt->i_getType();
10908 Medium *pMedium = pAtt->i_getMedium();
10909
10910 if ( devType != DeviceType_HardDisk
10911 || pMedium == NULL
10912 || pMedium->i_getType() != MediumType_Normal)
10913 {
10914 /* copy the attachment as is */
10915
10916 /** @todo the progress object created in SessionMachine::TakeSnaphot
10917 * only expects operations for hard disks. Later other
10918 * device types need to show up in the progress as well. */
10919 if (devType == DeviceType_HardDisk)
10920 {
10921 if (pMedium == NULL)
10922 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
10923 aWeight); // weight
10924 else
10925 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
10926 pMedium->i_getBase()->i_getName().c_str()).raw(),
10927 aWeight); // weight
10928 }
10929
10930 mMediumAttachments->push_back(pAtt);
10931 continue;
10932 }
10933
10934 /* need a diff */
10935 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
10936 pMedium->i_getBase()->i_getName().c_str()).raw(),
10937 aWeight); // weight
10938
10939 Utf8Str strFullSnapshotFolder;
10940 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10941
10942 ComObjPtr<Medium> diff;
10943 diff.createObject();
10944 // store the diff in the same registry as the parent
10945 // (this cannot fail here because we can't create implicit diffs for
10946 // unregistered images)
10947 Guid uuidRegistryParent;
10948 bool fInRegistry = pMedium->i_getFirstRegistryMachineId(uuidRegistryParent);
10949 Assert(fInRegistry); NOREF(fInRegistry);
10950 rc = diff->init(mParent,
10951 pMedium->i_getPreferredDiffFormat(),
10952 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
10953 uuidRegistryParent,
10954 DeviceType_HardDisk);
10955 if (FAILED(rc)) throw rc;
10956
10957 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
10958 * the push_back? Looks like we're going to release medium with the
10959 * wrong kind of lock (general issue with if we fail anywhere at all)
10960 * and an orphaned VDI in the snapshots folder. */
10961
10962 /* update the appropriate lock list */
10963 MediumLockList *pMediumLockList;
10964 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
10965 AssertComRCThrowRC(rc);
10966 if (aOnline)
10967 {
10968 alock.release();
10969 /* The currently attached medium will be read-only, change
10970 * the lock type to read. */
10971 rc = pMediumLockList->Update(pMedium, false);
10972 alock.acquire();
10973 AssertComRCThrowRC(rc);
10974 }
10975
10976 /* release the locks before the potentially lengthy operation */
10977 alock.release();
10978 rc = pMedium->i_createDiffStorage(diff,
10979 pMedium->i_getPreferredDiffVariant(),
10980 pMediumLockList,
10981 NULL /* aProgress */,
10982 true /* aWait */);
10983 alock.acquire();
10984 if (FAILED(rc)) throw rc;
10985
10986 /* actual lock list update is done in Machine::i_commitMedia */
10987
10988 rc = diff->i_addBackReference(mData->mUuid);
10989 AssertComRCThrowRC(rc);
10990
10991 /* add a new attachment */
10992 ComObjPtr<MediumAttachment> attachment;
10993 attachment.createObject();
10994 rc = attachment->init(this,
10995 diff,
10996 pAtt->i_getControllerName(),
10997 pAtt->i_getPort(),
10998 pAtt->i_getDevice(),
10999 DeviceType_HardDisk,
11000 true /* aImplicit */,
11001 false /* aPassthrough */,
11002 false /* aTempEject */,
11003 pAtt->i_getNonRotational(),
11004 pAtt->i_getDiscard(),
11005 pAtt->i_getHotPluggable(),
11006 pAtt->i_getBandwidthGroup());
11007 if (FAILED(rc)) throw rc;
11008
11009 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
11010 AssertComRCThrowRC(rc);
11011 mMediumAttachments->push_back(attachment);
11012 }
11013 }
11014 catch (HRESULT aRC) { rc = aRC; }
11015
11016 /* unlock all hard disks we locked when there is no VM */
11017 if (!aOnline)
11018 {
11019 ErrorInfoKeeper eik;
11020
11021 HRESULT rc1 = lockedMediaMap->Clear();
11022 AssertComRC(rc1);
11023 }
11024
11025 return rc;
11026}
11027
11028/**
11029 * Deletes implicit differencing hard disks created either by
11030 * #i_createImplicitDiffs() or by #attachDevice() and rolls back
11031 * mMediumAttachments.
11032 *
11033 * Note that to delete hard disks created by #attachDevice() this method is
11034 * called from #i_rollbackMedia() when the changes are rolled back.
11035 *
11036 * @note Locks this object and the media tree for writing.
11037 */
11038HRESULT Machine::i_deleteImplicitDiffs(bool aOnline)
11039{
11040 LogFlowThisFunc(("aOnline=%d\n", aOnline));
11041
11042 AutoCaller autoCaller(this);
11043 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11044
11045 AutoMultiWriteLock2 alock(this->lockHandle(),
11046 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
11047
11048 /* We absolutely must have backed up state. */
11049 AssertReturn(mMediumAttachments.isBackedUp(), E_FAIL);
11050
11051 /* Check if there are any implicitly created diff images. */
11052 bool fImplicitDiffs = false;
11053 for (MediumAttachmentList::const_iterator
11054 it = mMediumAttachments->begin();
11055 it != mMediumAttachments->end();
11056 ++it)
11057 {
11058 const ComObjPtr<MediumAttachment> &pAtt = *it;
11059 if (pAtt->i_isImplicit())
11060 {
11061 fImplicitDiffs = true;
11062 break;
11063 }
11064 }
11065 /* If there is nothing to do, leave early. This saves lots of image locking
11066 * effort. It also avoids a MachineStateChanged event without real reason.
11067 * This is important e.g. when loading a VM config, because there should be
11068 * no events. Otherwise API clients can become thoroughly confused for
11069 * inaccessible VMs (the code for loading VM configs uses this method for
11070 * cleanup if the config makes no sense), as they take such events as an
11071 * indication that the VM is alive, and they would force the VM config to
11072 * be reread, leading to an endless loop. */
11073 if (!fImplicitDiffs)
11074 return S_OK;
11075
11076 HRESULT rc = S_OK;
11077 MachineState_T oldState = mData->mMachineState;
11078
11079 /* will release the lock before the potentially lengthy operation,
11080 * so protect with the special state (unless already protected) */
11081 if ( oldState != MachineState_Snapshotting
11082 && oldState != MachineState_OnlineSnapshotting
11083 && oldState != MachineState_LiveSnapshotting
11084 && oldState != MachineState_RestoringSnapshot
11085 && oldState != MachineState_DeletingSnapshot
11086 && oldState != MachineState_DeletingSnapshotOnline
11087 && oldState != MachineState_DeletingSnapshotPaused
11088 )
11089 i_setMachineState(MachineState_SettingUp);
11090
11091 // use appropriate locked media map (online or offline)
11092 MediumLockListMap lockedMediaOffline;
11093 MediumLockListMap *lockedMediaMap;
11094 if (aOnline)
11095 lockedMediaMap = &mData->mSession.mLockedMedia;
11096 else
11097 lockedMediaMap = &lockedMediaOffline;
11098
11099 try
11100 {
11101 if (!aOnline)
11102 {
11103 /* lock all attached hard disks early to detect "in use"
11104 * situations before deleting actual diffs */
11105 for (MediumAttachmentList::const_iterator
11106 it = mMediumAttachments->begin();
11107 it != mMediumAttachments->end();
11108 ++it)
11109 {
11110 MediumAttachment *pAtt = *it;
11111 if (pAtt->i_getType() == DeviceType_HardDisk)
11112 {
11113 Medium *pMedium = pAtt->i_getMedium();
11114 Assert(pMedium);
11115
11116 MediumLockList *pMediumLockList(new MediumLockList());
11117 alock.release();
11118 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
11119 NULL /* pToLockWrite */,
11120 false /* fMediumLockWriteAll */,
11121 NULL,
11122 *pMediumLockList);
11123 alock.acquire();
11124
11125 if (FAILED(rc))
11126 {
11127 delete pMediumLockList;
11128 throw rc;
11129 }
11130
11131 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
11132 if (FAILED(rc))
11133 throw rc;
11134 }
11135 }
11136
11137 if (FAILED(rc))
11138 throw rc;
11139 } // end of offline
11140
11141 /* Lock lists are now up to date and include implicitly created media */
11142
11143 /* Go through remembered attachments and delete all implicitly created
11144 * diffs and fix up the attachment information */
11145 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
11146 MediumAttachmentList implicitAtts;
11147 for (MediumAttachmentList::const_iterator
11148 it = mMediumAttachments->begin();
11149 it != mMediumAttachments->end();
11150 ++it)
11151 {
11152 ComObjPtr<MediumAttachment> pAtt = *it;
11153 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11154 if (pMedium.isNull())
11155 continue;
11156
11157 // Implicit attachments go on the list for deletion and back references are removed.
11158 if (pAtt->i_isImplicit())
11159 {
11160 /* Deassociate and mark for deletion */
11161 LogFlowThisFunc(("Detaching '%s', pending deletion\n", pAtt->i_getLogName()));
11162 rc = pMedium->i_removeBackReference(mData->mUuid);
11163 if (FAILED(rc))
11164 throw rc;
11165 implicitAtts.push_back(pAtt);
11166 continue;
11167 }
11168
11169 /* Was this medium attached before? */
11170 if (!i_findAttachment(oldAtts, pMedium))
11171 {
11172 /* no: de-associate */
11173 LogFlowThisFunc(("Detaching '%s', no deletion\n", pAtt->i_getLogName()));
11174 rc = pMedium->i_removeBackReference(mData->mUuid);
11175 if (FAILED(rc))
11176 throw rc;
11177 continue;
11178 }
11179 LogFlowThisFunc(("Not detaching '%s'\n", pAtt->i_getLogName()));
11180 }
11181
11182 /* If there are implicit attachments to delete, throw away the lock
11183 * map contents (which will unlock all media) since the medium
11184 * attachments will be rolled back. Below we need to completely
11185 * recreate the lock map anyway since it is infinitely complex to
11186 * do this incrementally (would need reconstructing each attachment
11187 * change, which would be extremely hairy). */
11188 if (implicitAtts.size() != 0)
11189 {
11190 ErrorInfoKeeper eik;
11191
11192 HRESULT rc1 = lockedMediaMap->Clear();
11193 AssertComRC(rc1);
11194 }
11195
11196 /* rollback hard disk changes */
11197 mMediumAttachments.rollback();
11198
11199 MultiResult mrc(S_OK);
11200
11201 // Delete unused implicit diffs.
11202 if (implicitAtts.size() != 0)
11203 {
11204 alock.release();
11205
11206 for (MediumAttachmentList::const_iterator
11207 it = implicitAtts.begin();
11208 it != implicitAtts.end();
11209 ++it)
11210 {
11211 // Remove medium associated with this attachment.
11212 ComObjPtr<MediumAttachment> pAtt = *it;
11213 Assert(pAtt);
11214 LogFlowThisFunc(("Deleting '%s'\n", pAtt->i_getLogName()));
11215 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11216 Assert(pMedium);
11217
11218 rc = pMedium->i_deleteStorage(NULL /*aProgress*/, true /*aWait*/);
11219 // continue on delete failure, just collect error messages
11220 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, pAtt->i_getLogName(),
11221 pMedium->i_getLocationFull().c_str() ));
11222 mrc = rc;
11223 }
11224 // Clear the list of deleted implicit attachments now, while not
11225 // holding the lock, as it will ultimately trigger Medium::uninit()
11226 // calls which assume that the media tree lock isn't held.
11227 implicitAtts.clear();
11228
11229 alock.acquire();
11230
11231 /* if there is a VM recreate media lock map as mentioned above,
11232 * otherwise it is a waste of time and we leave things unlocked */
11233 if (aOnline)
11234 {
11235 const ComObjPtr<SessionMachine> pMachine = mData->mSession.mMachine;
11236 /* must never be NULL, but better safe than sorry */
11237 if (!pMachine.isNull())
11238 {
11239 alock.release();
11240 rc = mData->mSession.mMachine->i_lockMedia();
11241 alock.acquire();
11242 if (FAILED(rc))
11243 throw rc;
11244 }
11245 }
11246 }
11247 }
11248 catch (HRESULT aRC) {rc = aRC;}
11249
11250 if (mData->mMachineState == MachineState_SettingUp)
11251 i_setMachineState(oldState);
11252
11253 /* unlock all hard disks we locked when there is no VM */
11254 if (!aOnline)
11255 {
11256 ErrorInfoKeeper eik;
11257
11258 HRESULT rc1 = lockedMediaMap->Clear();
11259 AssertComRC(rc1);
11260 }
11261
11262 return rc;
11263}
11264
11265
11266/**
11267 * Looks through the given list of media attachments for one with the given parameters
11268 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11269 * can be searched as well if needed.
11270 *
11271 * @param ll
11272 * @param aControllerName
11273 * @param aControllerPort
11274 * @param aDevice
11275 * @return
11276 */
11277MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11278 const Utf8Str &aControllerName,
11279 LONG aControllerPort,
11280 LONG aDevice)
11281{
11282 for (MediumAttachmentList::const_iterator
11283 it = ll.begin();
11284 it != ll.end();
11285 ++it)
11286 {
11287 MediumAttachment *pAttach = *it;
11288 if (pAttach->i_matches(aControllerName, aControllerPort, aDevice))
11289 return pAttach;
11290 }
11291
11292 return NULL;
11293}
11294
11295/**
11296 * Looks through the given list of media attachments for one with the given parameters
11297 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11298 * can be searched as well if needed.
11299 *
11300 * @param ll
11301 * @param pMedium
11302 * @return
11303 */
11304MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11305 ComObjPtr<Medium> pMedium)
11306{
11307 for (MediumAttachmentList::const_iterator
11308 it = ll.begin();
11309 it != ll.end();
11310 ++it)
11311 {
11312 MediumAttachment *pAttach = *it;
11313 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11314 if (pMediumThis == pMedium)
11315 return pAttach;
11316 }
11317
11318 return NULL;
11319}
11320
11321/**
11322 * Looks through the given list of media attachments for one with the given parameters
11323 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11324 * can be searched as well if needed.
11325 *
11326 * @param ll
11327 * @param id
11328 * @return
11329 */
11330MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11331 Guid &id)
11332{
11333 for (MediumAttachmentList::const_iterator
11334 it = ll.begin();
11335 it != ll.end();
11336 ++it)
11337 {
11338 MediumAttachment *pAttach = *it;
11339 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11340 if (pMediumThis->i_getId() == id)
11341 return pAttach;
11342 }
11343
11344 return NULL;
11345}
11346
11347/**
11348 * Main implementation for Machine::DetachDevice. This also gets called
11349 * from Machine::prepareUnregister() so it has been taken out for simplicity.
11350 *
11351 * @param pAttach Medium attachment to detach.
11352 * @param writeLock Machine write lock which the caller must have locked once.
11353 * This may be released temporarily in here.
11354 * @param pSnapshot If NULL, then the detachment is for the current machine.
11355 * Otherwise this is for a SnapshotMachine, and this must be
11356 * its snapshot.
11357 * @return
11358 */
11359HRESULT Machine::i_detachDevice(MediumAttachment *pAttach,
11360 AutoWriteLock &writeLock,
11361 Snapshot *pSnapshot)
11362{
11363 ComObjPtr<Medium> oldmedium = pAttach->i_getMedium();
11364 DeviceType_T mediumType = pAttach->i_getType();
11365
11366 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->i_getLocationFull().c_str() : "NULL"));
11367
11368 if (pAttach->i_isImplicit())
11369 {
11370 /* attempt to implicitly delete the implicitly created diff */
11371
11372 /// @todo move the implicit flag from MediumAttachment to Medium
11373 /// and forbid any hard disk operation when it is implicit. Or maybe
11374 /// a special media state for it to make it even more simple.
11375
11376 Assert(mMediumAttachments.isBackedUp());
11377
11378 /* will release the lock before the potentially lengthy operation, so
11379 * protect with the special state */
11380 MachineState_T oldState = mData->mMachineState;
11381 i_setMachineState(MachineState_SettingUp);
11382
11383 writeLock.release();
11384
11385 HRESULT rc = oldmedium->i_deleteStorage(NULL /*aProgress*/,
11386 true /*aWait*/);
11387
11388 writeLock.acquire();
11389
11390 i_setMachineState(oldState);
11391
11392 if (FAILED(rc)) return rc;
11393 }
11394
11395 i_setModified(IsModified_Storage);
11396 mMediumAttachments.backup();
11397 mMediumAttachments->remove(pAttach);
11398
11399 if (!oldmedium.isNull())
11400 {
11401 // if this is from a snapshot, do not defer detachment to i_commitMedia()
11402 if (pSnapshot)
11403 oldmedium->i_removeBackReference(mData->mUuid, pSnapshot->i_getId());
11404 // else if non-hard disk media, do not defer detachment to i_commitMedia() either
11405 else if (mediumType != DeviceType_HardDisk)
11406 oldmedium->i_removeBackReference(mData->mUuid);
11407 }
11408
11409 return S_OK;
11410}
11411
11412/**
11413 * Goes thru all media of the given list and
11414 *
11415 * 1) calls i_detachDevice() on each of them for this machine and
11416 * 2) adds all Medium objects found in the process to the given list,
11417 * depending on cleanupMode.
11418 *
11419 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
11420 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
11421 * media to the list.
11422 *
11423 * This gets called from Machine::Unregister, both for the actual Machine and
11424 * the SnapshotMachine objects that might be found in the snapshots.
11425 *
11426 * Requires caller and locking. The machine lock must be passed in because it
11427 * will be passed on to i_detachDevice which needs it for temporary unlocking.
11428 *
11429 * @param writeLock Machine lock from top-level caller; this gets passed to
11430 * i_detachDevice.
11431 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot
11432 * object if called for a SnapshotMachine.
11433 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get
11434 * added to llMedia; if Full, then all media get added;
11435 * otherwise no media get added.
11436 * @param llMedia Caller's list to receive Medium objects which got detached so
11437 * caller can close() them, depending on cleanupMode.
11438 * @return
11439 */
11440HRESULT Machine::i_detachAllMedia(AutoWriteLock &writeLock,
11441 Snapshot *pSnapshot,
11442 CleanupMode_T cleanupMode,
11443 MediaList &llMedia)
11444{
11445 Assert(isWriteLockOnCurrentThread());
11446
11447 HRESULT rc;
11448
11449 // make a temporary list because i_detachDevice invalidates iterators into
11450 // mMediumAttachments
11451 MediumAttachmentList llAttachments2 = *mMediumAttachments.data();
11452
11453 for (MediumAttachmentList::iterator
11454 it = llAttachments2.begin();
11455 it != llAttachments2.end();
11456 ++it)
11457 {
11458 ComObjPtr<MediumAttachment> &pAttach = *it;
11459 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
11460
11461 if (!pMedium.isNull())
11462 {
11463 AutoCaller mac(pMedium);
11464 if (FAILED(mac.rc())) return mac.rc();
11465 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
11466 DeviceType_T devType = pMedium->i_getDeviceType();
11467 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
11468 && devType == DeviceType_HardDisk)
11469 || (cleanupMode == CleanupMode_Full)
11470 )
11471 {
11472 llMedia.push_back(pMedium);
11473 ComObjPtr<Medium> pParent = pMedium->i_getParent();
11474 /* Not allowed to keep this lock as below we need the parent
11475 * medium lock, and the lock order is parent to child. */
11476 lock.release();
11477 /*
11478 * Search for medias which are not attached to any machine, but
11479 * in the chain to an attached disk. Mediums are only consided
11480 * if they are:
11481 * - have only one child
11482 * - no references to any machines
11483 * - are of normal medium type
11484 */
11485 while (!pParent.isNull())
11486 {
11487 AutoCaller mac1(pParent);
11488 if (FAILED(mac1.rc())) return mac1.rc();
11489 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
11490 if (pParent->i_getChildren().size() == 1)
11491 {
11492 if ( pParent->i_getMachineBackRefCount() == 0
11493 && pParent->i_getType() == MediumType_Normal
11494 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
11495 llMedia.push_back(pParent);
11496 }
11497 else
11498 break;
11499 pParent = pParent->i_getParent();
11500 }
11501 }
11502 }
11503
11504 // real machine: then we need to use the proper method
11505 rc = i_detachDevice(pAttach, writeLock, pSnapshot);
11506
11507 if (FAILED(rc))
11508 return rc;
11509 }
11510
11511 return S_OK;
11512}
11513
11514/**
11515 * Perform deferred hard disk detachments.
11516 *
11517 * Does nothing if the hard disk attachment data (mMediumAttachments) is not
11518 * changed (not backed up).
11519 *
11520 * If @a aOnline is @c true then this method will also unlock the old hard
11521 * disks for which the new implicit diffs were created and will lock these new
11522 * diffs for writing.
11523 *
11524 * @param aOnline Whether the VM was online prior to this operation.
11525 *
11526 * @note Locks this object for writing!
11527 */
11528void Machine::i_commitMedia(bool aOnline /*= false*/)
11529{
11530 AutoCaller autoCaller(this);
11531 AssertComRCReturnVoid(autoCaller.rc());
11532
11533 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11534
11535 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
11536
11537 HRESULT rc = S_OK;
11538
11539 /* no attach/detach operations -- nothing to do */
11540 if (!mMediumAttachments.isBackedUp())
11541 return;
11542
11543 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
11544 bool fMediaNeedsLocking = false;
11545
11546 /* enumerate new attachments */
11547 for (MediumAttachmentList::const_iterator
11548 it = mMediumAttachments->begin();
11549 it != mMediumAttachments->end();
11550 ++it)
11551 {
11552 MediumAttachment *pAttach = *it;
11553
11554 pAttach->i_commit();
11555
11556 Medium *pMedium = pAttach->i_getMedium();
11557 bool fImplicit = pAttach->i_isImplicit();
11558
11559 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
11560 (pMedium) ? pMedium->i_getName().c_str() : "NULL",
11561 fImplicit));
11562
11563 /** @todo convert all this Machine-based voodoo to MediumAttachment
11564 * based commit logic. */
11565 if (fImplicit)
11566 {
11567 /* convert implicit attachment to normal */
11568 pAttach->i_setImplicit(false);
11569
11570 if ( aOnline
11571 && pMedium
11572 && pAttach->i_getType() == DeviceType_HardDisk
11573 )
11574 {
11575 /* update the appropriate lock list */
11576 MediumLockList *pMediumLockList;
11577 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11578 AssertComRC(rc);
11579 if (pMediumLockList)
11580 {
11581 /* unlock if there's a need to change the locking */
11582 if (!fMediaNeedsLocking)
11583 {
11584 rc = mData->mSession.mLockedMedia.Unlock();
11585 AssertComRC(rc);
11586 fMediaNeedsLocking = true;
11587 }
11588 rc = pMediumLockList->Update(pMedium->i_getParent(), false);
11589 AssertComRC(rc);
11590 rc = pMediumLockList->Append(pMedium, true);
11591 AssertComRC(rc);
11592 }
11593 }
11594
11595 continue;
11596 }
11597
11598 if (pMedium)
11599 {
11600 /* was this medium attached before? */
11601 for (MediumAttachmentList::iterator
11602 oldIt = oldAtts.begin();
11603 oldIt != oldAtts.end();
11604 ++oldIt)
11605 {
11606 MediumAttachment *pOldAttach = *oldIt;
11607 if (pOldAttach->i_getMedium() == pMedium)
11608 {
11609 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->i_getName().c_str()));
11610
11611 /* yes: remove from old to avoid de-association */
11612 oldAtts.erase(oldIt);
11613 break;
11614 }
11615 }
11616 }
11617 }
11618
11619 /* enumerate remaining old attachments and de-associate from the
11620 * current machine state */
11621 for (MediumAttachmentList::const_iterator
11622 it = oldAtts.begin();
11623 it != oldAtts.end();
11624 ++it)
11625 {
11626 MediumAttachment *pAttach = *it;
11627 Medium *pMedium = pAttach->i_getMedium();
11628
11629 /* Detach only hard disks, since DVD/floppy media is detached
11630 * instantly in MountMedium. */
11631 if (pAttach->i_getType() == DeviceType_HardDisk && pMedium)
11632 {
11633 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->i_getName().c_str()));
11634
11635 /* now de-associate from the current machine state */
11636 rc = pMedium->i_removeBackReference(mData->mUuid);
11637 AssertComRC(rc);
11638
11639 if (aOnline)
11640 {
11641 /* unlock since medium is not used anymore */
11642 MediumLockList *pMediumLockList;
11643 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11644 if (RT_UNLIKELY(rc == VBOX_E_INVALID_OBJECT_STATE))
11645 {
11646 /* this happens for online snapshots, there the attachment
11647 * is changing, but only to a diff image created under
11648 * the old one, so there is no separate lock list */
11649 Assert(!pMediumLockList);
11650 }
11651 else
11652 {
11653 AssertComRC(rc);
11654 if (pMediumLockList)
11655 {
11656 rc = mData->mSession.mLockedMedia.Remove(pAttach);
11657 AssertComRC(rc);
11658 }
11659 }
11660 }
11661 }
11662 }
11663
11664 /* take media locks again so that the locking state is consistent */
11665 if (fMediaNeedsLocking)
11666 {
11667 Assert(aOnline);
11668 rc = mData->mSession.mLockedMedia.Lock();
11669 AssertComRC(rc);
11670 }
11671
11672 /* commit the hard disk changes */
11673 mMediumAttachments.commit();
11674
11675 if (i_isSessionMachine())
11676 {
11677 /*
11678 * Update the parent machine to point to the new owner.
11679 * This is necessary because the stored parent will point to the
11680 * session machine otherwise and cause crashes or errors later
11681 * when the session machine gets invalid.
11682 */
11683 /** @todo Change the MediumAttachment class to behave like any other
11684 * class in this regard by creating peer MediumAttachment
11685 * objects for session machines and share the data with the peer
11686 * machine.
11687 */
11688 for (MediumAttachmentList::const_iterator
11689 it = mMediumAttachments->begin();
11690 it != mMediumAttachments->end();
11691 ++it)
11692 (*it)->i_updateParentMachine(mPeer);
11693
11694 /* attach new data to the primary machine and reshare it */
11695 mPeer->mMediumAttachments.attach(mMediumAttachments);
11696 }
11697
11698 return;
11699}
11700
11701/**
11702 * Perform deferred deletion of implicitly created diffs.
11703 *
11704 * Does nothing if the hard disk attachment data (mMediumAttachments) is not
11705 * changed (not backed up).
11706 *
11707 * @note Locks this object for writing!
11708 */
11709void Machine::i_rollbackMedia()
11710{
11711 AutoCaller autoCaller(this);
11712 AssertComRCReturnVoid(autoCaller.rc());
11713
11714 // AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11715 LogFlowThisFunc(("Entering rollbackMedia\n"));
11716
11717 HRESULT rc = S_OK;
11718
11719 /* no attach/detach operations -- nothing to do */
11720 if (!mMediumAttachments.isBackedUp())
11721 return;
11722
11723 /* enumerate new attachments */
11724 for (MediumAttachmentList::const_iterator
11725 it = mMediumAttachments->begin();
11726 it != mMediumAttachments->end();
11727 ++it)
11728 {
11729 MediumAttachment *pAttach = *it;
11730 /* Fix up the backrefs for DVD/floppy media. */
11731 if (pAttach->i_getType() != DeviceType_HardDisk)
11732 {
11733 Medium *pMedium = pAttach->i_getMedium();
11734 if (pMedium)
11735 {
11736 rc = pMedium->i_removeBackReference(mData->mUuid);
11737 AssertComRC(rc);
11738 }
11739 }
11740
11741 (*it)->i_rollback();
11742
11743 pAttach = *it;
11744 /* Fix up the backrefs for DVD/floppy media. */
11745 if (pAttach->i_getType() != DeviceType_HardDisk)
11746 {
11747 Medium *pMedium = pAttach->i_getMedium();
11748 if (pMedium)
11749 {
11750 rc = pMedium->i_addBackReference(mData->mUuid);
11751 AssertComRC(rc);
11752 }
11753 }
11754 }
11755
11756 /** @todo convert all this Machine-based voodoo to MediumAttachment
11757 * based rollback logic. */
11758 i_deleteImplicitDiffs(Global::IsOnline(mData->mMachineState));
11759
11760 return;
11761}
11762
11763/**
11764 * Returns true if the settings file is located in the directory named exactly
11765 * as the machine; this means, among other things, that the machine directory
11766 * should be auto-renamed.
11767 *
11768 * @param aSettingsDir if not NULL, the full machine settings file directory
11769 * name will be assigned there.
11770 *
11771 * @note Doesn't lock anything.
11772 * @note Not thread safe (must be called from this object's lock).
11773 */
11774bool Machine::i_isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
11775{
11776 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11777 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
11778 if (aSettingsDir)
11779 *aSettingsDir = strMachineDirName;
11780 strMachineDirName.stripPath(); // vmname
11781 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11782 strConfigFileOnly.stripPath() // vmname.vbox
11783 .stripSuffix(); // vmname
11784 /** @todo hack, make somehow use of ComposeMachineFilename */
11785 if (mUserData->s.fDirectoryIncludesUUID)
11786 strConfigFileOnly += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
11787
11788 AssertReturn(!strMachineDirName.isEmpty(), false);
11789 AssertReturn(!strConfigFileOnly.isEmpty(), false);
11790
11791 return strMachineDirName == strConfigFileOnly;
11792}
11793
11794/**
11795 * Discards all changes to machine settings.
11796 *
11797 * @param aNotify Whether to notify the direct session about changes or not.
11798 *
11799 * @note Locks objects for writing!
11800 */
11801void Machine::i_rollback(bool aNotify)
11802{
11803 AutoCaller autoCaller(this);
11804 AssertComRCReturn(autoCaller.rc(), (void)0);
11805
11806 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11807
11808 if (!mStorageControllers.isNull())
11809 {
11810 if (mStorageControllers.isBackedUp())
11811 {
11812 /* unitialize all new devices (absent in the backed up list). */
11813 StorageControllerList *backedList = mStorageControllers.backedUpData();
11814 for (StorageControllerList::const_iterator
11815 it = mStorageControllers->begin();
11816 it != mStorageControllers->end();
11817 ++it)
11818 {
11819 if ( std::find(backedList->begin(), backedList->end(), *it)
11820 == backedList->end()
11821 )
11822 {
11823 (*it)->uninit();
11824 }
11825 }
11826
11827 /* restore the list */
11828 mStorageControllers.rollback();
11829 }
11830
11831 /* rollback any changes to devices after restoring the list */
11832 if (mData->flModifications & IsModified_Storage)
11833 {
11834 for (StorageControllerList::const_iterator
11835 it = mStorageControllers->begin();
11836 it != mStorageControllers->end();
11837 ++it)
11838 {
11839 (*it)->i_rollback();
11840 }
11841 }
11842 }
11843
11844 if (!mUSBControllers.isNull())
11845 {
11846 if (mUSBControllers.isBackedUp())
11847 {
11848 /* unitialize all new devices (absent in the backed up list). */
11849 USBControllerList *backedList = mUSBControllers.backedUpData();
11850 for (USBControllerList::const_iterator
11851 it = mUSBControllers->begin();
11852 it != mUSBControllers->end();
11853 ++it)
11854 {
11855 if ( std::find(backedList->begin(), backedList->end(), *it)
11856 == backedList->end()
11857 )
11858 {
11859 (*it)->uninit();
11860 }
11861 }
11862
11863 /* restore the list */
11864 mUSBControllers.rollback();
11865 }
11866
11867 /* rollback any changes to devices after restoring the list */
11868 if (mData->flModifications & IsModified_USB)
11869 {
11870 for (USBControllerList::const_iterator
11871 it = mUSBControllers->begin();
11872 it != mUSBControllers->end();
11873 ++it)
11874 {
11875 (*it)->i_rollback();
11876 }
11877 }
11878 }
11879
11880 mUserData.rollback();
11881
11882 mHWData.rollback();
11883
11884 if (mData->flModifications & IsModified_Storage)
11885 i_rollbackMedia();
11886
11887 if (mBIOSSettings)
11888 mBIOSSettings->i_rollback();
11889
11890 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
11891 mVRDEServer->i_rollback();
11892
11893 if (mAudioAdapter)
11894 mAudioAdapter->i_rollback();
11895
11896 if (mUSBDeviceFilters && (mData->flModifications & IsModified_USB))
11897 mUSBDeviceFilters->i_rollback();
11898
11899 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
11900 mBandwidthControl->i_rollback();
11901
11902 if (!mHWData.isNull())
11903 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
11904 NetworkAdapterVector networkAdapters(mNetworkAdapters.size());
11905 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
11906 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
11907
11908 if (mData->flModifications & IsModified_NetworkAdapters)
11909 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
11910 if ( mNetworkAdapters[slot]
11911 && mNetworkAdapters[slot]->i_isModified())
11912 {
11913 mNetworkAdapters[slot]->i_rollback();
11914 networkAdapters[slot] = mNetworkAdapters[slot];
11915 }
11916
11917 if (mData->flModifications & IsModified_SerialPorts)
11918 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
11919 if ( mSerialPorts[slot]
11920 && mSerialPorts[slot]->i_isModified())
11921 {
11922 mSerialPorts[slot]->i_rollback();
11923 serialPorts[slot] = mSerialPorts[slot];
11924 }
11925
11926 if (mData->flModifications & IsModified_ParallelPorts)
11927 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
11928 if ( mParallelPorts[slot]
11929 && mParallelPorts[slot]->i_isModified())
11930 {
11931 mParallelPorts[slot]->i_rollback();
11932 parallelPorts[slot] = mParallelPorts[slot];
11933 }
11934
11935 if (aNotify)
11936 {
11937 /* inform the direct session about changes */
11938
11939 ComObjPtr<Machine> that = this;
11940 uint32_t flModifications = mData->flModifications;
11941 alock.release();
11942
11943 if (flModifications & IsModified_SharedFolders)
11944 that->i_onSharedFolderChange();
11945
11946 if (flModifications & IsModified_VRDEServer)
11947 that->i_onVRDEServerChange(/* aRestart */ TRUE);
11948 if (flModifications & IsModified_USB)
11949 that->i_onUSBControllerChange();
11950
11951 for (ULONG slot = 0; slot < networkAdapters.size(); ++slot)
11952 if (networkAdapters[slot])
11953 that->i_onNetworkAdapterChange(networkAdapters[slot], FALSE);
11954 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); ++slot)
11955 if (serialPorts[slot])
11956 that->i_onSerialPortChange(serialPorts[slot]);
11957 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); ++slot)
11958 if (parallelPorts[slot])
11959 that->i_onParallelPortChange(parallelPorts[slot]);
11960
11961 if (flModifications & IsModified_Storage)
11962 that->i_onStorageControllerChange();
11963
11964#if 0
11965 if (flModifications & IsModified_BandwidthControl)
11966 that->onBandwidthControlChange();
11967#endif
11968 }
11969}
11970
11971/**
11972 * Commits all the changes to machine settings.
11973 *
11974 * Note that this operation is supposed to never fail.
11975 *
11976 * @note Locks this object and children for writing.
11977 */
11978void Machine::i_commit()
11979{
11980 AutoCaller autoCaller(this);
11981 AssertComRCReturnVoid(autoCaller.rc());
11982
11983 AutoCaller peerCaller(mPeer);
11984 AssertComRCReturnVoid(peerCaller.rc());
11985
11986 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
11987
11988 /*
11989 * use safe commit to ensure Snapshot machines (that share mUserData)
11990 * will still refer to a valid memory location
11991 */
11992 mUserData.commitCopy();
11993
11994 mHWData.commit();
11995
11996 if (mMediumAttachments.isBackedUp())
11997 i_commitMedia(Global::IsOnline(mData->mMachineState));
11998
11999 mBIOSSettings->i_commit();
12000 mVRDEServer->i_commit();
12001 mAudioAdapter->i_commit();
12002 mUSBDeviceFilters->i_commit();
12003 mBandwidthControl->i_commit();
12004
12005 /* Since mNetworkAdapters is a list which might have been changed (resized)
12006 * without using the Backupable<> template we need to handle the copying
12007 * of the list entries manually, including the creation of peers for the
12008 * new objects. */
12009 bool commitNetworkAdapters = false;
12010 size_t newSize = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
12011 if (mPeer)
12012 {
12013 /* commit everything, even the ones which will go away */
12014 for (size_t slot = 0; slot < mNetworkAdapters.size(); slot++)
12015 mNetworkAdapters[slot]->i_commit();
12016 /* copy over the new entries, creating a peer and uninit the original */
12017 mPeer->mNetworkAdapters.resize(RT_MAX(newSize, mPeer->mNetworkAdapters.size()));
12018 for (size_t slot = 0; slot < newSize; slot++)
12019 {
12020 /* look if this adapter has a peer device */
12021 ComObjPtr<NetworkAdapter> peer = mNetworkAdapters[slot]->i_getPeer();
12022 if (!peer)
12023 {
12024 /* no peer means the adapter is a newly created one;
12025 * create a peer owning data this data share it with */
12026 peer.createObject();
12027 peer->init(mPeer, mNetworkAdapters[slot], true /* aReshare */);
12028 }
12029 mPeer->mNetworkAdapters[slot] = peer;
12030 }
12031 /* uninit any no longer needed network adapters */
12032 for (size_t slot = newSize; slot < mNetworkAdapters.size(); ++slot)
12033 mNetworkAdapters[slot]->uninit();
12034 for (size_t slot = newSize; slot < mPeer->mNetworkAdapters.size(); ++slot)
12035 {
12036 if (mPeer->mNetworkAdapters[slot])
12037 mPeer->mNetworkAdapters[slot]->uninit();
12038 }
12039 /* Keep the original network adapter count until this point, so that
12040 * discarding a chipset type change will not lose settings. */
12041 mNetworkAdapters.resize(newSize);
12042 mPeer->mNetworkAdapters.resize(newSize);
12043 }
12044 else
12045 {
12046 /* we have no peer (our parent is the newly created machine);
12047 * just commit changes to the network adapters */
12048 commitNetworkAdapters = true;
12049 }
12050 if (commitNetworkAdapters)
12051 for (size_t slot = 0; slot < mNetworkAdapters.size(); ++slot)
12052 mNetworkAdapters[slot]->i_commit();
12053
12054 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12055 mSerialPorts[slot]->i_commit();
12056 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12057 mParallelPorts[slot]->i_commit();
12058
12059 bool commitStorageControllers = false;
12060
12061 if (mStorageControllers.isBackedUp())
12062 {
12063 mStorageControllers.commit();
12064
12065 if (mPeer)
12066 {
12067 /* Commit all changes to new controllers (this will reshare data with
12068 * peers for those who have peers) */
12069 StorageControllerList *newList = new StorageControllerList();
12070 for (StorageControllerList::const_iterator
12071 it = mStorageControllers->begin();
12072 it != mStorageControllers->end();
12073 ++it)
12074 {
12075 (*it)->i_commit();
12076
12077 /* look if this controller has a peer device */
12078 ComObjPtr<StorageController> peer = (*it)->i_getPeer();
12079 if (!peer)
12080 {
12081 /* no peer means the device is a newly created one;
12082 * create a peer owning data this device share it with */
12083 peer.createObject();
12084 peer->init(mPeer, *it, true /* aReshare */);
12085 }
12086 else
12087 {
12088 /* remove peer from the old list */
12089 mPeer->mStorageControllers->remove(peer);
12090 }
12091 /* and add it to the new list */
12092 newList->push_back(peer);
12093 }
12094
12095 /* uninit old peer's controllers that are left */
12096 for (StorageControllerList::const_iterator
12097 it = mPeer->mStorageControllers->begin();
12098 it != mPeer->mStorageControllers->end();
12099 ++it)
12100 {
12101 (*it)->uninit();
12102 }
12103
12104 /* attach new list of controllers to our peer */
12105 mPeer->mStorageControllers.attach(newList);
12106 }
12107 else
12108 {
12109 /* we have no peer (our parent is the newly created machine);
12110 * just commit changes to devices */
12111 commitStorageControllers = true;
12112 }
12113 }
12114 else
12115 {
12116 /* the list of controllers itself is not changed,
12117 * just commit changes to controllers themselves */
12118 commitStorageControllers = true;
12119 }
12120
12121 if (commitStorageControllers)
12122 {
12123 for (StorageControllerList::const_iterator
12124 it = mStorageControllers->begin();
12125 it != mStorageControllers->end();
12126 ++it)
12127 {
12128 (*it)->i_commit();
12129 }
12130 }
12131
12132 bool commitUSBControllers = false;
12133
12134 if (mUSBControllers.isBackedUp())
12135 {
12136 mUSBControllers.commit();
12137
12138 if (mPeer)
12139 {
12140 /* Commit all changes to new controllers (this will reshare data with
12141 * peers for those who have peers) */
12142 USBControllerList *newList = new USBControllerList();
12143 for (USBControllerList::const_iterator
12144 it = mUSBControllers->begin();
12145 it != mUSBControllers->end();
12146 ++it)
12147 {
12148 (*it)->i_commit();
12149
12150 /* look if this controller has a peer device */
12151 ComObjPtr<USBController> peer = (*it)->i_getPeer();
12152 if (!peer)
12153 {
12154 /* no peer means the device is a newly created one;
12155 * create a peer owning data this device share it with */
12156 peer.createObject();
12157 peer->init(mPeer, *it, true /* aReshare */);
12158 }
12159 else
12160 {
12161 /* remove peer from the old list */
12162 mPeer->mUSBControllers->remove(peer);
12163 }
12164 /* and add it to the new list */
12165 newList->push_back(peer);
12166 }
12167
12168 /* uninit old peer's controllers that are left */
12169 for (USBControllerList::const_iterator
12170 it = mPeer->mUSBControllers->begin();
12171 it != mPeer->mUSBControllers->end();
12172 ++it)
12173 {
12174 (*it)->uninit();
12175 }
12176
12177 /* attach new list of controllers to our peer */
12178 mPeer->mUSBControllers.attach(newList);
12179 }
12180 else
12181 {
12182 /* we have no peer (our parent is the newly created machine);
12183 * just commit changes to devices */
12184 commitUSBControllers = true;
12185 }
12186 }
12187 else
12188 {
12189 /* the list of controllers itself is not changed,
12190 * just commit changes to controllers themselves */
12191 commitUSBControllers = true;
12192 }
12193
12194 if (commitUSBControllers)
12195 {
12196 for (USBControllerList::const_iterator
12197 it = mUSBControllers->begin();
12198 it != mUSBControllers->end();
12199 ++it)
12200 {
12201 (*it)->i_commit();
12202 }
12203 }
12204
12205 if (i_isSessionMachine())
12206 {
12207 /* attach new data to the primary machine and reshare it */
12208 mPeer->mUserData.attach(mUserData);
12209 mPeer->mHWData.attach(mHWData);
12210 /* mmMediumAttachments is reshared by fixupMedia */
12211 // mPeer->mMediumAttachments.attach(mMediumAttachments);
12212 Assert(mPeer->mMediumAttachments.data() == mMediumAttachments.data());
12213 }
12214}
12215
12216/**
12217 * Copies all the hardware data from the given machine.
12218 *
12219 * Currently, only called when the VM is being restored from a snapshot. In
12220 * particular, this implies that the VM is not running during this method's
12221 * call.
12222 *
12223 * @note This method must be called from under this object's lock.
12224 *
12225 * @note This method doesn't call #i_commit(), so all data remains backed up and
12226 * unsaved.
12227 */
12228void Machine::i_copyFrom(Machine *aThat)
12229{
12230 AssertReturnVoid(!i_isSnapshotMachine());
12231 AssertReturnVoid(aThat->i_isSnapshotMachine());
12232
12233 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
12234
12235 mHWData.assignCopy(aThat->mHWData);
12236
12237 // create copies of all shared folders (mHWData after attaching a copy
12238 // contains just references to original objects)
12239 for (HWData::SharedFolderList::iterator
12240 it = mHWData->mSharedFolders.begin();
12241 it != mHWData->mSharedFolders.end();
12242 ++it)
12243 {
12244 ComObjPtr<SharedFolder> folder;
12245 folder.createObject();
12246 HRESULT rc = folder->initCopy(i_getMachine(), *it);
12247 AssertComRC(rc);
12248 *it = folder;
12249 }
12250
12251 mBIOSSettings->i_copyFrom(aThat->mBIOSSettings);
12252 mVRDEServer->i_copyFrom(aThat->mVRDEServer);
12253 mAudioAdapter->i_copyFrom(aThat->mAudioAdapter);
12254 mUSBDeviceFilters->i_copyFrom(aThat->mUSBDeviceFilters);
12255 mBandwidthControl->i_copyFrom(aThat->mBandwidthControl);
12256
12257 /* create private copies of all controllers */
12258 mStorageControllers.backup();
12259 mStorageControllers->clear();
12260 for (StorageControllerList::const_iterator
12261 it = aThat->mStorageControllers->begin();
12262 it != aThat->mStorageControllers->end();
12263 ++it)
12264 {
12265 ComObjPtr<StorageController> ctrl;
12266 ctrl.createObject();
12267 ctrl->initCopy(this, *it);
12268 mStorageControllers->push_back(ctrl);
12269 }
12270
12271 /* create private copies of all USB controllers */
12272 mUSBControllers.backup();
12273 mUSBControllers->clear();
12274 for (USBControllerList::const_iterator
12275 it = aThat->mUSBControllers->begin();
12276 it != aThat->mUSBControllers->end();
12277 ++it)
12278 {
12279 ComObjPtr<USBController> ctrl;
12280 ctrl.createObject();
12281 ctrl->initCopy(this, *it);
12282 mUSBControllers->push_back(ctrl);
12283 }
12284
12285 mNetworkAdapters.resize(aThat->mNetworkAdapters.size());
12286 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12287 {
12288 if (mNetworkAdapters[slot].isNotNull())
12289 mNetworkAdapters[slot]->i_copyFrom(aThat->mNetworkAdapters[slot]);
12290 else
12291 {
12292 unconst(mNetworkAdapters[slot]).createObject();
12293 mNetworkAdapters[slot]->initCopy(this, aThat->mNetworkAdapters[slot]);
12294 }
12295 }
12296 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12297 mSerialPorts[slot]->i_copyFrom(aThat->mSerialPorts[slot]);
12298 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12299 mParallelPorts[slot]->i_copyFrom(aThat->mParallelPorts[slot]);
12300}
12301
12302/**
12303 * Returns whether the given storage controller is hotplug capable.
12304 *
12305 * @returns true if the controller supports hotplugging
12306 * false otherwise.
12307 * @param enmCtrlType The controller type to check for.
12308 */
12309bool Machine::i_isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
12310{
12311 ComPtr<ISystemProperties> systemProperties;
12312 HRESULT rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
12313 if (FAILED(rc))
12314 return false;
12315
12316 BOOL aHotplugCapable = FALSE;
12317 systemProperties->GetStorageControllerHotplugCapable(enmCtrlType, &aHotplugCapable);
12318
12319 return RT_BOOL(aHotplugCapable);
12320}
12321
12322#ifdef VBOX_WITH_RESOURCE_USAGE_API
12323
12324void Machine::i_getDiskList(MediaList &list)
12325{
12326 for (MediumAttachmentList::const_iterator
12327 it = mMediumAttachments->begin();
12328 it != mMediumAttachments->end();
12329 ++it)
12330 {
12331 MediumAttachment *pAttach = *it;
12332 /* just in case */
12333 AssertContinue(pAttach);
12334
12335 AutoCaller localAutoCallerA(pAttach);
12336 if (FAILED(localAutoCallerA.rc())) continue;
12337
12338 AutoReadLock local_alockA(pAttach COMMA_LOCKVAL_SRC_POS);
12339
12340 if (pAttach->i_getType() == DeviceType_HardDisk)
12341 list.push_back(pAttach->i_getMedium());
12342 }
12343}
12344
12345void Machine::i_registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
12346{
12347 AssertReturnVoid(isWriteLockOnCurrentThread());
12348 AssertPtrReturnVoid(aCollector);
12349
12350 pm::CollectorHAL *hal = aCollector->getHAL();
12351 /* Create sub metrics */
12352 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
12353 "Percentage of processor time spent in user mode by the VM process.");
12354 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
12355 "Percentage of processor time spent in kernel mode by the VM process.");
12356 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
12357 "Size of resident portion of VM process in memory.");
12358 pm::SubMetric *diskUsageUsed = new pm::SubMetric("Disk/Usage/Used",
12359 "Actual size of all VM disks combined.");
12360 pm::SubMetric *machineNetRx = new pm::SubMetric("Net/Rate/Rx",
12361 "Network receive rate.");
12362 pm::SubMetric *machineNetTx = new pm::SubMetric("Net/Rate/Tx",
12363 "Network transmit rate.");
12364 /* Create and register base metrics */
12365 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
12366 cpuLoadUser, cpuLoadKernel);
12367 aCollector->registerBaseMetric(cpuLoad);
12368 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
12369 ramUsageUsed);
12370 aCollector->registerBaseMetric(ramUsage);
12371 MediaList disks;
12372 i_getDiskList(disks);
12373 pm::BaseMetric *diskUsage = new pm::MachineDiskUsage(hal, aMachine, disks,
12374 diskUsageUsed);
12375 aCollector->registerBaseMetric(diskUsage);
12376
12377 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
12378 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12379 new pm::AggregateAvg()));
12380 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12381 new pm::AggregateMin()));
12382 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12383 new pm::AggregateMax()));
12384 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
12385 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12386 new pm::AggregateAvg()));
12387 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12388 new pm::AggregateMin()));
12389 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12390 new pm::AggregateMax()));
12391
12392 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
12393 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12394 new pm::AggregateAvg()));
12395 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12396 new pm::AggregateMin()));
12397 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12398 new pm::AggregateMax()));
12399
12400 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed, 0));
12401 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12402 new pm::AggregateAvg()));
12403 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12404 new pm::AggregateMin()));
12405 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12406 new pm::AggregateMax()));
12407
12408
12409 /* Guest metrics collector */
12410 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
12411 aCollector->registerGuest(mCollectorGuest);
12412 Log7Func(("{%p}: mCollectorGuest=%p\n", this, mCollectorGuest));
12413
12414 /* Create sub metrics */
12415 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
12416 "Percentage of processor time spent in user mode as seen by the guest.");
12417 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
12418 "Percentage of processor time spent in kernel mode as seen by the guest.");
12419 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
12420 "Percentage of processor time spent idling as seen by the guest.");
12421
12422 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
12423 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
12424 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
12425 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
12426 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
12427 pm::SubMetric *guestMemCache = new pm::SubMetric(
12428 "Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
12429
12430 pm::SubMetric *guestPagedTotal = new pm::SubMetric(
12431 "Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
12432
12433 /* Create and register base metrics */
12434 pm::BaseMetric *machineNetRate = new pm::MachineNetRate(mCollectorGuest, aMachine,
12435 machineNetRx, machineNetTx);
12436 aCollector->registerBaseMetric(machineNetRate);
12437
12438 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
12439 guestLoadUser, guestLoadKernel, guestLoadIdle);
12440 aCollector->registerBaseMetric(guestCpuLoad);
12441
12442 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
12443 guestMemTotal, guestMemFree,
12444 guestMemBalloon, guestMemShared,
12445 guestMemCache, guestPagedTotal);
12446 aCollector->registerBaseMetric(guestCpuMem);
12447
12448 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, 0));
12449 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateAvg()));
12450 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMin()));
12451 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMax()));
12452
12453 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, 0));
12454 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateAvg()));
12455 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMin()));
12456 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMax()));
12457
12458 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
12459 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
12460 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
12461 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
12462
12463 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
12464 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
12465 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
12466 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
12467
12468 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
12469 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
12470 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
12471 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
12472
12473 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
12474 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
12475 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
12476 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
12477
12478 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
12479 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
12480 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
12481 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
12482
12483 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
12484 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
12485 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
12486 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
12487
12488 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
12489 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
12490 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
12491 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
12492
12493 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
12494 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
12495 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
12496 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
12497
12498 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
12499 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
12500 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
12501 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
12502}
12503
12504void Machine::i_unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
12505{
12506 AssertReturnVoid(isWriteLockOnCurrentThread());
12507
12508 if (aCollector)
12509 {
12510 aCollector->unregisterMetricsFor(aMachine);
12511 aCollector->unregisterBaseMetricsFor(aMachine);
12512 }
12513}
12514
12515#endif /* VBOX_WITH_RESOURCE_USAGE_API */
12516
12517
12518////////////////////////////////////////////////////////////////////////////////
12519
12520DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
12521
12522HRESULT SessionMachine::FinalConstruct()
12523{
12524 LogFlowThisFunc(("\n"));
12525
12526 mClientToken = NULL;
12527
12528 return BaseFinalConstruct();
12529}
12530
12531void SessionMachine::FinalRelease()
12532{
12533 LogFlowThisFunc(("\n"));
12534
12535 Assert(!mClientToken);
12536 /* paranoia, should not hang around any more */
12537 if (mClientToken)
12538 {
12539 delete mClientToken;
12540 mClientToken = NULL;
12541 }
12542
12543 uninit(Uninit::Unexpected);
12544
12545 BaseFinalRelease();
12546}
12547
12548/**
12549 * @note Must be called only by Machine::LockMachine() from its own write lock.
12550 */
12551HRESULT SessionMachine::init(Machine *aMachine)
12552{
12553 LogFlowThisFuncEnter();
12554 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
12555
12556 AssertReturn(aMachine, E_INVALIDARG);
12557
12558 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
12559
12560 /* Enclose the state transition NotReady->InInit->Ready */
12561 AutoInitSpan autoInitSpan(this);
12562 AssertReturn(autoInitSpan.isOk(), E_FAIL);
12563
12564 HRESULT rc = S_OK;
12565
12566 RT_ZERO(mAuthLibCtx);
12567
12568 /* create the machine client token */
12569 try
12570 {
12571 mClientToken = new ClientToken(aMachine, this);
12572 if (!mClientToken->isReady())
12573 {
12574 delete mClientToken;
12575 mClientToken = NULL;
12576 rc = E_FAIL;
12577 }
12578 }
12579 catch (std::bad_alloc &)
12580 {
12581 rc = E_OUTOFMEMORY;
12582 }
12583 if (FAILED(rc))
12584 return rc;
12585
12586 /* memorize the peer Machine */
12587 unconst(mPeer) = aMachine;
12588 /* share the parent pointer */
12589 unconst(mParent) = aMachine->mParent;
12590
12591 /* take the pointers to data to share */
12592 mData.share(aMachine->mData);
12593 mSSData.share(aMachine->mSSData);
12594
12595 mUserData.share(aMachine->mUserData);
12596 mHWData.share(aMachine->mHWData);
12597 mMediumAttachments.share(aMachine->mMediumAttachments);
12598
12599 mStorageControllers.allocate();
12600 for (StorageControllerList::const_iterator
12601 it = aMachine->mStorageControllers->begin();
12602 it != aMachine->mStorageControllers->end();
12603 ++it)
12604 {
12605 ComObjPtr<StorageController> ctl;
12606 ctl.createObject();
12607 ctl->init(this, *it);
12608 mStorageControllers->push_back(ctl);
12609 }
12610
12611 mUSBControllers.allocate();
12612 for (USBControllerList::const_iterator
12613 it = aMachine->mUSBControllers->begin();
12614 it != aMachine->mUSBControllers->end();
12615 ++it)
12616 {
12617 ComObjPtr<USBController> ctl;
12618 ctl.createObject();
12619 ctl->init(this, *it);
12620 mUSBControllers->push_back(ctl);
12621 }
12622
12623 unconst(mBIOSSettings).createObject();
12624 mBIOSSettings->init(this, aMachine->mBIOSSettings);
12625 /* create another VRDEServer object that will be mutable */
12626 unconst(mVRDEServer).createObject();
12627 mVRDEServer->init(this, aMachine->mVRDEServer);
12628 /* create another audio adapter object that will be mutable */
12629 unconst(mAudioAdapter).createObject();
12630 mAudioAdapter->init(this, aMachine->mAudioAdapter);
12631 /* create a list of serial ports that will be mutable */
12632 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12633 {
12634 unconst(mSerialPorts[slot]).createObject();
12635 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
12636 }
12637 /* create a list of parallel ports that will be mutable */
12638 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12639 {
12640 unconst(mParallelPorts[slot]).createObject();
12641 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
12642 }
12643
12644 /* create another USB device filters object that will be mutable */
12645 unconst(mUSBDeviceFilters).createObject();
12646 mUSBDeviceFilters->init(this, aMachine->mUSBDeviceFilters);
12647
12648 /* create a list of network adapters that will be mutable */
12649 mNetworkAdapters.resize(aMachine->mNetworkAdapters.size());
12650 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12651 {
12652 unconst(mNetworkAdapters[slot]).createObject();
12653 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
12654 }
12655
12656 /* create another bandwidth control object that will be mutable */
12657 unconst(mBandwidthControl).createObject();
12658 mBandwidthControl->init(this, aMachine->mBandwidthControl);
12659
12660#ifdef VBOX_WITH_UNATTENDED
12661 /* create another unattended object that will be mutable */
12662 /** @todo r=bird: Why don't we create this when the IUnattended instance
12663 * is queried? */
12664 unconst(mUnattended).createObject();
12665 mUnattended->initWithUnattended(this, aMachine->mUnattended);
12666#endif
12667
12668 /* default is to delete saved state on Saved -> PoweredOff transition */
12669 mRemoveSavedState = true;
12670
12671 /* Confirm a successful initialization when it's the case */
12672 autoInitSpan.setSucceeded();
12673
12674 miNATNetworksStarted = 0;
12675
12676 LogFlowThisFuncLeave();
12677 return rc;
12678}
12679
12680/**
12681 * Uninitializes this session object. If the reason is other than
12682 * Uninit::Unexpected, then this method MUST be called from #i_checkForDeath()
12683 * or the client watcher code.
12684 *
12685 * @param aReason uninitialization reason
12686 *
12687 * @note Locks mParent + this object for writing.
12688 */
12689void SessionMachine::uninit(Uninit::Reason aReason)
12690{
12691 LogFlowThisFuncEnter();
12692 LogFlowThisFunc(("reason=%d\n", aReason));
12693
12694 /*
12695 * Strongly reference ourselves to prevent this object deletion after
12696 * mData->mSession.mMachine.setNull() below (which can release the last
12697 * reference and call the destructor). Important: this must be done before
12698 * accessing any members (and before AutoUninitSpan that does it as well).
12699 * This self reference will be released as the very last step on return.
12700 */
12701 ComObjPtr<SessionMachine> selfRef;
12702 if (aReason != Uninit::Unexpected)
12703 selfRef = this;
12704
12705 /* Enclose the state transition Ready->InUninit->NotReady */
12706 AutoUninitSpan autoUninitSpan(this);
12707 if (autoUninitSpan.uninitDone())
12708 {
12709 LogFlowThisFunc(("Already uninitialized\n"));
12710 LogFlowThisFuncLeave();
12711 return;
12712 }
12713
12714 if (autoUninitSpan.initFailed())
12715 {
12716 /* We've been called by init() because it's failed. It's not really
12717 * necessary (nor it's safe) to perform the regular uninit sequence
12718 * below, the following is enough.
12719 */
12720 LogFlowThisFunc(("Initialization failed.\n"));
12721 /* destroy the machine client token */
12722 if (mClientToken)
12723 {
12724 delete mClientToken;
12725 mClientToken = NULL;
12726 }
12727 uninitDataAndChildObjects();
12728 mData.free();
12729 unconst(mParent) = NULL;
12730 unconst(mPeer) = NULL;
12731 LogFlowThisFuncLeave();
12732 return;
12733 }
12734
12735 MachineState_T lastState;
12736 {
12737 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
12738 lastState = mData->mMachineState;
12739 }
12740 NOREF(lastState);
12741
12742#ifdef VBOX_WITH_USB
12743 // release all captured USB devices, but do this before requesting the locks below
12744 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
12745 {
12746 /* Console::captureUSBDevices() is called in the VM process only after
12747 * setting the machine state to Starting or Restoring.
12748 * Console::detachAllUSBDevices() will be called upon successful
12749 * termination. So, we need to release USB devices only if there was
12750 * an abnormal termination of a running VM.
12751 *
12752 * This is identical to SessionMachine::DetachAllUSBDevices except
12753 * for the aAbnormal argument. */
12754 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
12755 AssertComRC(rc);
12756 NOREF(rc);
12757
12758 USBProxyService *service = mParent->i_host()->i_usbProxyService();
12759 if (service)
12760 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
12761 }
12762#endif /* VBOX_WITH_USB */
12763
12764 // we need to lock this object in uninit() because the lock is shared
12765 // with mPeer (as well as data we modify below). mParent lock is needed
12766 // by several calls to it.
12767 AutoMultiWriteLock2 multilock(mParent, this COMMA_LOCKVAL_SRC_POS);
12768
12769#ifdef VBOX_WITH_RESOURCE_USAGE_API
12770 /*
12771 * It is safe to call Machine::i_unregisterMetrics() here because
12772 * PerformanceCollector::samplerCallback no longer accesses guest methods
12773 * holding the lock.
12774 */
12775 i_unregisterMetrics(mParent->i_performanceCollector(), mPeer);
12776 /* The guest must be unregistered after its metrics (@bugref{5949}). */
12777 Log7Func(("{%p}: mCollectorGuest=%p\n", this, mCollectorGuest));
12778 if (mCollectorGuest)
12779 {
12780 mParent->i_performanceCollector()->unregisterGuest(mCollectorGuest);
12781 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
12782 mCollectorGuest = NULL;
12783 }
12784#endif
12785
12786 if (aReason == Uninit::Abnormal)
12787 {
12788 Log1WarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n", Global::IsOnlineOrTransient(lastState)));
12789
12790 /* reset the state to Aborted */
12791 if (mData->mMachineState != MachineState_Aborted)
12792 i_setMachineState(MachineState_Aborted);
12793 }
12794
12795 // any machine settings modified?
12796 if (mData->flModifications)
12797 {
12798 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
12799 i_rollback(false /* aNotify */);
12800 }
12801
12802 mData->mSession.mPID = NIL_RTPROCESS;
12803
12804 if (aReason == Uninit::Unexpected)
12805 {
12806 /* Uninitialization didn't come from #i_checkForDeath(), so tell the
12807 * client watcher thread to update the set of machines that have open
12808 * sessions. */
12809 mParent->i_updateClientWatcher();
12810 }
12811
12812 /* uninitialize all remote controls */
12813 if (mData->mSession.mRemoteControls.size())
12814 {
12815 LogFlowThisFunc(("Closing remote sessions (%d):\n",
12816 mData->mSession.mRemoteControls.size()));
12817
12818 /* Always restart a the beginning, since the iterator is invalidated
12819 * by using erase(). */
12820 for (Data::Session::RemoteControlList::iterator
12821 it = mData->mSession.mRemoteControls.begin();
12822 it != mData->mSession.mRemoteControls.end();
12823 it = mData->mSession.mRemoteControls.begin())
12824 {
12825 ComPtr<IInternalSessionControl> pControl = *it;
12826 mData->mSession.mRemoteControls.erase(it);
12827 multilock.release();
12828 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
12829 HRESULT rc = pControl->Uninitialize();
12830 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
12831 if (FAILED(rc))
12832 Log1WarningThisFunc(("Forgot to close the remote session?\n"));
12833 multilock.acquire();
12834 }
12835 mData->mSession.mRemoteControls.clear();
12836 }
12837
12838 /* Remove all references to the NAT network service. The service will stop
12839 * if all references (also from other VMs) are removed. */
12840 for (; miNATNetworksStarted > 0; miNATNetworksStarted--)
12841 {
12842 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12843 {
12844 BOOL enabled;
12845 HRESULT hrc = mNetworkAdapters[slot]->COMGETTER(Enabled)(&enabled);
12846 if ( FAILED(hrc)
12847 || !enabled)
12848 continue;
12849
12850 NetworkAttachmentType_T type;
12851 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
12852 if ( SUCCEEDED(hrc)
12853 && type == NetworkAttachmentType_NATNetwork)
12854 {
12855 Bstr name;
12856 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
12857 if (SUCCEEDED(hrc))
12858 {
12859 multilock.release();
12860 Utf8Str strName(name);
12861 LogRel(("VM '%s' stops using NAT network '%s'\n",
12862 mUserData->s.strName.c_str(), strName.c_str()));
12863 mParent->i_natNetworkRefDec(strName);
12864 multilock.acquire();
12865 }
12866 }
12867 }
12868 }
12869
12870 /*
12871 * An expected uninitialization can come only from #i_checkForDeath().
12872 * Otherwise it means that something's gone really wrong (for example,
12873 * the Session implementation has released the VirtualBox reference
12874 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
12875 * etc). However, it's also possible, that the client releases the IPC
12876 * semaphore correctly (i.e. before it releases the VirtualBox reference),
12877 * but the VirtualBox release event comes first to the server process.
12878 * This case is practically possible, so we should not assert on an
12879 * unexpected uninit, just log a warning.
12880 */
12881
12882 if (aReason == Uninit::Unexpected)
12883 Log1WarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
12884
12885 if (aReason != Uninit::Normal)
12886 {
12887 mData->mSession.mDirectControl.setNull();
12888 }
12889 else
12890 {
12891 /* this must be null here (see #OnSessionEnd()) */
12892 Assert(mData->mSession.mDirectControl.isNull());
12893 Assert(mData->mSession.mState == SessionState_Unlocking);
12894 Assert(!mData->mSession.mProgress.isNull());
12895 }
12896 if (mData->mSession.mProgress)
12897 {
12898 if (aReason == Uninit::Normal)
12899 mData->mSession.mProgress->i_notifyComplete(S_OK);
12900 else
12901 mData->mSession.mProgress->i_notifyComplete(E_FAIL,
12902 COM_IIDOF(ISession),
12903 getComponentName(),
12904 tr("The VM session was aborted"));
12905 mData->mSession.mProgress.setNull();
12906 }
12907
12908 if (mConsoleTaskData.mProgress)
12909 {
12910 Assert(aReason == Uninit::Abnormal);
12911 mConsoleTaskData.mProgress->i_notifyComplete(E_FAIL,
12912 COM_IIDOF(ISession),
12913 getComponentName(),
12914 tr("The VM session was aborted"));
12915 mConsoleTaskData.mProgress.setNull();
12916 }
12917
12918 /* remove the association between the peer machine and this session machine */
12919 Assert( (SessionMachine*)mData->mSession.mMachine == this
12920 || aReason == Uninit::Unexpected);
12921
12922 /* reset the rest of session data */
12923 mData->mSession.mLockType = LockType_Null;
12924 mData->mSession.mMachine.setNull();
12925 mData->mSession.mState = SessionState_Unlocked;
12926 mData->mSession.mName.setNull();
12927
12928 /* destroy the machine client token before leaving the exclusive lock */
12929 if (mClientToken)
12930 {
12931 delete mClientToken;
12932 mClientToken = NULL;
12933 }
12934
12935 /* fire an event */
12936 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
12937
12938 uninitDataAndChildObjects();
12939
12940 /* free the essential data structure last */
12941 mData.free();
12942
12943 /* release the exclusive lock before setting the below two to NULL */
12944 multilock.release();
12945
12946 unconst(mParent) = NULL;
12947 unconst(mPeer) = NULL;
12948
12949 AuthLibUnload(&mAuthLibCtx);
12950
12951 LogFlowThisFuncLeave();
12952}
12953
12954// util::Lockable interface
12955////////////////////////////////////////////////////////////////////////////////
12956
12957/**
12958 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
12959 * with the primary Machine instance (mPeer).
12960 */
12961RWLockHandle *SessionMachine::lockHandle() const
12962{
12963 AssertReturn(mPeer != NULL, NULL);
12964 return mPeer->lockHandle();
12965}
12966
12967// IInternalMachineControl methods
12968////////////////////////////////////////////////////////////////////////////////
12969
12970/**
12971 * Passes collected guest statistics to performance collector object
12972 */
12973HRESULT SessionMachine::reportVmStatistics(ULONG aValidStats, ULONG aCpuUser,
12974 ULONG aCpuKernel, ULONG aCpuIdle,
12975 ULONG aMemTotal, ULONG aMemFree,
12976 ULONG aMemBalloon, ULONG aMemShared,
12977 ULONG aMemCache, ULONG aPageTotal,
12978 ULONG aAllocVMM, ULONG aFreeVMM,
12979 ULONG aBalloonedVMM, ULONG aSharedVMM,
12980 ULONG aVmNetRx, ULONG aVmNetTx)
12981{
12982#ifdef VBOX_WITH_RESOURCE_USAGE_API
12983 if (mCollectorGuest)
12984 mCollectorGuest->updateStats(aValidStats, aCpuUser, aCpuKernel, aCpuIdle,
12985 aMemTotal, aMemFree, aMemBalloon, aMemShared,
12986 aMemCache, aPageTotal, aAllocVMM, aFreeVMM,
12987 aBalloonedVMM, aSharedVMM, aVmNetRx, aVmNetTx);
12988
12989 return S_OK;
12990#else
12991 NOREF(aValidStats);
12992 NOREF(aCpuUser);
12993 NOREF(aCpuKernel);
12994 NOREF(aCpuIdle);
12995 NOREF(aMemTotal);
12996 NOREF(aMemFree);
12997 NOREF(aMemBalloon);
12998 NOREF(aMemShared);
12999 NOREF(aMemCache);
13000 NOREF(aPageTotal);
13001 NOREF(aAllocVMM);
13002 NOREF(aFreeVMM);
13003 NOREF(aBalloonedVMM);
13004 NOREF(aSharedVMM);
13005 NOREF(aVmNetRx);
13006 NOREF(aVmNetTx);
13007 return E_NOTIMPL;
13008#endif
13009}
13010
13011////////////////////////////////////////////////////////////////////////////////
13012//
13013// SessionMachine task records
13014//
13015////////////////////////////////////////////////////////////////////////////////
13016
13017/**
13018 * Task record for saving the machine state.
13019 */
13020class SessionMachine::SaveStateTask
13021 : public Machine::Task
13022{
13023public:
13024 SaveStateTask(SessionMachine *m,
13025 Progress *p,
13026 const Utf8Str &t,
13027 Reason_T enmReason,
13028 const Utf8Str &strStateFilePath)
13029 : Task(m, p, t),
13030 m_enmReason(enmReason),
13031 m_strStateFilePath(strStateFilePath)
13032 {}
13033
13034private:
13035 void handler()
13036 {
13037 ((SessionMachine *)(Machine *)m_pMachine)->i_saveStateHandler(*this);
13038 }
13039
13040 Reason_T m_enmReason;
13041 Utf8Str m_strStateFilePath;
13042
13043 friend class SessionMachine;
13044};
13045
13046/**
13047 * Task thread implementation for SessionMachine::SaveState(), called from
13048 * SessionMachine::taskHandler().
13049 *
13050 * @note Locks this object for writing.
13051 *
13052 * @param task
13053 * @return
13054 */
13055void SessionMachine::i_saveStateHandler(SaveStateTask &task)
13056{
13057 LogFlowThisFuncEnter();
13058
13059 AutoCaller autoCaller(this);
13060 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
13061 if (FAILED(autoCaller.rc()))
13062 {
13063 /* we might have been uninitialized because the session was accidentally
13064 * closed by the client, so don't assert */
13065 HRESULT rc = setError(E_FAIL,
13066 tr("The session has been accidentally closed"));
13067 task.m_pProgress->i_notifyComplete(rc);
13068 LogFlowThisFuncLeave();
13069 return;
13070 }
13071
13072 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13073
13074 HRESULT rc = S_OK;
13075
13076 try
13077 {
13078 ComPtr<IInternalSessionControl> directControl;
13079 if (mData->mSession.mLockType == LockType_VM)
13080 directControl = mData->mSession.mDirectControl;
13081 if (directControl.isNull())
13082 throw setError(VBOX_E_INVALID_VM_STATE,
13083 tr("Trying to save state without a running VM"));
13084 alock.release();
13085 BOOL fSuspendedBySave;
13086 rc = directControl->SaveStateWithReason(task.m_enmReason, task.m_pProgress, Bstr(task.m_strStateFilePath).raw(), task.m_machineStateBackup != MachineState_Paused, &fSuspendedBySave);
13087 Assert(!fSuspendedBySave);
13088 alock.acquire();
13089
13090 AssertStmt( (SUCCEEDED(rc) && mData->mMachineState == MachineState_Saved)
13091 || (FAILED(rc) && mData->mMachineState == MachineState_Saving),
13092 throw E_FAIL);
13093
13094 if (SUCCEEDED(rc))
13095 {
13096 mSSData->strStateFilePath = task.m_strStateFilePath;
13097
13098 /* save all VM settings */
13099 rc = i_saveSettings(NULL);
13100 // no need to check whether VirtualBox.xml needs saving also since
13101 // we can't have a name change pending at this point
13102 }
13103 else
13104 {
13105 // On failure, set the state to the state we had at the beginning.
13106 i_setMachineState(task.m_machineStateBackup);
13107 i_updateMachineStateOnClient();
13108
13109 // Delete the saved state file (might have been already created).
13110 // No need to check whether this is shared with a snapshot here
13111 // because we certainly created a fresh saved state file here.
13112 RTFileDelete(task.m_strStateFilePath.c_str());
13113 }
13114 }
13115 catch (HRESULT aRC) { rc = aRC; }
13116
13117 task.m_pProgress->i_notifyComplete(rc);
13118
13119 LogFlowThisFuncLeave();
13120}
13121
13122/**
13123 * @note Locks this object for writing.
13124 */
13125HRESULT SessionMachine::saveState(ComPtr<IProgress> &aProgress)
13126{
13127 return i_saveStateWithReason(Reason_Unspecified, aProgress);
13128}
13129
13130HRESULT SessionMachine::i_saveStateWithReason(Reason_T aReason, ComPtr<IProgress> &aProgress)
13131{
13132 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13133
13134 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
13135 if (FAILED(rc)) return rc;
13136
13137 if ( mData->mMachineState != MachineState_Running
13138 && mData->mMachineState != MachineState_Paused
13139 )
13140 return setError(VBOX_E_INVALID_VM_STATE,
13141 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
13142 Global::stringifyMachineState(mData->mMachineState));
13143
13144 ComObjPtr<Progress> pProgress;
13145 pProgress.createObject();
13146 rc = pProgress->init(i_getVirtualBox(),
13147 static_cast<IMachine *>(this) /* aInitiator */,
13148 tr("Saving the execution state of the virtual machine"),
13149 FALSE /* aCancelable */);
13150 if (FAILED(rc))
13151 return rc;
13152
13153 Utf8Str strStateFilePath;
13154 i_composeSavedStateFilename(strStateFilePath);
13155
13156 /* create and start the task on a separate thread (note that it will not
13157 * start working until we release alock) */
13158 SaveStateTask *pTask = new SaveStateTask(this, pProgress, "SaveState", aReason, strStateFilePath);
13159 rc = pTask->createThread();
13160 if (FAILED(rc))
13161 return rc;
13162
13163 /* set the state to Saving (expected by Session::SaveStateWithReason()) */
13164 i_setMachineState(MachineState_Saving);
13165 i_updateMachineStateOnClient();
13166
13167 pProgress.queryInterfaceTo(aProgress.asOutParam());
13168
13169 return S_OK;
13170}
13171
13172/**
13173 * @note Locks this object for writing.
13174 */
13175HRESULT SessionMachine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
13176{
13177 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13178
13179 HRESULT rc = i_checkStateDependency(MutableStateDep);
13180 if (FAILED(rc)) return rc;
13181
13182 if ( mData->mMachineState != MachineState_PoweredOff
13183 && mData->mMachineState != MachineState_Teleported
13184 && mData->mMachineState != MachineState_Aborted
13185 )
13186 return setError(VBOX_E_INVALID_VM_STATE,
13187 tr("Cannot adopt the saved machine state as the machine is not in Powered Off, Teleported or Aborted state (machine state: %s)"),
13188 Global::stringifyMachineState(mData->mMachineState));
13189
13190 com::Utf8Str stateFilePathFull;
13191 int vrc = i_calculateFullPath(aSavedStateFile, stateFilePathFull);
13192 if (RT_FAILURE(vrc))
13193 return setError(VBOX_E_FILE_ERROR,
13194 tr("Invalid saved state file path '%s' (%Rrc)"),
13195 aSavedStateFile.c_str(),
13196 vrc);
13197
13198 mSSData->strStateFilePath = stateFilePathFull;
13199
13200 /* The below i_setMachineState() will detect the state transition and will
13201 * update the settings file */
13202
13203 return i_setMachineState(MachineState_Saved);
13204}
13205
13206/**
13207 * @note Locks this object for writing.
13208 */
13209HRESULT SessionMachine::discardSavedState(BOOL aFRemoveFile)
13210{
13211 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13212
13213 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
13214 if (FAILED(rc)) return rc;
13215
13216 if (mData->mMachineState != MachineState_Saved)
13217 return setError(VBOX_E_INVALID_VM_STATE,
13218 tr("Cannot delete the machine state as the machine is not in the saved state (machine state: %s)"),
13219 Global::stringifyMachineState(mData->mMachineState));
13220
13221 mRemoveSavedState = RT_BOOL(aFRemoveFile);
13222
13223 /*
13224 * Saved -> PoweredOff transition will be detected in the SessionMachine
13225 * and properly handled.
13226 */
13227 rc = i_setMachineState(MachineState_PoweredOff);
13228 return rc;
13229}
13230
13231
13232/**
13233 * @note Locks the same as #i_setMachineState() does.
13234 */
13235HRESULT SessionMachine::updateState(MachineState_T aState)
13236{
13237 return i_setMachineState(aState);
13238}
13239
13240/**
13241 * @note Locks this object for writing.
13242 */
13243HRESULT SessionMachine::beginPowerUp(const ComPtr<IProgress> &aProgress)
13244{
13245 IProgress *pProgress(aProgress);
13246
13247 LogFlowThisFunc(("aProgress=%p\n", pProgress));
13248
13249 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13250
13251 if (mData->mSession.mState != SessionState_Locked)
13252 return VBOX_E_INVALID_OBJECT_STATE;
13253
13254 if (!mData->mSession.mProgress.isNull())
13255 mData->mSession.mProgress->setOtherProgressObject(pProgress);
13256
13257 /* If we didn't reference the NAT network service yet, add a reference to
13258 * force a start */
13259 if (miNATNetworksStarted < 1)
13260 {
13261 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
13262 {
13263 BOOL enabled;
13264 HRESULT hrc = mNetworkAdapters[slot]->COMGETTER(Enabled)(&enabled);
13265 if ( FAILED(hrc)
13266 || !enabled)
13267 continue;
13268
13269 NetworkAttachmentType_T type;
13270 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
13271 if ( SUCCEEDED(hrc)
13272 && type == NetworkAttachmentType_NATNetwork)
13273 {
13274 Bstr name;
13275 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
13276 if (SUCCEEDED(hrc))
13277 {
13278 Utf8Str strName(name);
13279 LogRel(("VM '%s' starts using NAT network '%s'\n",
13280 mUserData->s.strName.c_str(), strName.c_str()));
13281 mPeer->lockHandle()->unlockWrite();
13282 mParent->i_natNetworkRefInc(strName);
13283#ifdef RT_LOCK_STRICT
13284 mPeer->lockHandle()->lockWrite(RT_SRC_POS);
13285#else
13286 mPeer->lockHandle()->lockWrite();
13287#endif
13288 }
13289 }
13290 }
13291 miNATNetworksStarted++;
13292 }
13293
13294 LogFlowThisFunc(("returns S_OK.\n"));
13295 return S_OK;
13296}
13297
13298/**
13299 * @note Locks this object for writing.
13300 */
13301HRESULT SessionMachine::endPowerUp(LONG aResult)
13302{
13303 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13304
13305 if (mData->mSession.mState != SessionState_Locked)
13306 return VBOX_E_INVALID_OBJECT_STATE;
13307
13308 /* Finalize the LaunchVMProcess progress object. */
13309 if (mData->mSession.mProgress)
13310 {
13311 mData->mSession.mProgress->notifyComplete((HRESULT)aResult);
13312 mData->mSession.mProgress.setNull();
13313 }
13314
13315 if (SUCCEEDED((HRESULT)aResult))
13316 {
13317#ifdef VBOX_WITH_RESOURCE_USAGE_API
13318 /* The VM has been powered up successfully, so it makes sense
13319 * now to offer the performance metrics for a running machine
13320 * object. Doing it earlier wouldn't be safe. */
13321 i_registerMetrics(mParent->i_performanceCollector(), mPeer,
13322 mData->mSession.mPID);
13323#endif /* VBOX_WITH_RESOURCE_USAGE_API */
13324 }
13325
13326 return S_OK;
13327}
13328
13329/**
13330 * @note Locks this object for writing.
13331 */
13332HRESULT SessionMachine::beginPoweringDown(ComPtr<IProgress> &aProgress)
13333{
13334 LogFlowThisFuncEnter();
13335
13336 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13337
13338 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
13339 E_FAIL);
13340
13341 /* create a progress object to track operation completion */
13342 ComObjPtr<Progress> pProgress;
13343 pProgress.createObject();
13344 pProgress->init(i_getVirtualBox(),
13345 static_cast<IMachine *>(this) /* aInitiator */,
13346 tr("Stopping the virtual machine"),
13347 FALSE /* aCancelable */);
13348
13349 /* fill in the console task data */
13350 mConsoleTaskData.mLastState = mData->mMachineState;
13351 mConsoleTaskData.mProgress = pProgress;
13352
13353 /* set the state to Stopping (this is expected by Console::PowerDown()) */
13354 i_setMachineState(MachineState_Stopping);
13355
13356 pProgress.queryInterfaceTo(aProgress.asOutParam());
13357
13358 return S_OK;
13359}
13360
13361/**
13362 * @note Locks this object for writing.
13363 */
13364HRESULT SessionMachine::endPoweringDown(LONG aResult,
13365 const com::Utf8Str &aErrMsg)
13366{
13367 LogFlowThisFuncEnter();
13368
13369 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13370
13371 AssertReturn( ( (SUCCEEDED(aResult) && mData->mMachineState == MachineState_PoweredOff)
13372 || (FAILED(aResult) && mData->mMachineState == MachineState_Stopping))
13373 && mConsoleTaskData.mLastState != MachineState_Null,
13374 E_FAIL);
13375
13376 /*
13377 * On failure, set the state to the state we had when BeginPoweringDown()
13378 * was called (this is expected by Console::PowerDown() and the associated
13379 * task). On success the VM process already changed the state to
13380 * MachineState_PoweredOff, so no need to do anything.
13381 */
13382 if (FAILED(aResult))
13383 i_setMachineState(mConsoleTaskData.mLastState);
13384
13385 /* notify the progress object about operation completion */
13386 Assert(mConsoleTaskData.mProgress);
13387 if (SUCCEEDED(aResult))
13388 mConsoleTaskData.mProgress->i_notifyComplete(S_OK);
13389 else
13390 {
13391 if (aErrMsg.length())
13392 mConsoleTaskData.mProgress->i_notifyComplete(aResult,
13393 COM_IIDOF(ISession),
13394 getComponentName(),
13395 aErrMsg.c_str());
13396 else
13397 mConsoleTaskData.mProgress->i_notifyComplete(aResult);
13398 }
13399
13400 /* clear out the temporary saved state data */
13401 mConsoleTaskData.mLastState = MachineState_Null;
13402 mConsoleTaskData.mProgress.setNull();
13403
13404 LogFlowThisFuncLeave();
13405 return S_OK;
13406}
13407
13408
13409/**
13410 * Goes through the USB filters of the given machine to see if the given
13411 * device matches any filter or not.
13412 *
13413 * @note Locks the same as USBController::hasMatchingFilter() does.
13414 */
13415HRESULT SessionMachine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
13416 BOOL *aMatched,
13417 ULONG *aMaskedInterfaces)
13418{
13419 LogFlowThisFunc(("\n"));
13420
13421#ifdef VBOX_WITH_USB
13422 *aMatched = mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedInterfaces);
13423#else
13424 NOREF(aDevice);
13425 NOREF(aMaskedInterfaces);
13426 *aMatched = FALSE;
13427#endif
13428
13429 return S_OK;
13430}
13431
13432/**
13433 * @note Locks the same as Host::captureUSBDevice() does.
13434 */
13435HRESULT SessionMachine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
13436{
13437 LogFlowThisFunc(("\n"));
13438
13439#ifdef VBOX_WITH_USB
13440 /* if captureDeviceForVM() fails, it must have set extended error info */
13441 clearError();
13442 MultiResult rc = mParent->i_host()->i_checkUSBProxyService();
13443 if (FAILED(rc)) return rc;
13444
13445 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13446 AssertReturn(service, E_FAIL);
13447 return service->captureDeviceForVM(this, aId.ref(), aCaptureFilename);
13448#else
13449 NOREF(aId);
13450 return E_NOTIMPL;
13451#endif
13452}
13453
13454/**
13455 * @note Locks the same as Host::detachUSBDevice() does.
13456 */
13457HRESULT SessionMachine::detachUSBDevice(const com::Guid &aId,
13458 BOOL aDone)
13459{
13460 LogFlowThisFunc(("\n"));
13461
13462#ifdef VBOX_WITH_USB
13463 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13464 AssertReturn(service, E_FAIL);
13465 return service->detachDeviceFromVM(this, aId.ref(), !!aDone);
13466#else
13467 NOREF(aId);
13468 NOREF(aDone);
13469 return E_NOTIMPL;
13470#endif
13471}
13472
13473/**
13474 * Inserts all machine filters to the USB proxy service and then calls
13475 * Host::autoCaptureUSBDevices().
13476 *
13477 * Called by Console from the VM process upon VM startup.
13478 *
13479 * @note Locks what called methods lock.
13480 */
13481HRESULT SessionMachine::autoCaptureUSBDevices()
13482{
13483 LogFlowThisFunc(("\n"));
13484
13485#ifdef VBOX_WITH_USB
13486 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(true /* aInsertFilters */);
13487 AssertComRC(rc);
13488 NOREF(rc);
13489
13490 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13491 AssertReturn(service, E_FAIL);
13492 return service->autoCaptureDevicesForVM(this);
13493#else
13494 return S_OK;
13495#endif
13496}
13497
13498/**
13499 * Removes all machine filters from the USB proxy service and then calls
13500 * Host::detachAllUSBDevices().
13501 *
13502 * Called by Console from the VM process upon normal VM termination or by
13503 * SessionMachine::uninit() upon abnormal VM termination (from under the
13504 * Machine/SessionMachine lock).
13505 *
13506 * @note Locks what called methods lock.
13507 */
13508HRESULT SessionMachine::detachAllUSBDevices(BOOL aDone)
13509{
13510 LogFlowThisFunc(("\n"));
13511
13512#ifdef VBOX_WITH_USB
13513 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
13514 AssertComRC(rc);
13515 NOREF(rc);
13516
13517 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13518 AssertReturn(service, E_FAIL);
13519 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
13520#else
13521 NOREF(aDone);
13522 return S_OK;
13523#endif
13524}
13525
13526/**
13527 * @note Locks this object for writing.
13528 */
13529HRESULT SessionMachine::onSessionEnd(const ComPtr<ISession> &aSession,
13530 ComPtr<IProgress> &aProgress)
13531{
13532 LogFlowThisFuncEnter();
13533
13534 LogFlowThisFunc(("callerstate=%d\n", getObjectState().getState()));
13535 /*
13536 * We don't assert below because it might happen that a non-direct session
13537 * informs us it is closed right after we've been uninitialized -- it's ok.
13538 */
13539
13540 /* get IInternalSessionControl interface */
13541 ComPtr<IInternalSessionControl> control(aSession);
13542
13543 ComAssertRet(!control.isNull(), E_INVALIDARG);
13544
13545 /* Creating a Progress object requires the VirtualBox lock, and
13546 * thus locking it here is required by the lock order rules. */
13547 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
13548
13549 if (control == mData->mSession.mDirectControl)
13550 {
13551 /* The direct session is being normally closed by the client process
13552 * ----------------------------------------------------------------- */
13553
13554 /* go to the closing state (essential for all open*Session() calls and
13555 * for #i_checkForDeath()) */
13556 Assert(mData->mSession.mState == SessionState_Locked);
13557 mData->mSession.mState = SessionState_Unlocking;
13558
13559 /* set direct control to NULL to release the remote instance */
13560 mData->mSession.mDirectControl.setNull();
13561 LogFlowThisFunc(("Direct control is set to NULL\n"));
13562
13563 if (mData->mSession.mProgress)
13564 {
13565 /* finalize the progress, someone might wait if a frontend
13566 * closes the session before powering on the VM. */
13567 mData->mSession.mProgress->notifyComplete(E_FAIL,
13568 COM_IIDOF(ISession),
13569 getComponentName(),
13570 tr("The VM session was closed before any attempt to power it on"));
13571 mData->mSession.mProgress.setNull();
13572 }
13573
13574 /* Create the progress object the client will use to wait until
13575 * #i_checkForDeath() is called to uninitialize this session object after
13576 * it releases the IPC semaphore.
13577 * Note! Because we're "reusing" mProgress here, this must be a proxy
13578 * object just like for LaunchVMProcess. */
13579 Assert(mData->mSession.mProgress.isNull());
13580 ComObjPtr<ProgressProxy> progress;
13581 progress.createObject();
13582 ComPtr<IUnknown> pPeer(mPeer);
13583 progress->init(mParent, pPeer,
13584 Bstr(tr("Closing session")).raw(),
13585 FALSE /* aCancelable */);
13586 progress.queryInterfaceTo(aProgress.asOutParam());
13587 mData->mSession.mProgress = progress;
13588 }
13589 else
13590 {
13591 /* the remote session is being normally closed */
13592 bool found = false;
13593 for (Data::Session::RemoteControlList::iterator
13594 it = mData->mSession.mRemoteControls.begin();
13595 it != mData->mSession.mRemoteControls.end();
13596 ++it)
13597 {
13598 if (control == *it)
13599 {
13600 found = true;
13601 // This MUST be erase(it), not remove(*it) as the latter
13602 // triggers a very nasty use after free due to the place where
13603 // the value "lives".
13604 mData->mSession.mRemoteControls.erase(it);
13605 break;
13606 }
13607 }
13608 ComAssertMsgRet(found, ("The session is not found in the session list!"),
13609 E_INVALIDARG);
13610 }
13611
13612 /* signal the client watcher thread, because the client is going away */
13613 mParent->i_updateClientWatcher();
13614
13615 LogFlowThisFuncLeave();
13616 return S_OK;
13617}
13618
13619HRESULT SessionMachine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
13620 std::vector<com::Utf8Str> &aValues,
13621 std::vector<LONG64> &aTimestamps,
13622 std::vector<com::Utf8Str> &aFlags)
13623{
13624 LogFlowThisFunc(("\n"));
13625
13626#ifdef VBOX_WITH_GUEST_PROPS
13627 using namespace guestProp;
13628
13629 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13630
13631 size_t cEntries = mHWData->mGuestProperties.size();
13632 aNames.resize(cEntries);
13633 aValues.resize(cEntries);
13634 aTimestamps.resize(cEntries);
13635 aFlags.resize(cEntries);
13636
13637 size_t i = 0;
13638 for (HWData::GuestPropertyMap::const_iterator
13639 it = mHWData->mGuestProperties.begin();
13640 it != mHWData->mGuestProperties.end();
13641 ++it, ++i)
13642 {
13643 char szFlags[MAX_FLAGS_LEN + 1];
13644 aNames[i] = it->first;
13645 aValues[i] = it->second.strValue;
13646 aTimestamps[i] = it->second.mTimestamp;
13647
13648 /* If it is NULL, keep it NULL. */
13649 if (it->second.mFlags)
13650 {
13651 writeFlags(it->second.mFlags, szFlags);
13652 aFlags[i] = szFlags;
13653 }
13654 else
13655 aFlags[i] = "";
13656 }
13657 return S_OK;
13658#else
13659 ReturnComNotImplemented();
13660#endif
13661}
13662
13663HRESULT SessionMachine::pushGuestProperty(const com::Utf8Str &aName,
13664 const com::Utf8Str &aValue,
13665 LONG64 aTimestamp,
13666 const com::Utf8Str &aFlags)
13667{
13668 LogFlowThisFunc(("\n"));
13669
13670#ifdef VBOX_WITH_GUEST_PROPS
13671 using namespace guestProp;
13672
13673 try
13674 {
13675 /*
13676 * Convert input up front.
13677 */
13678 uint32_t fFlags = NILFLAG;
13679 if (aFlags.length())
13680 {
13681 int vrc = validateFlags(aFlags.c_str(), &fFlags);
13682 AssertRCReturn(vrc, E_INVALIDARG);
13683 }
13684
13685 /*
13686 * Now grab the object lock, validate the state and do the update.
13687 */
13688
13689 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13690
13691 if (!Global::IsOnline(mData->mMachineState))
13692 {
13693 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
13694 VBOX_E_INVALID_VM_STATE);
13695 }
13696
13697 i_setModified(IsModified_MachineData);
13698 mHWData.backup();
13699
13700 bool fDelete = !aValue.length();
13701 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
13702 if (it != mHWData->mGuestProperties.end())
13703 {
13704 if (!fDelete)
13705 {
13706 it->second.strValue = aValue;
13707 it->second.mTimestamp = aTimestamp;
13708 it->second.mFlags = fFlags;
13709 }
13710 else
13711 mHWData->mGuestProperties.erase(it);
13712
13713 mData->mGuestPropertiesModified = TRUE;
13714 }
13715 else if (!fDelete)
13716 {
13717 HWData::GuestProperty prop;
13718 prop.strValue = aValue;
13719 prop.mTimestamp = aTimestamp;
13720 prop.mFlags = fFlags;
13721
13722 mHWData->mGuestProperties[aName] = prop;
13723 mData->mGuestPropertiesModified = TRUE;
13724 }
13725
13726 alock.release();
13727
13728 mParent->i_onGuestPropertyChange(mData->mUuid,
13729 Bstr(aName).raw(),
13730 Bstr(aValue).raw(),
13731 Bstr(aFlags).raw());
13732 }
13733 catch (...)
13734 {
13735 return VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
13736 }
13737 return S_OK;
13738#else
13739 ReturnComNotImplemented();
13740#endif
13741}
13742
13743
13744HRESULT SessionMachine::lockMedia()
13745{
13746 AutoMultiWriteLock2 alock(this->lockHandle(),
13747 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13748
13749 AssertReturn( mData->mMachineState == MachineState_Starting
13750 || mData->mMachineState == MachineState_Restoring
13751 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
13752
13753 clearError();
13754 alock.release();
13755 return i_lockMedia();
13756}
13757
13758HRESULT SessionMachine::unlockMedia()
13759{
13760 HRESULT hrc = i_unlockMedia();
13761 return hrc;
13762}
13763
13764HRESULT SessionMachine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
13765 ComPtr<IMediumAttachment> &aNewAttachment)
13766{
13767 // request the host lock first, since might be calling Host methods for getting host drives;
13768 // next, protect the media tree all the while we're in here, as well as our member variables
13769 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
13770 this->lockHandle(),
13771 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13772
13773 IMediumAttachment *iAttach = aAttachment;
13774 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(iAttach);
13775
13776 Utf8Str ctrlName;
13777 LONG lPort;
13778 LONG lDevice;
13779 bool fTempEject;
13780 {
13781 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13782
13783 /* Need to query the details first, as the IMediumAttachment reference
13784 * might be to the original settings, which we are going to change. */
13785 ctrlName = pAttach->i_getControllerName();
13786 lPort = pAttach->i_getPort();
13787 lDevice = pAttach->i_getDevice();
13788 fTempEject = pAttach->i_getTempEject();
13789 }
13790
13791 if (!fTempEject)
13792 {
13793 /* Remember previously mounted medium. The medium before taking the
13794 * backup is not necessarily the same thing. */
13795 ComObjPtr<Medium> oldmedium;
13796 oldmedium = pAttach->i_getMedium();
13797
13798 i_setModified(IsModified_Storage);
13799 mMediumAttachments.backup();
13800
13801 // The backup operation makes the pAttach reference point to the
13802 // old settings. Re-get the correct reference.
13803 pAttach = i_findAttachment(*mMediumAttachments.data(),
13804 ctrlName,
13805 lPort,
13806 lDevice);
13807
13808 {
13809 AutoCaller autoAttachCaller(this);
13810 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
13811
13812 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13813 if (!oldmedium.isNull())
13814 oldmedium->i_removeBackReference(mData->mUuid);
13815
13816 pAttach->i_updateMedium(NULL);
13817 pAttach->i_updateEjected();
13818 }
13819
13820 i_setModified(IsModified_Storage);
13821 }
13822 else
13823 {
13824 {
13825 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13826 pAttach->i_updateEjected();
13827 }
13828 }
13829
13830 pAttach.queryInterfaceTo(aNewAttachment.asOutParam());
13831
13832 return S_OK;
13833}
13834
13835HRESULT SessionMachine::authenticateExternal(const std::vector<com::Utf8Str> &aAuthParams,
13836 com::Utf8Str &aResult)
13837{
13838 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13839
13840 HRESULT hr = S_OK;
13841
13842 if (!mAuthLibCtx.hAuthLibrary)
13843 {
13844 /* Load the external authentication library. */
13845 Bstr authLibrary;
13846 mVRDEServer->COMGETTER(AuthLibrary)(authLibrary.asOutParam());
13847
13848 Utf8Str filename = authLibrary;
13849
13850 int rc = AuthLibLoad(&mAuthLibCtx, filename.c_str());
13851 if (RT_FAILURE(rc))
13852 {
13853 hr = setError(E_FAIL,
13854 tr("Could not load the external authentication library '%s' (%Rrc)"),
13855 filename.c_str(), rc);
13856 }
13857 }
13858
13859 /* The auth library might need the machine lock. */
13860 alock.release();
13861
13862 if (FAILED(hr))
13863 return hr;
13864
13865 if (aAuthParams[0] == "VRDEAUTH" && aAuthParams.size() == 7)
13866 {
13867 enum VRDEAuthParams
13868 {
13869 parmUuid = 1,
13870 parmGuestJudgement,
13871 parmUser,
13872 parmPassword,
13873 parmDomain,
13874 parmClientId
13875 };
13876
13877 AuthResult result = AuthResultAccessDenied;
13878
13879 Guid uuid(aAuthParams[parmUuid]);
13880 AuthGuestJudgement guestJudgement = (AuthGuestJudgement)aAuthParams[parmGuestJudgement].toUInt32();
13881 uint32_t u32ClientId = aAuthParams[parmClientId].toUInt32();
13882
13883 result = AuthLibAuthenticate(&mAuthLibCtx,
13884 uuid.raw(), guestJudgement,
13885 aAuthParams[parmUser].c_str(),
13886 aAuthParams[parmPassword].c_str(),
13887 aAuthParams[parmDomain].c_str(),
13888 u32ClientId);
13889
13890 /* Hack: aAuthParams[parmPassword] is const but the code believes in writable memory. */
13891 size_t cbPassword = aAuthParams[parmPassword].length();
13892 if (cbPassword)
13893 {
13894 RTMemWipeThoroughly((void *)aAuthParams[parmPassword].c_str(), cbPassword, 10 /* cPasses */);
13895 memset((void *)aAuthParams[parmPassword].c_str(), 'x', cbPassword);
13896 }
13897
13898 if (result == AuthResultAccessGranted)
13899 aResult = "granted";
13900 else
13901 aResult = "denied";
13902
13903 LogRel(("AUTH: VRDE authentification for user '%s' result '%s'\n",
13904 aAuthParams[parmUser].c_str(), aResult.c_str()));
13905 }
13906 else if (aAuthParams[0] == "VRDEAUTHDISCONNECT" && aAuthParams.size() == 3)
13907 {
13908 enum VRDEAuthDisconnectParams
13909 {
13910 parmUuid = 1,
13911 parmClientId
13912 };
13913
13914 Guid uuid(aAuthParams[parmUuid]);
13915 uint32_t u32ClientId = 0;
13916 AuthLibDisconnect(&mAuthLibCtx, uuid.raw(), u32ClientId);
13917 }
13918 else
13919 {
13920 hr = E_INVALIDARG;
13921 }
13922
13923 return hr;
13924}
13925
13926// public methods only for internal purposes
13927/////////////////////////////////////////////////////////////////////////////
13928
13929#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
13930/**
13931 * Called from the client watcher thread to check for expected or unexpected
13932 * death of the client process that has a direct session to this machine.
13933 *
13934 * On Win32 and on OS/2, this method is called only when we've got the
13935 * mutex (i.e. the client has either died or terminated normally) so it always
13936 * returns @c true (the client is terminated, the session machine is
13937 * uninitialized).
13938 *
13939 * On other platforms, the method returns @c true if the client process has
13940 * terminated normally or abnormally and the session machine was uninitialized,
13941 * and @c false if the client process is still alive.
13942 *
13943 * @note Locks this object for writing.
13944 */
13945bool SessionMachine::i_checkForDeath()
13946{
13947 Uninit::Reason reason;
13948 bool terminated = false;
13949
13950 /* Enclose autoCaller with a block because calling uninit() from under it
13951 * will deadlock. */
13952 {
13953 AutoCaller autoCaller(this);
13954 if (!autoCaller.isOk())
13955 {
13956 /* return true if not ready, to cause the client watcher to exclude
13957 * the corresponding session from watching */
13958 LogFlowThisFunc(("Already uninitialized!\n"));
13959 return true;
13960 }
13961
13962 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13963
13964 /* Determine the reason of death: if the session state is Closing here,
13965 * everything is fine. Otherwise it means that the client did not call
13966 * OnSessionEnd() before it released the IPC semaphore. This may happen
13967 * either because the client process has abnormally terminated, or
13968 * because it simply forgot to call ISession::Close() before exiting. We
13969 * threat the latter also as an abnormal termination (see
13970 * Session::uninit() for details). */
13971 reason = mData->mSession.mState == SessionState_Unlocking ?
13972 Uninit::Normal :
13973 Uninit::Abnormal;
13974
13975 if (mClientToken)
13976 terminated = mClientToken->release();
13977 } /* AutoCaller block */
13978
13979 if (terminated)
13980 uninit(reason);
13981
13982 return terminated;
13983}
13984
13985void SessionMachine::i_getTokenId(Utf8Str &strTokenId)
13986{
13987 LogFlowThisFunc(("\n"));
13988
13989 strTokenId.setNull();
13990
13991 AutoCaller autoCaller(this);
13992 AssertComRCReturnVoid(autoCaller.rc());
13993
13994 Assert(mClientToken);
13995 if (mClientToken)
13996 mClientToken->getId(strTokenId);
13997}
13998#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
13999IToken *SessionMachine::i_getToken()
14000{
14001 LogFlowThisFunc(("\n"));
14002
14003 AutoCaller autoCaller(this);
14004 AssertComRCReturn(autoCaller.rc(), NULL);
14005
14006 Assert(mClientToken);
14007 if (mClientToken)
14008 return mClientToken->getToken();
14009 else
14010 return NULL;
14011}
14012#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
14013
14014Machine::ClientToken *SessionMachine::i_getClientToken()
14015{
14016 LogFlowThisFunc(("\n"));
14017
14018 AutoCaller autoCaller(this);
14019 AssertComRCReturn(autoCaller.rc(), NULL);
14020
14021 return mClientToken;
14022}
14023
14024
14025/**
14026 * @note Locks this object for reading.
14027 */
14028HRESULT SessionMachine::i_onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
14029{
14030 LogFlowThisFunc(("\n"));
14031
14032 AutoCaller autoCaller(this);
14033 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14034
14035 ComPtr<IInternalSessionControl> directControl;
14036 {
14037 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14038 if (mData->mSession.mLockType == LockType_VM)
14039 directControl = mData->mSession.mDirectControl;
14040 }
14041
14042 /* ignore notifications sent after #OnSessionEnd() is called */
14043 if (!directControl)
14044 return S_OK;
14045
14046 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
14047}
14048
14049/**
14050 * @note Locks this object for reading.
14051 */
14052HRESULT SessionMachine::i_onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
14053 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort,
14054 IN_BSTR aGuestIp, LONG aGuestPort)
14055{
14056 LogFlowThisFunc(("\n"));
14057
14058 AutoCaller autoCaller(this);
14059 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14060
14061 ComPtr<IInternalSessionControl> directControl;
14062 {
14063 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14064 if (mData->mSession.mLockType == LockType_VM)
14065 directControl = mData->mSession.mDirectControl;
14066 }
14067
14068 /* ignore notifications sent after #OnSessionEnd() is called */
14069 if (!directControl)
14070 return S_OK;
14071 /*
14072 * instead acting like callback we ask IVirtualBox deliver corresponding event
14073 */
14074
14075 mParent->i_onNatRedirectChange(i_getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp,
14076 (uint16_t)aHostPort, aGuestIp, (uint16_t)aGuestPort);
14077 return S_OK;
14078}
14079
14080/**
14081 * @note Locks this object for reading.
14082 */
14083HRESULT SessionMachine::i_onSerialPortChange(ISerialPort *serialPort)
14084{
14085 LogFlowThisFunc(("\n"));
14086
14087 AutoCaller autoCaller(this);
14088 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14089
14090 ComPtr<IInternalSessionControl> directControl;
14091 {
14092 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14093 if (mData->mSession.mLockType == LockType_VM)
14094 directControl = mData->mSession.mDirectControl;
14095 }
14096
14097 /* ignore notifications sent after #OnSessionEnd() is called */
14098 if (!directControl)
14099 return S_OK;
14100
14101 return directControl->OnSerialPortChange(serialPort);
14102}
14103
14104/**
14105 * @note Locks this object for reading.
14106 */
14107HRESULT SessionMachine::i_onParallelPortChange(IParallelPort *parallelPort)
14108{
14109 LogFlowThisFunc(("\n"));
14110
14111 AutoCaller autoCaller(this);
14112 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14113
14114 ComPtr<IInternalSessionControl> directControl;
14115 {
14116 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14117 if (mData->mSession.mLockType == LockType_VM)
14118 directControl = mData->mSession.mDirectControl;
14119 }
14120
14121 /* ignore notifications sent after #OnSessionEnd() is called */
14122 if (!directControl)
14123 return S_OK;
14124
14125 return directControl->OnParallelPortChange(parallelPort);
14126}
14127
14128/**
14129 * @note Locks this object for reading.
14130 */
14131HRESULT SessionMachine::i_onStorageControllerChange()
14132{
14133 LogFlowThisFunc(("\n"));
14134
14135 AutoCaller autoCaller(this);
14136 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14137
14138 ComPtr<IInternalSessionControl> directControl;
14139 {
14140 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14141 if (mData->mSession.mLockType == LockType_VM)
14142 directControl = mData->mSession.mDirectControl;
14143 }
14144
14145 /* ignore notifications sent after #OnSessionEnd() is called */
14146 if (!directControl)
14147 return S_OK;
14148
14149 return directControl->OnStorageControllerChange();
14150}
14151
14152/**
14153 * @note Locks this object for reading.
14154 */
14155HRESULT SessionMachine::i_onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
14156{
14157 LogFlowThisFunc(("\n"));
14158
14159 AutoCaller autoCaller(this);
14160 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14161
14162 ComPtr<IInternalSessionControl> directControl;
14163 {
14164 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14165 if (mData->mSession.mLockType == LockType_VM)
14166 directControl = mData->mSession.mDirectControl;
14167 }
14168
14169 /* ignore notifications sent after #OnSessionEnd() is called */
14170 if (!directControl)
14171 return S_OK;
14172
14173 return directControl->OnMediumChange(aAttachment, aForce);
14174}
14175
14176/**
14177 * @note Locks this object for reading.
14178 */
14179HRESULT SessionMachine::i_onCPUChange(ULONG aCPU, BOOL aRemove)
14180{
14181 LogFlowThisFunc(("\n"));
14182
14183 AutoCaller autoCaller(this);
14184 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14185
14186 ComPtr<IInternalSessionControl> directControl;
14187 {
14188 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14189 if (mData->mSession.mLockType == LockType_VM)
14190 directControl = mData->mSession.mDirectControl;
14191 }
14192
14193 /* ignore notifications sent after #OnSessionEnd() is called */
14194 if (!directControl)
14195 return S_OK;
14196
14197 return directControl->OnCPUChange(aCPU, aRemove);
14198}
14199
14200HRESULT SessionMachine::i_onCPUExecutionCapChange(ULONG aExecutionCap)
14201{
14202 LogFlowThisFunc(("\n"));
14203
14204 AutoCaller autoCaller(this);
14205 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14206
14207 ComPtr<IInternalSessionControl> directControl;
14208 {
14209 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14210 if (mData->mSession.mLockType == LockType_VM)
14211 directControl = mData->mSession.mDirectControl;
14212 }
14213
14214 /* ignore notifications sent after #OnSessionEnd() is called */
14215 if (!directControl)
14216 return S_OK;
14217
14218 return directControl->OnCPUExecutionCapChange(aExecutionCap);
14219}
14220
14221/**
14222 * @note Locks this object for reading.
14223 */
14224HRESULT SessionMachine::i_onVRDEServerChange(BOOL aRestart)
14225{
14226 LogFlowThisFunc(("\n"));
14227
14228 AutoCaller autoCaller(this);
14229 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14230
14231 ComPtr<IInternalSessionControl> directControl;
14232 {
14233 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14234 if (mData->mSession.mLockType == LockType_VM)
14235 directControl = mData->mSession.mDirectControl;
14236 }
14237
14238 /* ignore notifications sent after #OnSessionEnd() is called */
14239 if (!directControl)
14240 return S_OK;
14241
14242 return directControl->OnVRDEServerChange(aRestart);
14243}
14244
14245/**
14246 * @note Locks this object for reading.
14247 */
14248HRESULT SessionMachine::i_onVideoCaptureChange()
14249{
14250 LogFlowThisFunc(("\n"));
14251
14252 AutoCaller autoCaller(this);
14253 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14254
14255 ComPtr<IInternalSessionControl> directControl;
14256 {
14257 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14258 if (mData->mSession.mLockType == LockType_VM)
14259 directControl = mData->mSession.mDirectControl;
14260 }
14261
14262 /* ignore notifications sent after #OnSessionEnd() is called */
14263 if (!directControl)
14264 return S_OK;
14265
14266 return directControl->OnVideoCaptureChange();
14267}
14268
14269/**
14270 * @note Locks this object for reading.
14271 */
14272HRESULT SessionMachine::i_onUSBControllerChange()
14273{
14274 LogFlowThisFunc(("\n"));
14275
14276 AutoCaller autoCaller(this);
14277 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14278
14279 ComPtr<IInternalSessionControl> directControl;
14280 {
14281 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14282 if (mData->mSession.mLockType == LockType_VM)
14283 directControl = mData->mSession.mDirectControl;
14284 }
14285
14286 /* ignore notifications sent after #OnSessionEnd() is called */
14287 if (!directControl)
14288 return S_OK;
14289
14290 return directControl->OnUSBControllerChange();
14291}
14292
14293/**
14294 * @note Locks this object for reading.
14295 */
14296HRESULT SessionMachine::i_onSharedFolderChange()
14297{
14298 LogFlowThisFunc(("\n"));
14299
14300 AutoCaller autoCaller(this);
14301 AssertComRCReturnRC(autoCaller.rc());
14302
14303 ComPtr<IInternalSessionControl> directControl;
14304 {
14305 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14306 if (mData->mSession.mLockType == LockType_VM)
14307 directControl = mData->mSession.mDirectControl;
14308 }
14309
14310 /* ignore notifications sent after #OnSessionEnd() is called */
14311 if (!directControl)
14312 return S_OK;
14313
14314 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
14315}
14316
14317/**
14318 * @note Locks this object for reading.
14319 */
14320HRESULT SessionMachine::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
14321{
14322 LogFlowThisFunc(("\n"));
14323
14324 AutoCaller autoCaller(this);
14325 AssertComRCReturnRC(autoCaller.rc());
14326
14327 ComPtr<IInternalSessionControl> directControl;
14328 {
14329 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14330 if (mData->mSession.mLockType == LockType_VM)
14331 directControl = mData->mSession.mDirectControl;
14332 }
14333
14334 /* ignore notifications sent after #OnSessionEnd() is called */
14335 if (!directControl)
14336 return S_OK;
14337
14338 return directControl->OnClipboardModeChange(aClipboardMode);
14339}
14340
14341/**
14342 * @note Locks this object for reading.
14343 */
14344HRESULT SessionMachine::i_onDnDModeChange(DnDMode_T aDnDMode)
14345{
14346 LogFlowThisFunc(("\n"));
14347
14348 AutoCaller autoCaller(this);
14349 AssertComRCReturnRC(autoCaller.rc());
14350
14351 ComPtr<IInternalSessionControl> directControl;
14352 {
14353 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14354 if (mData->mSession.mLockType == LockType_VM)
14355 directControl = mData->mSession.mDirectControl;
14356 }
14357
14358 /* ignore notifications sent after #OnSessionEnd() is called */
14359 if (!directControl)
14360 return S_OK;
14361
14362 return directControl->OnDnDModeChange(aDnDMode);
14363}
14364
14365/**
14366 * @note Locks this object for reading.
14367 */
14368HRESULT SessionMachine::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
14369{
14370 LogFlowThisFunc(("\n"));
14371
14372 AutoCaller autoCaller(this);
14373 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14374
14375 ComPtr<IInternalSessionControl> directControl;
14376 {
14377 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14378 if (mData->mSession.mLockType == LockType_VM)
14379 directControl = mData->mSession.mDirectControl;
14380 }
14381
14382 /* ignore notifications sent after #OnSessionEnd() is called */
14383 if (!directControl)
14384 return S_OK;
14385
14386 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
14387}
14388
14389/**
14390 * @note Locks this object for reading.
14391 */
14392HRESULT SessionMachine::i_onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove, BOOL aSilent)
14393{
14394 LogFlowThisFunc(("\n"));
14395
14396 AutoCaller autoCaller(this);
14397 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14398
14399 ComPtr<IInternalSessionControl> directControl;
14400 {
14401 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14402 if (mData->mSession.mLockType == LockType_VM)
14403 directControl = mData->mSession.mDirectControl;
14404 }
14405
14406 /* ignore notifications sent after #OnSessionEnd() is called */
14407 if (!directControl)
14408 return S_OK;
14409
14410 return directControl->OnStorageDeviceChange(aAttachment, aRemove, aSilent);
14411}
14412
14413/**
14414 * Returns @c true if this machine's USB controller reports it has a matching
14415 * filter for the given USB device and @c false otherwise.
14416 *
14417 * @note locks this object for reading.
14418 */
14419bool SessionMachine::i_hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
14420{
14421 AutoCaller autoCaller(this);
14422 /* silently return if not ready -- this method may be called after the
14423 * direct machine session has been called */
14424 if (!autoCaller.isOk())
14425 return false;
14426
14427#ifdef VBOX_WITH_USB
14428 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14429
14430 switch (mData->mMachineState)
14431 {
14432 case MachineState_Starting:
14433 case MachineState_Restoring:
14434 case MachineState_TeleportingIn:
14435 case MachineState_Paused:
14436 case MachineState_Running:
14437 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
14438 * elsewhere... */
14439 alock.release();
14440 return mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedIfs);
14441 default: break;
14442 }
14443#else
14444 NOREF(aDevice);
14445 NOREF(aMaskedIfs);
14446#endif
14447 return false;
14448}
14449
14450/**
14451 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14452 */
14453HRESULT SessionMachine::i_onUSBDeviceAttach(IUSBDevice *aDevice,
14454 IVirtualBoxErrorInfo *aError,
14455 ULONG aMaskedIfs,
14456 const com::Utf8Str &aCaptureFilename)
14457{
14458 LogFlowThisFunc(("\n"));
14459
14460 AutoCaller autoCaller(this);
14461
14462 /* This notification may happen after the machine object has been
14463 * uninitialized (the session was closed), so don't assert. */
14464 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14465
14466 ComPtr<IInternalSessionControl> directControl;
14467 {
14468 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14469 if (mData->mSession.mLockType == LockType_VM)
14470 directControl = mData->mSession.mDirectControl;
14471 }
14472
14473 /* fail on notifications sent after #OnSessionEnd() is called, it is
14474 * expected by the caller */
14475 if (!directControl)
14476 return E_FAIL;
14477
14478 /* No locks should be held at this point. */
14479 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14480 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14481
14482 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs, Bstr(aCaptureFilename).raw());
14483}
14484
14485/**
14486 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14487 */
14488HRESULT SessionMachine::i_onUSBDeviceDetach(IN_BSTR aId,
14489 IVirtualBoxErrorInfo *aError)
14490{
14491 LogFlowThisFunc(("\n"));
14492
14493 AutoCaller autoCaller(this);
14494
14495 /* This notification may happen after the machine object has been
14496 * uninitialized (the session was closed), so don't assert. */
14497 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14498
14499 ComPtr<IInternalSessionControl> directControl;
14500 {
14501 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14502 if (mData->mSession.mLockType == LockType_VM)
14503 directControl = mData->mSession.mDirectControl;
14504 }
14505
14506 /* fail on notifications sent after #OnSessionEnd() is called, it is
14507 * expected by the caller */
14508 if (!directControl)
14509 return E_FAIL;
14510
14511 /* No locks should be held at this point. */
14512 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14513 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14514
14515 return directControl->OnUSBDeviceDetach(aId, aError);
14516}
14517
14518// protected methods
14519/////////////////////////////////////////////////////////////////////////////
14520
14521/**
14522 * Deletes the given file if it is no longer in use by either the current machine state
14523 * (if the machine is "saved") or any of the machine's snapshots.
14524 *
14525 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
14526 * but is different for each SnapshotMachine. When calling this, the order of calling this
14527 * function on the one hand and changing that variable OR the snapshots tree on the other hand
14528 * is therefore critical. I know, it's all rather messy.
14529 *
14530 * @param strStateFile
14531 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in
14532 * the test for whether the saved state file is in use.
14533 */
14534void SessionMachine::i_releaseSavedStateFile(const Utf8Str &strStateFile,
14535 Snapshot *pSnapshotToIgnore)
14536{
14537 // it is safe to delete this saved state file if it is not currently in use by the machine ...
14538 if ( (strStateFile.isNotEmpty())
14539 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
14540 )
14541 // ... and it must also not be shared with other snapshots
14542 if ( !mData->mFirstSnapshot
14543 || !mData->mFirstSnapshot->i_sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
14544 // this checks the SnapshotMachine's state file paths
14545 )
14546 RTFileDelete(strStateFile.c_str());
14547}
14548
14549/**
14550 * Locks the attached media.
14551 *
14552 * All attached hard disks are locked for writing and DVD/floppy are locked for
14553 * reading. Parents of attached hard disks (if any) are locked for reading.
14554 *
14555 * This method also performs accessibility check of all media it locks: if some
14556 * media is inaccessible, the method will return a failure and a bunch of
14557 * extended error info objects per each inaccessible medium.
14558 *
14559 * Note that this method is atomic: if it returns a success, all media are
14560 * locked as described above; on failure no media is locked at all (all
14561 * succeeded individual locks will be undone).
14562 *
14563 * The caller is responsible for doing the necessary state sanity checks.
14564 *
14565 * The locks made by this method must be undone by calling #unlockMedia() when
14566 * no more needed.
14567 */
14568HRESULT SessionMachine::i_lockMedia()
14569{
14570 AutoCaller autoCaller(this);
14571 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14572
14573 AutoMultiWriteLock2 alock(this->lockHandle(),
14574 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
14575
14576 /* bail out if trying to lock things with already set up locking */
14577 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
14578
14579 MultiResult mrc(S_OK);
14580
14581 /* Collect locking information for all medium objects attached to the VM. */
14582 for (MediumAttachmentList::const_iterator
14583 it = mMediumAttachments->begin();
14584 it != mMediumAttachments->end();
14585 ++it)
14586 {
14587 MediumAttachment *pAtt = *it;
14588 DeviceType_T devType = pAtt->i_getType();
14589 Medium *pMedium = pAtt->i_getMedium();
14590
14591 MediumLockList *pMediumLockList(new MediumLockList());
14592 // There can be attachments without a medium (floppy/dvd), and thus
14593 // it's impossible to create a medium lock list. It still makes sense
14594 // to have the empty medium lock list in the map in case a medium is
14595 // attached later.
14596 if (pMedium != NULL)
14597 {
14598 MediumType_T mediumType = pMedium->i_getType();
14599 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
14600 || mediumType == MediumType_Shareable;
14601 bool fIsVitalImage = (devType == DeviceType_HardDisk);
14602
14603 alock.release();
14604 mrc = pMedium->i_createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
14605 !fIsReadOnlyLock ? pMedium : NULL /* pToLockWrite */,
14606 false /* fMediumLockWriteAll */,
14607 NULL,
14608 *pMediumLockList);
14609 alock.acquire();
14610 if (FAILED(mrc))
14611 {
14612 delete pMediumLockList;
14613 mData->mSession.mLockedMedia.Clear();
14614 break;
14615 }
14616 }
14617
14618 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
14619 if (FAILED(rc))
14620 {
14621 mData->mSession.mLockedMedia.Clear();
14622 mrc = setError(rc,
14623 tr("Collecting locking information for all attached media failed"));
14624 break;
14625 }
14626 }
14627
14628 if (SUCCEEDED(mrc))
14629 {
14630 /* Now lock all media. If this fails, nothing is locked. */
14631 alock.release();
14632 HRESULT rc = mData->mSession.mLockedMedia.Lock();
14633 alock.acquire();
14634 if (FAILED(rc))
14635 {
14636 mrc = setError(rc,
14637 tr("Locking of attached media failed. A possible reason is that one of the media is attached to a running VM"));
14638 }
14639 }
14640
14641 return mrc;
14642}
14643
14644/**
14645 * Undoes the locks made by by #lockMedia().
14646 */
14647HRESULT SessionMachine::i_unlockMedia()
14648{
14649 AutoCaller autoCaller(this);
14650 AssertComRCReturn(autoCaller.rc(),autoCaller.rc());
14651
14652 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14653
14654 /* we may be holding important error info on the current thread;
14655 * preserve it */
14656 ErrorInfoKeeper eik;
14657
14658 HRESULT rc = mData->mSession.mLockedMedia.Clear();
14659 AssertComRC(rc);
14660 return rc;
14661}
14662
14663/**
14664 * Helper to change the machine state (reimplementation).
14665 *
14666 * @note Locks this object for writing.
14667 * @note This method must not call i_saveSettings or SaveSettings, otherwise
14668 * it can cause crashes in random places due to unexpectedly committing
14669 * the current settings. The caller is responsible for that. The call
14670 * to saveStateSettings is fine, because this method does not commit.
14671 */
14672HRESULT SessionMachine::i_setMachineState(MachineState_T aMachineState)
14673{
14674 LogFlowThisFuncEnter();
14675 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
14676
14677 AutoCaller autoCaller(this);
14678 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14679
14680 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14681
14682 MachineState_T oldMachineState = mData->mMachineState;
14683
14684 AssertMsgReturn(oldMachineState != aMachineState,
14685 ("oldMachineState=%s, aMachineState=%s\n",
14686 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
14687 E_FAIL);
14688
14689 HRESULT rc = S_OK;
14690
14691 int stsFlags = 0;
14692 bool deleteSavedState = false;
14693
14694 /* detect some state transitions */
14695
14696 if ( ( oldMachineState == MachineState_Saved
14697 && aMachineState == MachineState_Restoring)
14698 || ( ( oldMachineState == MachineState_PoweredOff
14699 || oldMachineState == MachineState_Teleported
14700 || oldMachineState == MachineState_Aborted
14701 )
14702 && ( aMachineState == MachineState_TeleportingIn
14703 || aMachineState == MachineState_Starting
14704 )
14705 )
14706 )
14707 {
14708 /* The EMT thread is about to start */
14709
14710 /* Nothing to do here for now... */
14711
14712 /// @todo NEWMEDIA don't let mDVDDrive and other children
14713 /// change anything when in the Starting/Restoring state
14714 }
14715 else if ( ( oldMachineState == MachineState_Running
14716 || oldMachineState == MachineState_Paused
14717 || oldMachineState == MachineState_Teleporting
14718 || oldMachineState == MachineState_OnlineSnapshotting
14719 || oldMachineState == MachineState_LiveSnapshotting
14720 || oldMachineState == MachineState_Stuck
14721 || oldMachineState == MachineState_Starting
14722 || oldMachineState == MachineState_Stopping
14723 || oldMachineState == MachineState_Saving
14724 || oldMachineState == MachineState_Restoring
14725 || oldMachineState == MachineState_TeleportingPausedVM
14726 || oldMachineState == MachineState_TeleportingIn
14727 )
14728 && ( aMachineState == MachineState_PoweredOff
14729 || aMachineState == MachineState_Saved
14730 || aMachineState == MachineState_Teleported
14731 || aMachineState == MachineState_Aborted
14732 )
14733 )
14734 {
14735 /* The EMT thread has just stopped, unlock attached media. Note that as
14736 * opposed to locking that is done from Console, we do unlocking here
14737 * because the VM process may have aborted before having a chance to
14738 * properly unlock all media it locked. */
14739
14740 unlockMedia();
14741 }
14742
14743 if (oldMachineState == MachineState_Restoring)
14744 {
14745 if (aMachineState != MachineState_Saved)
14746 {
14747 /*
14748 * delete the saved state file once the machine has finished
14749 * restoring from it (note that Console sets the state from
14750 * Restoring to Saved if the VM couldn't restore successfully,
14751 * to give the user an ability to fix an error and retry --
14752 * we keep the saved state file in this case)
14753 */
14754 deleteSavedState = true;
14755 }
14756 }
14757 else if ( oldMachineState == MachineState_Saved
14758 && ( aMachineState == MachineState_PoweredOff
14759 || aMachineState == MachineState_Aborted
14760 || aMachineState == MachineState_Teleported
14761 )
14762 )
14763 {
14764 /*
14765 * delete the saved state after SessionMachine::ForgetSavedState() is called
14766 * or if the VM process (owning a direct VM session) crashed while the
14767 * VM was Saved
14768 */
14769
14770 /// @todo (dmik)
14771 // Not sure that deleting the saved state file just because of the
14772 // client death before it attempted to restore the VM is a good
14773 // thing. But when it crashes we need to go to the Aborted state
14774 // which cannot have the saved state file associated... The only
14775 // way to fix this is to make the Aborted condition not a VM state
14776 // but a bool flag: i.e., when a crash occurs, set it to true and
14777 // change the state to PoweredOff or Saved depending on the
14778 // saved state presence.
14779
14780 deleteSavedState = true;
14781 mData->mCurrentStateModified = TRUE;
14782 stsFlags |= SaveSTS_CurStateModified;
14783 }
14784
14785 if ( aMachineState == MachineState_Starting
14786 || aMachineState == MachineState_Restoring
14787 || aMachineState == MachineState_TeleportingIn
14788 )
14789 {
14790 /* set the current state modified flag to indicate that the current
14791 * state is no more identical to the state in the
14792 * current snapshot */
14793 if (!mData->mCurrentSnapshot.isNull())
14794 {
14795 mData->mCurrentStateModified = TRUE;
14796 stsFlags |= SaveSTS_CurStateModified;
14797 }
14798 }
14799
14800 if (deleteSavedState)
14801 {
14802 if (mRemoveSavedState)
14803 {
14804 Assert(!mSSData->strStateFilePath.isEmpty());
14805
14806 // it is safe to delete the saved state file if ...
14807 if ( !mData->mFirstSnapshot // ... we have no snapshots or
14808 || !mData->mFirstSnapshot->i_sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
14809 // ... none of the snapshots share the saved state file
14810 )
14811 RTFileDelete(mSSData->strStateFilePath.c_str());
14812 }
14813
14814 mSSData->strStateFilePath.setNull();
14815 stsFlags |= SaveSTS_StateFilePath;
14816 }
14817
14818 /* redirect to the underlying peer machine */
14819 mPeer->i_setMachineState(aMachineState);
14820
14821 if ( oldMachineState != MachineState_RestoringSnapshot
14822 && ( aMachineState == MachineState_PoweredOff
14823 || aMachineState == MachineState_Teleported
14824 || aMachineState == MachineState_Aborted
14825 || aMachineState == MachineState_Saved))
14826 {
14827 /* the machine has stopped execution
14828 * (or the saved state file was adopted) */
14829 stsFlags |= SaveSTS_StateTimeStamp;
14830 }
14831
14832 if ( ( oldMachineState == MachineState_PoweredOff
14833 || oldMachineState == MachineState_Aborted
14834 || oldMachineState == MachineState_Teleported
14835 )
14836 && aMachineState == MachineState_Saved)
14837 {
14838 /* the saved state file was adopted */
14839 Assert(!mSSData->strStateFilePath.isEmpty());
14840 stsFlags |= SaveSTS_StateFilePath;
14841 }
14842
14843#ifdef VBOX_WITH_GUEST_PROPS
14844 if ( aMachineState == MachineState_PoweredOff
14845 || aMachineState == MachineState_Aborted
14846 || aMachineState == MachineState_Teleported)
14847 {
14848 /* Make sure any transient guest properties get removed from the
14849 * property store on shutdown. */
14850 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
14851
14852 /* remove it from the settings representation */
14853 settings::GuestPropertiesList &llGuestProperties = mData->pMachineConfigFile->hardwareMachine.llGuestProperties;
14854 for (settings::GuestPropertiesList::iterator
14855 it = llGuestProperties.begin();
14856 it != llGuestProperties.end();
14857 /*nothing*/)
14858 {
14859 const settings::GuestProperty &prop = *it;
14860 if ( prop.strFlags.contains("TRANSRESET", Utf8Str::CaseInsensitive)
14861 || prop.strFlags.contains("TRANSIENT", Utf8Str::CaseInsensitive))
14862 {
14863 it = llGuestProperties.erase(it);
14864 fNeedsSaving = true;
14865 }
14866 else
14867 {
14868 ++it;
14869 }
14870 }
14871
14872 /* Additionally remove it from the HWData representation. Required to
14873 * keep everything in sync, as this is what the API keeps using. */
14874 HWData::GuestPropertyMap &llHWGuestProperties = mHWData->mGuestProperties;
14875 for (HWData::GuestPropertyMap::iterator
14876 it = llHWGuestProperties.begin();
14877 it != llHWGuestProperties.end();
14878 /*nothing*/)
14879 {
14880 uint32_t fFlags = it->second.mFlags;
14881 if ( fFlags & guestProp::TRANSIENT
14882 || fFlags & guestProp::TRANSRESET)
14883 {
14884 /* iterator where we need to continue after the erase call
14885 * (C++03 is a fact still, and it doesn't return the iterator
14886 * which would allow continuing) */
14887 HWData::GuestPropertyMap::iterator it2 = it;
14888 ++it2;
14889 llHWGuestProperties.erase(it);
14890 it = it2;
14891 fNeedsSaving = true;
14892 }
14893 else
14894 {
14895 ++it;
14896 }
14897 }
14898
14899 if (fNeedsSaving)
14900 {
14901 mData->mCurrentStateModified = TRUE;
14902 stsFlags |= SaveSTS_CurStateModified;
14903 }
14904 }
14905#endif /* VBOX_WITH_GUEST_PROPS */
14906
14907 rc = i_saveStateSettings(stsFlags);
14908
14909 if ( ( oldMachineState != MachineState_PoweredOff
14910 && oldMachineState != MachineState_Aborted
14911 && oldMachineState != MachineState_Teleported
14912 )
14913 && ( aMachineState == MachineState_PoweredOff
14914 || aMachineState == MachineState_Aborted
14915 || aMachineState == MachineState_Teleported
14916 )
14917 )
14918 {
14919 /* we've been shut down for any reason */
14920 /* no special action so far */
14921 }
14922
14923 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
14924 LogFlowThisFuncLeave();
14925 return rc;
14926}
14927
14928/**
14929 * Sends the current machine state value to the VM process.
14930 *
14931 * @note Locks this object for reading, then calls a client process.
14932 */
14933HRESULT SessionMachine::i_updateMachineStateOnClient()
14934{
14935 AutoCaller autoCaller(this);
14936 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14937
14938 ComPtr<IInternalSessionControl> directControl;
14939 {
14940 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14941 AssertReturn(!!mData, E_FAIL);
14942 if (mData->mSession.mLockType == LockType_VM)
14943 directControl = mData->mSession.mDirectControl;
14944
14945 /* directControl may be already set to NULL here in #OnSessionEnd()
14946 * called too early by the direct session process while there is still
14947 * some operation (like deleting the snapshot) in progress. The client
14948 * process in this case is waiting inside Session::close() for the
14949 * "end session" process object to complete, while #uninit() called by
14950 * #i_checkForDeath() on the Watcher thread is waiting for the pending
14951 * operation to complete. For now, we accept this inconsistent behavior
14952 * and simply do nothing here. */
14953
14954 if (mData->mSession.mState == SessionState_Unlocking)
14955 return S_OK;
14956 }
14957
14958 /* ignore notifications sent after #OnSessionEnd() is called */
14959 if (!directControl)
14960 return S_OK;
14961
14962 return directControl->UpdateMachineState(mData->mMachineState);
14963}
14964
14965
14966/*static*/
14967HRESULT Machine::i_setErrorStatic(HRESULT aResultCode, const char *pcszMsg, ...)
14968{
14969 va_list args;
14970 va_start(args, pcszMsg);
14971 HRESULT rc = setErrorInternal(aResultCode,
14972 getStaticClassIID(),
14973 getStaticComponentName(),
14974 Utf8Str(pcszMsg, args),
14975 false /* aWarning */,
14976 true /* aLogIt */);
14977 va_end(args);
14978 return rc;
14979}
14980
14981
14982HRESULT Machine::updateState(MachineState_T aState)
14983{
14984 NOREF(aState);
14985 ReturnComNotImplemented();
14986}
14987
14988HRESULT Machine::beginPowerUp(const ComPtr<IProgress> &aProgress)
14989{
14990 NOREF(aProgress);
14991 ReturnComNotImplemented();
14992}
14993
14994HRESULT Machine::endPowerUp(LONG aResult)
14995{
14996 NOREF(aResult);
14997 ReturnComNotImplemented();
14998}
14999
15000HRESULT Machine::beginPoweringDown(ComPtr<IProgress> &aProgress)
15001{
15002 NOREF(aProgress);
15003 ReturnComNotImplemented();
15004}
15005
15006HRESULT Machine::endPoweringDown(LONG aResult,
15007 const com::Utf8Str &aErrMsg)
15008{
15009 NOREF(aResult);
15010 NOREF(aErrMsg);
15011 ReturnComNotImplemented();
15012}
15013
15014HRESULT Machine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
15015 BOOL *aMatched,
15016 ULONG *aMaskedInterfaces)
15017{
15018 NOREF(aDevice);
15019 NOREF(aMatched);
15020 NOREF(aMaskedInterfaces);
15021 ReturnComNotImplemented();
15022
15023}
15024
15025HRESULT Machine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
15026{
15027 NOREF(aId); NOREF(aCaptureFilename);
15028 ReturnComNotImplemented();
15029}
15030
15031HRESULT Machine::detachUSBDevice(const com::Guid &aId,
15032 BOOL aDone)
15033{
15034 NOREF(aId);
15035 NOREF(aDone);
15036 ReturnComNotImplemented();
15037}
15038
15039HRESULT Machine::autoCaptureUSBDevices()
15040{
15041 ReturnComNotImplemented();
15042}
15043
15044HRESULT Machine::detachAllUSBDevices(BOOL aDone)
15045{
15046 NOREF(aDone);
15047 ReturnComNotImplemented();
15048}
15049
15050HRESULT Machine::onSessionEnd(const ComPtr<ISession> &aSession,
15051 ComPtr<IProgress> &aProgress)
15052{
15053 NOREF(aSession);
15054 NOREF(aProgress);
15055 ReturnComNotImplemented();
15056}
15057
15058HRESULT Machine::finishOnlineMergeMedium()
15059{
15060 ReturnComNotImplemented();
15061}
15062
15063HRESULT Machine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
15064 std::vector<com::Utf8Str> &aValues,
15065 std::vector<LONG64> &aTimestamps,
15066 std::vector<com::Utf8Str> &aFlags)
15067{
15068 NOREF(aNames);
15069 NOREF(aValues);
15070 NOREF(aTimestamps);
15071 NOREF(aFlags);
15072 ReturnComNotImplemented();
15073}
15074
15075HRESULT Machine::pushGuestProperty(const com::Utf8Str &aName,
15076 const com::Utf8Str &aValue,
15077 LONG64 aTimestamp,
15078 const com::Utf8Str &aFlags)
15079{
15080 NOREF(aName);
15081 NOREF(aValue);
15082 NOREF(aTimestamp);
15083 NOREF(aFlags);
15084 ReturnComNotImplemented();
15085}
15086
15087HRESULT Machine::lockMedia()
15088{
15089 ReturnComNotImplemented();
15090}
15091
15092HRESULT Machine::unlockMedia()
15093{
15094 ReturnComNotImplemented();
15095}
15096
15097HRESULT Machine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
15098 ComPtr<IMediumAttachment> &aNewAttachment)
15099{
15100 NOREF(aAttachment);
15101 NOREF(aNewAttachment);
15102 ReturnComNotImplemented();
15103}
15104
15105HRESULT Machine::reportVmStatistics(ULONG aValidStats,
15106 ULONG aCpuUser,
15107 ULONG aCpuKernel,
15108 ULONG aCpuIdle,
15109 ULONG aMemTotal,
15110 ULONG aMemFree,
15111 ULONG aMemBalloon,
15112 ULONG aMemShared,
15113 ULONG aMemCache,
15114 ULONG aPagedTotal,
15115 ULONG aMemAllocTotal,
15116 ULONG aMemFreeTotal,
15117 ULONG aMemBalloonTotal,
15118 ULONG aMemSharedTotal,
15119 ULONG aVmNetRx,
15120 ULONG aVmNetTx)
15121{
15122 NOREF(aValidStats);
15123 NOREF(aCpuUser);
15124 NOREF(aCpuKernel);
15125 NOREF(aCpuIdle);
15126 NOREF(aMemTotal);
15127 NOREF(aMemFree);
15128 NOREF(aMemBalloon);
15129 NOREF(aMemShared);
15130 NOREF(aMemCache);
15131 NOREF(aPagedTotal);
15132 NOREF(aMemAllocTotal);
15133 NOREF(aMemFreeTotal);
15134 NOREF(aMemBalloonTotal);
15135 NOREF(aMemSharedTotal);
15136 NOREF(aVmNetRx);
15137 NOREF(aVmNetTx);
15138 ReturnComNotImplemented();
15139}
15140
15141HRESULT Machine::authenticateExternal(const std::vector<com::Utf8Str> &aAuthParams,
15142 com::Utf8Str &aResult)
15143{
15144 NOREF(aAuthParams);
15145 NOREF(aResult);
15146 ReturnComNotImplemented();
15147}
15148
15149HRESULT Machine::applyDefaults(const com::Utf8Str &aFlags)
15150{
15151 NOREF(aFlags);
15152 ReturnComNotImplemented();
15153}
15154
15155/* This isn't handled entirely by the wrapper generator yet. */
15156#ifdef VBOX_WITH_XPCOM
15157NS_DECL_CLASSINFO(SessionMachine)
15158NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
15159
15160NS_DECL_CLASSINFO(SnapshotMachine)
15161NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
15162#endif
Note: See TracBrowser for help on using the repository browser.

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