VirtualBox

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

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

build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 518.9 KB
Line 
1/* $Id: MachineImpl.cpp 66945 2017-05-17 18:56:31Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2004-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/* Make sure all the stdint.h macros are included - must come first! */
19#ifndef __STDC_LIMIT_MACROS
20# define __STDC_LIMIT_MACROS
21#endif
22#ifndef __STDC_CONSTANT_MACROS
23# define __STDC_CONSTANT_MACROS
24#endif
25
26#include "Logging.h"
27#include "VirtualBoxImpl.h"
28#include "MachineImpl.h"
29#include "ClientToken.h"
30#include "ProgressImpl.h"
31#include "ProgressProxyImpl.h"
32#include "MediumAttachmentImpl.h"
33#include "MediumImpl.h"
34#include "MediumLock.h"
35#include "USBControllerImpl.h"
36#include "USBDeviceFiltersImpl.h"
37#include "HostImpl.h"
38#include "SharedFolderImpl.h"
39#include "GuestOSTypeImpl.h"
40#include "VirtualBoxErrorInfoImpl.h"
41#include "StorageControllerImpl.h"
42#include "DisplayImpl.h"
43#include "DisplayUtils.h"
44#include "MachineImplCloneVM.h"
45#include "AutostartDb.h"
46#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 = "2"; /** @todo get the default from the schema if that is possible. */
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)
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 unconst(mUnattended).createObject();
8427 mUnattended->init(this);
8428#endif
8429
8430 return S_OK;
8431}
8432
8433/**
8434 * Helper to uninitialize all associated child objects and to free all data
8435 * structures.
8436 *
8437 * This method must be called as a part of the object's uninitialization
8438 * procedure (usually done in the #uninit() method).
8439 *
8440 * @note Must be called only from #uninit() or from #i_registeredInit().
8441 */
8442void Machine::uninitDataAndChildObjects()
8443{
8444 AutoCaller autoCaller(this);
8445 AssertComRCReturnVoid(autoCaller.rc());
8446 AssertComRCReturnVoid( getObjectState().getState() == ObjectState::InUninit
8447 || getObjectState().getState() == ObjectState::Limited);
8448
8449 /* tell all our other child objects we've been uninitialized */
8450 if (mBandwidthControl)
8451 {
8452 mBandwidthControl->uninit();
8453 unconst(mBandwidthControl).setNull();
8454 }
8455
8456 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8457 {
8458 if (mNetworkAdapters[slot])
8459 {
8460 mNetworkAdapters[slot]->uninit();
8461 unconst(mNetworkAdapters[slot]).setNull();
8462 }
8463 }
8464
8465 if (mUSBDeviceFilters)
8466 {
8467 mUSBDeviceFilters->uninit();
8468 unconst(mUSBDeviceFilters).setNull();
8469 }
8470
8471 if (mAudioAdapter)
8472 {
8473 mAudioAdapter->uninit();
8474 unconst(mAudioAdapter).setNull();
8475 }
8476
8477 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8478 {
8479 if (mParallelPorts[slot])
8480 {
8481 mParallelPorts[slot]->uninit();
8482 unconst(mParallelPorts[slot]).setNull();
8483 }
8484 }
8485
8486 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8487 {
8488 if (mSerialPorts[slot])
8489 {
8490 mSerialPorts[slot]->uninit();
8491 unconst(mSerialPorts[slot]).setNull();
8492 }
8493 }
8494
8495 if (mVRDEServer)
8496 {
8497 mVRDEServer->uninit();
8498 unconst(mVRDEServer).setNull();
8499 }
8500
8501 if (mBIOSSettings)
8502 {
8503 mBIOSSettings->uninit();
8504 unconst(mBIOSSettings).setNull();
8505 }
8506
8507#ifdef VBOX_WITH_UNATTENDED
8508 if (mUnattended)
8509 {
8510 mUnattended->uninit();
8511 unconst(mUnattended).setNull();
8512 }
8513#endif
8514
8515 /* Deassociate media (only when a real Machine or a SnapshotMachine
8516 * instance is uninitialized; SessionMachine instances refer to real
8517 * Machine media). This is necessary for a clean re-initialization of
8518 * the VM after successfully re-checking the accessibility state. Note
8519 * that in case of normal Machine or SnapshotMachine uninitialization (as
8520 * a result of unregistering or deleting the snapshot), outdated media
8521 * attachments will already be uninitialized and deleted, so this
8522 * code will not affect them. */
8523 if ( !mMediumAttachments.isNull()
8524 && !i_isSessionMachine()
8525 )
8526 {
8527 for (MediumAttachmentList::const_iterator
8528 it = mMediumAttachments->begin();
8529 it != mMediumAttachments->end();
8530 ++it)
8531 {
8532 ComObjPtr<Medium> pMedium = (*it)->i_getMedium();
8533 if (pMedium.isNull())
8534 continue;
8535 HRESULT rc = pMedium->i_removeBackReference(mData->mUuid, i_getSnapshotId());
8536 AssertComRC(rc);
8537 }
8538 }
8539
8540 if (!i_isSessionMachine() && !i_isSnapshotMachine())
8541 {
8542 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
8543 if (mData->mFirstSnapshot)
8544 {
8545 // snapshots tree is protected by machine write lock; strictly
8546 // this isn't necessary here since we're deleting the entire
8547 // machine, but otherwise we assert in Snapshot::uninit()
8548 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8549 mData->mFirstSnapshot->uninit();
8550 mData->mFirstSnapshot.setNull();
8551 }
8552
8553 mData->mCurrentSnapshot.setNull();
8554 }
8555
8556 /* free data structures (the essential mData structure is not freed here
8557 * since it may be still in use) */
8558 mMediumAttachments.free();
8559 mStorageControllers.free();
8560 mUSBControllers.free();
8561 mHWData.free();
8562 mUserData.free();
8563 mSSData.free();
8564}
8565
8566/**
8567 * Returns a pointer to the Machine object for this machine that acts like a
8568 * parent for complex machine data objects such as shared folders, etc.
8569 *
8570 * For primary Machine objects and for SnapshotMachine objects, returns this
8571 * object's pointer itself. For SessionMachine objects, returns the peer
8572 * (primary) machine pointer.
8573 */
8574Machine *Machine::i_getMachine()
8575{
8576 if (i_isSessionMachine())
8577 return (Machine*)mPeer;
8578 return this;
8579}
8580
8581/**
8582 * Makes sure that there are no machine state dependents. If necessary, waits
8583 * for the number of dependents to drop to zero.
8584 *
8585 * Make sure this method is called from under this object's write lock to
8586 * guarantee that no new dependents may be added when this method returns
8587 * control to the caller.
8588 *
8589 * @note Locks this object for writing. The lock will be released while waiting
8590 * (if necessary).
8591 *
8592 * @warning To be used only in methods that change the machine state!
8593 */
8594void Machine::i_ensureNoStateDependencies()
8595{
8596 AssertReturnVoid(isWriteLockOnCurrentThread());
8597
8598 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8599
8600 /* Wait for all state dependents if necessary */
8601 if (mData->mMachineStateDeps != 0)
8602 {
8603 /* lazy semaphore creation */
8604 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
8605 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
8606
8607 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
8608 mData->mMachineStateDeps));
8609
8610 ++mData->mMachineStateChangePending;
8611
8612 /* reset the semaphore before waiting, the last dependent will signal
8613 * it */
8614 RTSemEventMultiReset(mData->mMachineStateDepsSem);
8615
8616 alock.release();
8617
8618 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
8619
8620 alock.acquire();
8621
8622 -- mData->mMachineStateChangePending;
8623 }
8624}
8625
8626/**
8627 * Changes the machine state and informs callbacks.
8628 *
8629 * This method is not intended to fail so it either returns S_OK or asserts (and
8630 * returns a failure).
8631 *
8632 * @note Locks this object for writing.
8633 */
8634HRESULT Machine::i_setMachineState(MachineState_T aMachineState)
8635{
8636 LogFlowThisFuncEnter();
8637 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
8638 Assert(aMachineState != MachineState_Null);
8639
8640 AutoCaller autoCaller(this);
8641 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8642
8643 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8644
8645 /* wait for state dependents to drop to zero */
8646 i_ensureNoStateDependencies();
8647
8648 MachineState_T const enmOldState = mData->mMachineState;
8649 if (enmOldState != aMachineState)
8650 {
8651 mData->mMachineState = aMachineState;
8652 RTTimeNow(&mData->mLastStateChange);
8653
8654#ifdef VBOX_WITH_DTRACE_R3_MAIN
8655 VBOXAPI_MACHINE_STATE_CHANGED(this, aMachineState, enmOldState, mData->mUuid.toStringCurly().c_str());
8656#endif
8657 mParent->i_onMachineStateChange(mData->mUuid, aMachineState);
8658 }
8659
8660 LogFlowThisFuncLeave();
8661 return S_OK;
8662}
8663
8664/**
8665 * Searches for a shared folder with the given logical name
8666 * in the collection of shared folders.
8667 *
8668 * @param aName logical name of the shared folder
8669 * @param aSharedFolder where to return the found object
8670 * @param aSetError whether to set the error info if the folder is
8671 * not found
8672 * @return
8673 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
8674 *
8675 * @note
8676 * must be called from under the object's lock!
8677 */
8678HRESULT Machine::i_findSharedFolder(const Utf8Str &aName,
8679 ComObjPtr<SharedFolder> &aSharedFolder,
8680 bool aSetError /* = false */)
8681{
8682 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
8683 for (HWData::SharedFolderList::const_iterator
8684 it = mHWData->mSharedFolders.begin();
8685 it != mHWData->mSharedFolders.end();
8686 ++it)
8687 {
8688 SharedFolder *pSF = *it;
8689 AutoCaller autoCaller(pSF);
8690 if (pSF->i_getName() == aName)
8691 {
8692 aSharedFolder = pSF;
8693 rc = S_OK;
8694 break;
8695 }
8696 }
8697
8698 if (aSetError && FAILED(rc))
8699 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
8700
8701 return rc;
8702}
8703
8704/**
8705 * Initializes all machine instance data from the given settings structures
8706 * from XML. The exception is the machine UUID which needs special handling
8707 * depending on the caller's use case, so the caller needs to set that herself.
8708 *
8709 * This gets called in several contexts during machine initialization:
8710 *
8711 * -- When machine XML exists on disk already and needs to be loaded into memory,
8712 * for example, from #i_registeredInit() to load all registered machines on
8713 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
8714 * attached to the machine should be part of some media registry already.
8715 *
8716 * -- During OVF import, when a machine config has been constructed from an
8717 * OVF file. In this case, puuidRegistry is set to the machine UUID to
8718 * ensure that the media listed as attachments in the config (which have
8719 * been imported from the OVF) receive the correct registry ID.
8720 *
8721 * -- During VM cloning.
8722 *
8723 * @param config Machine settings from XML.
8724 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID
8725 * for each attached medium in the config.
8726 * @return
8727 */
8728HRESULT Machine::i_loadMachineDataFromSettings(const settings::MachineConfigFile &config,
8729 const Guid *puuidRegistry)
8730{
8731 // copy name, description, OS type, teleporter, UTC etc.
8732 mUserData->s = config.machineUserData;
8733
8734 // look up the object by Id to check it is valid
8735 ComObjPtr<GuestOSType> pGuestOSType;
8736 HRESULT rc = mParent->i_findGuestOSType(mUserData->s.strOsType,
8737 pGuestOSType);
8738 if (FAILED(rc)) return rc;
8739 mUserData->s.strOsType = pGuestOSType->i_id();
8740
8741 // stateFile (optional)
8742 if (config.strStateFile.isEmpty())
8743 mSSData->strStateFilePath.setNull();
8744 else
8745 {
8746 Utf8Str stateFilePathFull(config.strStateFile);
8747 int vrc = i_calculateFullPath(stateFilePathFull, stateFilePathFull);
8748 if (RT_FAILURE(vrc))
8749 return setError(E_FAIL,
8750 tr("Invalid saved state file path '%s' (%Rrc)"),
8751 config.strStateFile.c_str(),
8752 vrc);
8753 mSSData->strStateFilePath = stateFilePathFull;
8754 }
8755
8756 // snapshot folder needs special processing so set it again
8757 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
8758 if (FAILED(rc)) return rc;
8759
8760 /* Copy the extra data items (config may or may not be the same as
8761 * mData->pMachineConfigFile) if necessary. When loading the XML files
8762 * from disk they are the same, but not for OVF import. */
8763 if (mData->pMachineConfigFile != &config)
8764 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
8765
8766 /* currentStateModified (optional, default is true) */
8767 mData->mCurrentStateModified = config.fCurrentStateModified;
8768
8769 mData->mLastStateChange = config.timeLastStateChange;
8770
8771 /*
8772 * note: all mUserData members must be assigned prior this point because
8773 * we need to commit changes in order to let mUserData be shared by all
8774 * snapshot machine instances.
8775 */
8776 mUserData.commitCopy();
8777
8778 // machine registry, if present (must be loaded before snapshots)
8779 if (config.canHaveOwnMediaRegistry())
8780 {
8781 // determine machine folder
8782 Utf8Str strMachineFolder = i_getSettingsFileFull();
8783 strMachineFolder.stripFilename();
8784 rc = mParent->initMedia(i_getId(), // media registry ID == machine UUID
8785 config.mediaRegistry,
8786 strMachineFolder);
8787 if (FAILED(rc)) return rc;
8788 }
8789
8790 /* Snapshot node (optional) */
8791 size_t cRootSnapshots;
8792 if ((cRootSnapshots = config.llFirstSnapshot.size()))
8793 {
8794 // there must be only one root snapshot
8795 Assert(cRootSnapshots == 1);
8796
8797 const settings::Snapshot &snap = config.llFirstSnapshot.front();
8798
8799 rc = i_loadSnapshot(snap,
8800 config.uuidCurrentSnapshot,
8801 NULL); // no parent == first snapshot
8802 if (FAILED(rc)) return rc;
8803 }
8804
8805 // hardware data
8806 rc = i_loadHardware(puuidRegistry, NULL, config.hardwareMachine, &config.debugging, &config.autostart);
8807 if (FAILED(rc)) return rc;
8808
8809 /*
8810 * NOTE: the assignment below must be the last thing to do,
8811 * otherwise it will be not possible to change the settings
8812 * somewhere in the code above because all setters will be
8813 * blocked by i_checkStateDependency(MutableStateDep).
8814 */
8815
8816 /* set the machine state to Aborted or Saved when appropriate */
8817 if (config.fAborted)
8818 {
8819 mSSData->strStateFilePath.setNull();
8820
8821 /* no need to use i_setMachineState() during init() */
8822 mData->mMachineState = MachineState_Aborted;
8823 }
8824 else if (!mSSData->strStateFilePath.isEmpty())
8825 {
8826 /* no need to use i_setMachineState() during init() */
8827 mData->mMachineState = MachineState_Saved;
8828 }
8829
8830 // after loading settings, we are no longer different from the XML on disk
8831 mData->flModifications = 0;
8832
8833 return S_OK;
8834}
8835
8836/**
8837 * Recursively loads all snapshots starting from the given.
8838 *
8839 * @param data snapshot settings.
8840 * @param aCurSnapshotId Current snapshot ID from the settings file.
8841 * @param aParentSnapshot Parent snapshot.
8842 */
8843HRESULT Machine::i_loadSnapshot(const settings::Snapshot &data,
8844 const Guid &aCurSnapshotId,
8845 Snapshot *aParentSnapshot)
8846{
8847 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
8848 AssertReturn(!i_isSessionMachine(), E_FAIL);
8849
8850 HRESULT rc = S_OK;
8851
8852 Utf8Str strStateFile;
8853 if (!data.strStateFile.isEmpty())
8854 {
8855 /* optional */
8856 strStateFile = data.strStateFile;
8857 int vrc = i_calculateFullPath(strStateFile, strStateFile);
8858 if (RT_FAILURE(vrc))
8859 return setError(E_FAIL,
8860 tr("Invalid saved state file path '%s' (%Rrc)"),
8861 strStateFile.c_str(),
8862 vrc);
8863 }
8864
8865 /* create a snapshot machine object */
8866 ComObjPtr<SnapshotMachine> pSnapshotMachine;
8867 pSnapshotMachine.createObject();
8868 rc = pSnapshotMachine->initFromSettings(this,
8869 data.hardware,
8870 &data.debugging,
8871 &data.autostart,
8872 data.uuid.ref(),
8873 strStateFile);
8874 if (FAILED(rc)) return rc;
8875
8876 /* create a snapshot object */
8877 ComObjPtr<Snapshot> pSnapshot;
8878 pSnapshot.createObject();
8879 /* initialize the snapshot */
8880 rc = pSnapshot->init(mParent, // VirtualBox object
8881 data.uuid,
8882 data.strName,
8883 data.strDescription,
8884 data.timestamp,
8885 pSnapshotMachine,
8886 aParentSnapshot);
8887 if (FAILED(rc)) return rc;
8888
8889 /* memorize the first snapshot if necessary */
8890 if (!mData->mFirstSnapshot)
8891 mData->mFirstSnapshot = pSnapshot;
8892
8893 /* memorize the current snapshot when appropriate */
8894 if ( !mData->mCurrentSnapshot
8895 && pSnapshot->i_getId() == aCurSnapshotId
8896 )
8897 mData->mCurrentSnapshot = pSnapshot;
8898
8899 // now create the children
8900 for (settings::SnapshotsList::const_iterator
8901 it = data.llChildSnapshots.begin();
8902 it != data.llChildSnapshots.end();
8903 ++it)
8904 {
8905 const settings::Snapshot &childData = *it;
8906 // recurse
8907 rc = i_loadSnapshot(childData,
8908 aCurSnapshotId,
8909 pSnapshot); // parent = the one we created above
8910 if (FAILED(rc)) return rc;
8911 }
8912
8913 return rc;
8914}
8915
8916/**
8917 * Loads settings into mHWData.
8918 *
8919 * @param puuidRegistry Registry ID.
8920 * @param puuidSnapshot Snapshot ID
8921 * @param data Reference to the hardware settings.
8922 * @param pDbg Pointer to the debugging settings.
8923 * @param pAutostart Pointer to the autostart settings.
8924 */
8925HRESULT Machine::i_loadHardware(const Guid *puuidRegistry,
8926 const Guid *puuidSnapshot,
8927 const settings::Hardware &data,
8928 const settings::Debugging *pDbg,
8929 const settings::Autostart *pAutostart)
8930{
8931 AssertReturn(!i_isSessionMachine(), E_FAIL);
8932
8933 HRESULT rc = S_OK;
8934
8935 try
8936 {
8937 ComObjPtr<GuestOSType> pGuestOSType;
8938 rc = mParent->i_findGuestOSType(Bstr(mUserData->s.strOsType).raw(),
8939 pGuestOSType);
8940 if (FAILED(rc))
8941 return rc;
8942
8943 /* The hardware version attribute (optional). */
8944 mHWData->mHWVersion = data.strVersion;
8945 mHWData->mHardwareUUID = data.uuid;
8946
8947 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
8948 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
8949 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
8950 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
8951 mHWData->mHWVirtExUXEnabled = data.fUnrestrictedExecution;
8952 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
8953 mHWData->mPAEEnabled = data.fPAE;
8954 mHWData->mLongMode = data.enmLongMode;
8955 mHWData->mTripleFaultReset = data.fTripleFaultReset;
8956 mHWData->mAPIC = data.fAPIC;
8957 mHWData->mX2APIC = data.fX2APIC;
8958 mHWData->mCPUCount = data.cCPUs;
8959 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
8960 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
8961 mHWData->mCpuIdPortabilityLevel = data.uCpuIdPortabilityLevel;
8962 mHWData->mCpuProfile = data.strCpuProfile;
8963
8964 // cpu
8965 if (mHWData->mCPUHotPlugEnabled)
8966 {
8967 for (settings::CpuList::const_iterator
8968 it = data.llCpus.begin();
8969 it != data.llCpus.end();
8970 ++it)
8971 {
8972 const settings::Cpu &cpu = *it;
8973
8974 mHWData->mCPUAttached[cpu.ulId] = true;
8975 }
8976 }
8977
8978 // cpuid leafs
8979 for (settings::CpuIdLeafsList::const_iterator
8980 it = data.llCpuIdLeafs.begin();
8981 it != data.llCpuIdLeafs.end();
8982 ++it)
8983 {
8984 const settings::CpuIdLeaf &leaf = *it;
8985
8986 switch (leaf.ulId)
8987 {
8988 case 0x0:
8989 case 0x1:
8990 case 0x2:
8991 case 0x3:
8992 case 0x4:
8993 case 0x5:
8994 case 0x6:
8995 case 0x7:
8996 case 0x8:
8997 case 0x9:
8998 case 0xA:
8999 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
9000 break;
9001
9002 case 0x80000000:
9003 case 0x80000001:
9004 case 0x80000002:
9005 case 0x80000003:
9006 case 0x80000004:
9007 case 0x80000005:
9008 case 0x80000006:
9009 case 0x80000007:
9010 case 0x80000008:
9011 case 0x80000009:
9012 case 0x8000000A:
9013 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
9014 break;
9015
9016 default:
9017 /* just ignore */
9018 break;
9019 }
9020 }
9021
9022 mHWData->mMemorySize = data.ulMemorySizeMB;
9023 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
9024
9025 // boot order
9026 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
9027 {
9028 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
9029 if (it == data.mapBootOrder.end())
9030 mHWData->mBootOrder[i] = DeviceType_Null;
9031 else
9032 mHWData->mBootOrder[i] = it->second;
9033 }
9034
9035 mHWData->mGraphicsControllerType = data.graphicsControllerType;
9036 mHWData->mVRAMSize = data.ulVRAMSizeMB;
9037 mHWData->mMonitorCount = data.cMonitors;
9038 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
9039 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
9040 mHWData->mVideoCaptureWidth = data.ulVideoCaptureHorzRes;
9041 mHWData->mVideoCaptureHeight = data.ulVideoCaptureVertRes;
9042 mHWData->mVideoCaptureEnabled = data.fVideoCaptureEnabled;
9043 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->maVideoCaptureScreens); ++i)
9044 mHWData->maVideoCaptureScreens[i] = ASMBitTest(&data.u64VideoCaptureScreens, i);
9045 AssertCompile(RT_ELEMENTS(mHWData->maVideoCaptureScreens) == sizeof(data.u64VideoCaptureScreens) * 8);
9046 mHWData->mVideoCaptureRate = data.ulVideoCaptureRate;
9047 mHWData->mVideoCaptureFPS = data.ulVideoCaptureFPS;
9048 if (!data.strVideoCaptureFile.isEmpty())
9049 i_calculateFullPath(data.strVideoCaptureFile, mHWData->mVideoCaptureFile);
9050 else
9051 mHWData->mVideoCaptureFile.setNull();
9052 mHWData->mFirmwareType = data.firmwareType;
9053 mHWData->mPointingHIDType = data.pointingHIDType;
9054 mHWData->mKeyboardHIDType = data.keyboardHIDType;
9055 mHWData->mChipsetType = data.chipsetType;
9056 mHWData->mParavirtProvider = data.paravirtProvider;
9057 mHWData->mParavirtDebug = data.strParavirtDebug;
9058 mHWData->mEmulatedUSBCardReaderEnabled = data.fEmulatedUSBCardReader;
9059 mHWData->mHPETEnabled = data.fHPETEnabled;
9060
9061 /* VRDEServer */
9062 rc = mVRDEServer->i_loadSettings(data.vrdeSettings);
9063 if (FAILED(rc)) return rc;
9064
9065 /* BIOS */
9066 rc = mBIOSSettings->i_loadSettings(data.biosSettings);
9067 if (FAILED(rc)) return rc;
9068
9069 // Bandwidth control (must come before network adapters)
9070 rc = mBandwidthControl->i_loadSettings(data.ioSettings);
9071 if (FAILED(rc)) return rc;
9072
9073 /* Shared folders */
9074 for (settings::USBControllerList::const_iterator
9075 it = data.usbSettings.llUSBControllers.begin();
9076 it != data.usbSettings.llUSBControllers.end();
9077 ++it)
9078 {
9079 const settings::USBController &settingsCtrl = *it;
9080 ComObjPtr<USBController> newCtrl;
9081
9082 newCtrl.createObject();
9083 newCtrl->init(this, settingsCtrl.strName, settingsCtrl.enmType);
9084 mUSBControllers->push_back(newCtrl);
9085 }
9086
9087 /* USB device filters */
9088 rc = mUSBDeviceFilters->i_loadSettings(data.usbSettings);
9089 if (FAILED(rc)) return rc;
9090
9091 // network adapters (establish array size first and apply defaults, to
9092 // ensure reading the same settings as we saved, since the list skips
9093 // adapters having defaults)
9094 size_t newCount = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
9095 size_t oldCount = mNetworkAdapters.size();
9096 if (newCount > oldCount)
9097 {
9098 mNetworkAdapters.resize(newCount);
9099 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); ++slot)
9100 {
9101 unconst(mNetworkAdapters[slot]).createObject();
9102 mNetworkAdapters[slot]->init(this, (ULONG)slot);
9103 }
9104 }
9105 else if (newCount < oldCount)
9106 mNetworkAdapters.resize(newCount);
9107 for (unsigned i = 0; i < mNetworkAdapters.size(); i++)
9108 mNetworkAdapters[i]->i_applyDefaults(pGuestOSType);
9109 for (settings::NetworkAdaptersList::const_iterator
9110 it = data.llNetworkAdapters.begin();
9111 it != data.llNetworkAdapters.end();
9112 ++it)
9113 {
9114 const settings::NetworkAdapter &nic = *it;
9115
9116 /* slot uniqueness is guaranteed by XML Schema */
9117 AssertBreak(nic.ulSlot < mNetworkAdapters.size());
9118 rc = mNetworkAdapters[nic.ulSlot]->i_loadSettings(mBandwidthControl, nic);
9119 if (FAILED(rc)) return rc;
9120 }
9121
9122 // serial ports (establish defaults first, to ensure reading the same
9123 // settings as we saved, since the list skips ports having defaults)
9124 for (unsigned i = 0; i < RT_ELEMENTS(mSerialPorts); i++)
9125 mSerialPorts[i]->i_applyDefaults(pGuestOSType);
9126 for (settings::SerialPortsList::const_iterator
9127 it = data.llSerialPorts.begin();
9128 it != data.llSerialPorts.end();
9129 ++it)
9130 {
9131 const settings::SerialPort &s = *it;
9132
9133 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
9134 rc = mSerialPorts[s.ulSlot]->i_loadSettings(s);
9135 if (FAILED(rc)) return rc;
9136 }
9137
9138 // parallel ports (establish defaults first, to ensure reading the same
9139 // settings as we saved, since the list skips ports having defaults)
9140 for (unsigned i = 0; i < RT_ELEMENTS(mParallelPorts); i++)
9141 mParallelPorts[i]->i_applyDefaults();
9142 for (settings::ParallelPortsList::const_iterator
9143 it = data.llParallelPorts.begin();
9144 it != data.llParallelPorts.end();
9145 ++it)
9146 {
9147 const settings::ParallelPort &p = *it;
9148
9149 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
9150 rc = mParallelPorts[p.ulSlot]->i_loadSettings(p);
9151 if (FAILED(rc)) return rc;
9152 }
9153
9154 /* AudioAdapter */
9155 rc = mAudioAdapter->i_loadSettings(data.audioAdapter);
9156 if (FAILED(rc)) return rc;
9157
9158 /* storage controllers */
9159 rc = i_loadStorageControllers(data.storage,
9160 puuidRegistry,
9161 puuidSnapshot);
9162 if (FAILED(rc)) return rc;
9163
9164 /* Shared folders */
9165 for (settings::SharedFoldersList::const_iterator
9166 it = data.llSharedFolders.begin();
9167 it != data.llSharedFolders.end();
9168 ++it)
9169 {
9170 const settings::SharedFolder &sf = *it;
9171
9172 ComObjPtr<SharedFolder> sharedFolder;
9173 /* Check for double entries. Not allowed! */
9174 rc = i_findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
9175 if (SUCCEEDED(rc))
9176 return setError(VBOX_E_OBJECT_IN_USE,
9177 tr("Shared folder named '%s' already exists"),
9178 sf.strName.c_str());
9179
9180 /* Create the new shared folder. Don't break on error. This will be
9181 * reported when the machine starts. */
9182 sharedFolder.createObject();
9183 rc = sharedFolder->init(i_getMachine(),
9184 sf.strName,
9185 sf.strHostPath,
9186 RT_BOOL(sf.fWritable),
9187 RT_BOOL(sf.fAutoMount),
9188 false /* fFailOnError */);
9189 if (FAILED(rc)) return rc;
9190 mHWData->mSharedFolders.push_back(sharedFolder);
9191 }
9192
9193 // Clipboard
9194 mHWData->mClipboardMode = data.clipboardMode;
9195
9196 // drag'n'drop
9197 mHWData->mDnDMode = data.dndMode;
9198
9199 // guest settings
9200 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
9201
9202 // IO settings
9203 mHWData->mIOCacheEnabled = data.ioSettings.fIOCacheEnabled;
9204 mHWData->mIOCacheSize = data.ioSettings.ulIOCacheSize;
9205
9206 // Host PCI devices
9207 for (settings::HostPCIDeviceAttachmentList::const_iterator
9208 it = data.pciAttachments.begin();
9209 it != data.pciAttachments.end();
9210 ++it)
9211 {
9212 const settings::HostPCIDeviceAttachment &hpda = *it;
9213 ComObjPtr<PCIDeviceAttachment> pda;
9214
9215 pda.createObject();
9216 pda->i_loadSettings(this, hpda);
9217 mHWData->mPCIDeviceAssignments.push_back(pda);
9218 }
9219
9220 /*
9221 * (The following isn't really real hardware, but it lives in HWData
9222 * for reasons of convenience.)
9223 */
9224
9225#ifdef VBOX_WITH_GUEST_PROPS
9226 /* Guest properties (optional) */
9227
9228 /* Only load transient guest properties for configs which have saved
9229 * state, because there shouldn't be any for powered off VMs. The same
9230 * logic applies for snapshots, as offline snapshots shouldn't have
9231 * any such properties. They confuse the code in various places.
9232 * Note: can't rely on the machine state, as it isn't set yet. */
9233 bool fSkipTransientGuestProperties = mSSData->strStateFilePath.isEmpty();
9234 /* apologies for the hacky unconst() usage, but this needs hacking
9235 * actually inconsistent settings into consistency, otherwise there
9236 * will be some corner cases where the inconsistency survives
9237 * surprisingly long without getting fixed, especially for snapshots
9238 * as there are no config changes. */
9239 settings::GuestPropertiesList &llGuestProperties = unconst(data.llGuestProperties);
9240 for (settings::GuestPropertiesList::iterator
9241 it = llGuestProperties.begin();
9242 it != llGuestProperties.end();
9243 /*nothing*/)
9244 {
9245 const settings::GuestProperty &prop = *it;
9246 uint32_t fFlags = guestProp::NILFLAG;
9247 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
9248 if ( fSkipTransientGuestProperties
9249 && ( fFlags & guestProp::TRANSIENT
9250 || fFlags & guestProp::TRANSRESET))
9251 {
9252 it = llGuestProperties.erase(it);
9253 continue;
9254 }
9255 HWData::GuestProperty property = { prop.strValue, (LONG64) prop.timestamp, fFlags };
9256 mHWData->mGuestProperties[prop.strName] = property;
9257 ++it;
9258 }
9259#endif /* VBOX_WITH_GUEST_PROPS defined */
9260
9261 rc = i_loadDebugging(pDbg);
9262 if (FAILED(rc))
9263 return rc;
9264
9265 mHWData->mAutostart = *pAutostart;
9266
9267 /* default frontend */
9268 mHWData->mDefaultFrontend = data.strDefaultFrontend;
9269 }
9270 catch (std::bad_alloc &)
9271 {
9272 return E_OUTOFMEMORY;
9273 }
9274
9275 AssertComRC(rc);
9276 return rc;
9277}
9278
9279/**
9280 * Called from i_loadHardware() to load the debugging settings of the
9281 * machine.
9282 *
9283 * @param pDbg Pointer to the settings.
9284 */
9285HRESULT Machine::i_loadDebugging(const settings::Debugging *pDbg)
9286{
9287 mHWData->mDebugging = *pDbg;
9288 /* no more processing currently required, this will probably change. */
9289 return S_OK;
9290}
9291
9292/**
9293 * Called from i_loadMachineDataFromSettings() for the storage controller data, including media.
9294 *
9295 * @param data storage settings.
9296 * @param puuidRegistry media registry ID to set media to or NULL;
9297 * see Machine::i_loadMachineDataFromSettings()
9298 * @param puuidSnapshot snapshot ID
9299 * @return
9300 */
9301HRESULT Machine::i_loadStorageControllers(const settings::Storage &data,
9302 const Guid *puuidRegistry,
9303 const Guid *puuidSnapshot)
9304{
9305 AssertReturn(!i_isSessionMachine(), E_FAIL);
9306
9307 HRESULT rc = S_OK;
9308
9309 for (settings::StorageControllersList::const_iterator
9310 it = data.llStorageControllers.begin();
9311 it != data.llStorageControllers.end();
9312 ++it)
9313 {
9314 const settings::StorageController &ctlData = *it;
9315
9316 ComObjPtr<StorageController> pCtl;
9317 /* Try to find one with the name first. */
9318 rc = i_getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
9319 if (SUCCEEDED(rc))
9320 return setError(VBOX_E_OBJECT_IN_USE,
9321 tr("Storage controller named '%s' already exists"),
9322 ctlData.strName.c_str());
9323
9324 pCtl.createObject();
9325 rc = pCtl->init(this,
9326 ctlData.strName,
9327 ctlData.storageBus,
9328 ctlData.ulInstance,
9329 ctlData.fBootable);
9330 if (FAILED(rc)) return rc;
9331
9332 mStorageControllers->push_back(pCtl);
9333
9334 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
9335 if (FAILED(rc)) return rc;
9336
9337 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
9338 if (FAILED(rc)) return rc;
9339
9340 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
9341 if (FAILED(rc)) return rc;
9342
9343 /* Load the attached devices now. */
9344 rc = i_loadStorageDevices(pCtl,
9345 ctlData,
9346 puuidRegistry,
9347 puuidSnapshot);
9348 if (FAILED(rc)) return rc;
9349 }
9350
9351 return S_OK;
9352}
9353
9354/**
9355 * Called from i_loadStorageControllers for a controller's devices.
9356 *
9357 * @param aStorageController
9358 * @param data
9359 * @param puuidRegistry media registry ID to set media to or NULL; see
9360 * Machine::i_loadMachineDataFromSettings()
9361 * @param puuidSnapshot pointer to the snapshot ID if this is a snapshot machine
9362 * @return
9363 */
9364HRESULT Machine::i_loadStorageDevices(StorageController *aStorageController,
9365 const settings::StorageController &data,
9366 const Guid *puuidRegistry,
9367 const Guid *puuidSnapshot)
9368{
9369 HRESULT rc = S_OK;
9370
9371 /* paranoia: detect duplicate attachments */
9372 for (settings::AttachedDevicesList::const_iterator
9373 it = data.llAttachedDevices.begin();
9374 it != data.llAttachedDevices.end();
9375 ++it)
9376 {
9377 const settings::AttachedDevice &ad = *it;
9378
9379 for (settings::AttachedDevicesList::const_iterator it2 = it;
9380 it2 != data.llAttachedDevices.end();
9381 ++it2)
9382 {
9383 if (it == it2)
9384 continue;
9385
9386 const settings::AttachedDevice &ad2 = *it2;
9387
9388 if ( ad.lPort == ad2.lPort
9389 && ad.lDevice == ad2.lDevice)
9390 {
9391 return setError(E_FAIL,
9392 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
9393 aStorageController->i_getName().c_str(),
9394 ad.lPort,
9395 ad.lDevice,
9396 mUserData->s.strName.c_str());
9397 }
9398 }
9399 }
9400
9401 for (settings::AttachedDevicesList::const_iterator
9402 it = data.llAttachedDevices.begin();
9403 it != data.llAttachedDevices.end();
9404 ++it)
9405 {
9406 const settings::AttachedDevice &dev = *it;
9407 ComObjPtr<Medium> medium;
9408
9409 switch (dev.deviceType)
9410 {
9411 case DeviceType_Floppy:
9412 case DeviceType_DVD:
9413 if (dev.strHostDriveSrc.isNotEmpty())
9414 rc = mParent->i_host()->i_findHostDriveByName(dev.deviceType, dev.strHostDriveSrc,
9415 false /* fRefresh */, medium);
9416 else
9417 rc = mParent->i_findRemoveableMedium(dev.deviceType,
9418 dev.uuid,
9419 false /* fRefresh */,
9420 false /* aSetError */,
9421 medium);
9422 if (rc == VBOX_E_OBJECT_NOT_FOUND)
9423 // This is not an error. The host drive or UUID might have vanished, so just go
9424 // ahead without this removeable medium attachment
9425 rc = S_OK;
9426 break;
9427
9428 case DeviceType_HardDisk:
9429 {
9430 /* find a hard disk by UUID */
9431 rc = mParent->i_findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
9432 if (FAILED(rc))
9433 {
9434 if (i_isSnapshotMachine())
9435 {
9436 // wrap another error message around the "cannot find hard disk" set by findHardDisk
9437 // so the user knows that the bad disk is in a snapshot somewhere
9438 com::ErrorInfo info;
9439 return setError(E_FAIL,
9440 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
9441 puuidSnapshot->raw(),
9442 info.getText().raw());
9443 }
9444 else
9445 return rc;
9446 }
9447
9448 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
9449
9450 if (medium->i_getType() == MediumType_Immutable)
9451 {
9452 if (i_isSnapshotMachine())
9453 return setError(E_FAIL,
9454 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9455 "of the virtual machine '%s' ('%s')"),
9456 medium->i_getLocationFull().c_str(),
9457 dev.uuid.raw(),
9458 puuidSnapshot->raw(),
9459 mUserData->s.strName.c_str(),
9460 mData->m_strConfigFileFull.c_str());
9461
9462 return setError(E_FAIL,
9463 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9464 medium->i_getLocationFull().c_str(),
9465 dev.uuid.raw(),
9466 mUserData->s.strName.c_str(),
9467 mData->m_strConfigFileFull.c_str());
9468 }
9469
9470 if (medium->i_getType() == MediumType_MultiAttach)
9471 {
9472 if (i_isSnapshotMachine())
9473 return setError(E_FAIL,
9474 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9475 "of the virtual machine '%s' ('%s')"),
9476 medium->i_getLocationFull().c_str(),
9477 dev.uuid.raw(),
9478 puuidSnapshot->raw(),
9479 mUserData->s.strName.c_str(),
9480 mData->m_strConfigFileFull.c_str());
9481
9482 return setError(E_FAIL,
9483 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9484 medium->i_getLocationFull().c_str(),
9485 dev.uuid.raw(),
9486 mUserData->s.strName.c_str(),
9487 mData->m_strConfigFileFull.c_str());
9488 }
9489
9490 if ( !i_isSnapshotMachine()
9491 && medium->i_getChildren().size() != 0
9492 )
9493 return setError(E_FAIL,
9494 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
9495 "because it has %d differencing child hard disks"),
9496 medium->i_getLocationFull().c_str(),
9497 dev.uuid.raw(),
9498 mUserData->s.strName.c_str(),
9499 mData->m_strConfigFileFull.c_str(),
9500 medium->i_getChildren().size());
9501
9502 if (i_findAttachment(*mMediumAttachments.data(),
9503 medium))
9504 return setError(E_FAIL,
9505 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
9506 medium->i_getLocationFull().c_str(),
9507 dev.uuid.raw(),
9508 mUserData->s.strName.c_str(),
9509 mData->m_strConfigFileFull.c_str());
9510
9511 break;
9512 }
9513
9514 default:
9515 return setError(E_FAIL,
9516 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
9517 medium->i_getLocationFull().c_str(),
9518 mUserData->s.strName.c_str(),
9519 mData->m_strConfigFileFull.c_str());
9520 }
9521
9522 if (FAILED(rc))
9523 break;
9524
9525 /* Bandwidth groups are loaded at this point. */
9526 ComObjPtr<BandwidthGroup> pBwGroup;
9527
9528 if (!dev.strBwGroup.isEmpty())
9529 {
9530 rc = mBandwidthControl->i_getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
9531 if (FAILED(rc))
9532 return setError(E_FAIL,
9533 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
9534 medium->i_getLocationFull().c_str(),
9535 dev.strBwGroup.c_str(),
9536 mUserData->s.strName.c_str(),
9537 mData->m_strConfigFileFull.c_str());
9538 pBwGroup->i_reference();
9539 }
9540
9541 const Utf8Str controllerName = aStorageController->i_getName();
9542 ComObjPtr<MediumAttachment> pAttachment;
9543 pAttachment.createObject();
9544 rc = pAttachment->init(this,
9545 medium,
9546 controllerName,
9547 dev.lPort,
9548 dev.lDevice,
9549 dev.deviceType,
9550 false,
9551 dev.fPassThrough,
9552 dev.fTempEject,
9553 dev.fNonRotational,
9554 dev.fDiscard,
9555 dev.fHotPluggable,
9556 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->i_getName());
9557 if (FAILED(rc)) break;
9558
9559 /* associate the medium with this machine and snapshot */
9560 if (!medium.isNull())
9561 {
9562 AutoCaller medCaller(medium);
9563 if (FAILED(medCaller.rc())) return medCaller.rc();
9564 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
9565
9566 if (i_isSnapshotMachine())
9567 rc = medium->i_addBackReference(mData->mUuid, *puuidSnapshot);
9568 else
9569 rc = medium->i_addBackReference(mData->mUuid);
9570 /* If the medium->addBackReference fails it sets an appropriate
9571 * error message, so no need to do any guesswork here. */
9572
9573 if (puuidRegistry)
9574 // caller wants registry ID to be set on all attached media (OVF import case)
9575 medium->i_addRegistry(*puuidRegistry);
9576 }
9577
9578 if (FAILED(rc))
9579 break;
9580
9581 /* back up mMediumAttachments to let registeredInit() properly rollback
9582 * on failure (= limited accessibility) */
9583 i_setModified(IsModified_Storage);
9584 mMediumAttachments.backup();
9585 mMediumAttachments->push_back(pAttachment);
9586 }
9587
9588 return rc;
9589}
9590
9591/**
9592 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
9593 *
9594 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
9595 * @param aSnapshot where to return the found snapshot
9596 * @param aSetError true to set extended error info on failure
9597 */
9598HRESULT Machine::i_findSnapshotById(const Guid &aId,
9599 ComObjPtr<Snapshot> &aSnapshot,
9600 bool aSetError /* = false */)
9601{
9602 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9603
9604 if (!mData->mFirstSnapshot)
9605 {
9606 if (aSetError)
9607 return setError(E_FAIL, tr("This machine does not have any snapshots"));
9608 return E_FAIL;
9609 }
9610
9611 if (aId.isZero())
9612 aSnapshot = mData->mFirstSnapshot;
9613 else
9614 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(aId.ref());
9615
9616 if (!aSnapshot)
9617 {
9618 if (aSetError)
9619 return setError(E_FAIL,
9620 tr("Could not find a snapshot with UUID {%s}"),
9621 aId.toString().c_str());
9622 return E_FAIL;
9623 }
9624
9625 return S_OK;
9626}
9627
9628/**
9629 * Returns the snapshot with the given name or fails of no such snapshot.
9630 *
9631 * @param strName snapshot name to find
9632 * @param aSnapshot where to return the found snapshot
9633 * @param aSetError true to set extended error info on failure
9634 */
9635HRESULT Machine::i_findSnapshotByName(const Utf8Str &strName,
9636 ComObjPtr<Snapshot> &aSnapshot,
9637 bool aSetError /* = false */)
9638{
9639 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
9640
9641 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9642
9643 if (!mData->mFirstSnapshot)
9644 {
9645 if (aSetError)
9646 return setError(VBOX_E_OBJECT_NOT_FOUND,
9647 tr("This machine does not have any snapshots"));
9648 return VBOX_E_OBJECT_NOT_FOUND;
9649 }
9650
9651 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(strName);
9652
9653 if (!aSnapshot)
9654 {
9655 if (aSetError)
9656 return setError(VBOX_E_OBJECT_NOT_FOUND,
9657 tr("Could not find a snapshot named '%s'"), strName.c_str());
9658 return VBOX_E_OBJECT_NOT_FOUND;
9659 }
9660
9661 return S_OK;
9662}
9663
9664/**
9665 * Returns a storage controller object with the given name.
9666 *
9667 * @param aName storage controller name to find
9668 * @param aStorageController where to return the found storage controller
9669 * @param aSetError true to set extended error info on failure
9670 */
9671HRESULT Machine::i_getStorageControllerByName(const Utf8Str &aName,
9672 ComObjPtr<StorageController> &aStorageController,
9673 bool aSetError /* = false */)
9674{
9675 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9676
9677 for (StorageControllerList::const_iterator
9678 it = mStorageControllers->begin();
9679 it != mStorageControllers->end();
9680 ++it)
9681 {
9682 if ((*it)->i_getName() == aName)
9683 {
9684 aStorageController = (*it);
9685 return S_OK;
9686 }
9687 }
9688
9689 if (aSetError)
9690 return setError(VBOX_E_OBJECT_NOT_FOUND,
9691 tr("Could not find a storage controller named '%s'"),
9692 aName.c_str());
9693 return VBOX_E_OBJECT_NOT_FOUND;
9694}
9695
9696/**
9697 * Returns a USB controller object with the given name.
9698 *
9699 * @param aName USB controller name to find
9700 * @param aUSBController where to return the found USB controller
9701 * @param aSetError true to set extended error info on failure
9702 */
9703HRESULT Machine::i_getUSBControllerByName(const Utf8Str &aName,
9704 ComObjPtr<USBController> &aUSBController,
9705 bool aSetError /* = false */)
9706{
9707 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9708
9709 for (USBControllerList::const_iterator
9710 it = mUSBControllers->begin();
9711 it != mUSBControllers->end();
9712 ++it)
9713 {
9714 if ((*it)->i_getName() == aName)
9715 {
9716 aUSBController = (*it);
9717 return S_OK;
9718 }
9719 }
9720
9721 if (aSetError)
9722 return setError(VBOX_E_OBJECT_NOT_FOUND,
9723 tr("Could not find a storage controller named '%s'"),
9724 aName.c_str());
9725 return VBOX_E_OBJECT_NOT_FOUND;
9726}
9727
9728/**
9729 * Returns the number of USB controller instance of the given type.
9730 *
9731 * @param enmType USB controller type.
9732 */
9733ULONG Machine::i_getUSBControllerCountByType(USBControllerType_T enmType)
9734{
9735 ULONG cCtrls = 0;
9736
9737 for (USBControllerList::const_iterator
9738 it = mUSBControllers->begin();
9739 it != mUSBControllers->end();
9740 ++it)
9741 {
9742 if ((*it)->i_getControllerType() == enmType)
9743 cCtrls++;
9744 }
9745
9746 return cCtrls;
9747}
9748
9749HRESULT Machine::i_getMediumAttachmentsOfController(const Utf8Str &aName,
9750 MediumAttachmentList &atts)
9751{
9752 AutoCaller autoCaller(this);
9753 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9754
9755 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9756
9757 for (MediumAttachmentList::const_iterator
9758 it = mMediumAttachments->begin();
9759 it != mMediumAttachments->end();
9760 ++it)
9761 {
9762 const ComObjPtr<MediumAttachment> &pAtt = *it;
9763 // should never happen, but deal with NULL pointers in the list.
9764 AssertContinue(!pAtt.isNull());
9765
9766 // getControllerName() needs caller+read lock
9767 AutoCaller autoAttCaller(pAtt);
9768 if (FAILED(autoAttCaller.rc()))
9769 {
9770 atts.clear();
9771 return autoAttCaller.rc();
9772 }
9773 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
9774
9775 if (pAtt->i_getControllerName() == aName)
9776 atts.push_back(pAtt);
9777 }
9778
9779 return S_OK;
9780}
9781
9782
9783/**
9784 * Helper for #i_saveSettings. Cares about renaming the settings directory and
9785 * file if the machine name was changed and about creating a new settings file
9786 * if this is a new machine.
9787 *
9788 * @note Must be never called directly but only from #saveSettings().
9789 */
9790HRESULT Machine::i_prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
9791{
9792 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9793
9794 HRESULT rc = S_OK;
9795
9796 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
9797
9798 /// @todo need to handle primary group change, too
9799
9800 /* attempt to rename the settings file if machine name is changed */
9801 if ( mUserData->s.fNameSync
9802 && mUserData.isBackedUp()
9803 && ( mUserData.backedUpData()->s.strName != mUserData->s.strName
9804 || mUserData.backedUpData()->s.llGroups.front() != mUserData->s.llGroups.front())
9805 )
9806 {
9807 bool dirRenamed = false;
9808 bool fileRenamed = false;
9809
9810 Utf8Str configFile, newConfigFile;
9811 Utf8Str configFilePrev, newConfigFilePrev;
9812 Utf8Str configDir, newConfigDir;
9813
9814 do
9815 {
9816 int vrc = VINF_SUCCESS;
9817
9818 Utf8Str name = mUserData.backedUpData()->s.strName;
9819 Utf8Str newName = mUserData->s.strName;
9820 Utf8Str group = mUserData.backedUpData()->s.llGroups.front();
9821 if (group == "/")
9822 group.setNull();
9823 Utf8Str newGroup = mUserData->s.llGroups.front();
9824 if (newGroup == "/")
9825 newGroup.setNull();
9826
9827 configFile = mData->m_strConfigFileFull;
9828
9829 /* first, rename the directory if it matches the group and machine name */
9830 Utf8Str groupPlusName = Utf8StrFmt("%s%c%s",
9831 group.c_str(), RTPATH_DELIMITER, name.c_str());
9832 /** @todo hack, make somehow use of ComposeMachineFilename */
9833 if (mUserData->s.fDirectoryIncludesUUID)
9834 groupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9835 Utf8Str newGroupPlusName = Utf8StrFmt("%s%c%s",
9836 newGroup.c_str(), RTPATH_DELIMITER, newName.c_str());
9837 /** @todo hack, make somehow use of ComposeMachineFilename */
9838 if (mUserData->s.fDirectoryIncludesUUID)
9839 newGroupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9840 configDir = configFile;
9841 configDir.stripFilename();
9842 newConfigDir = configDir;
9843 if ( configDir.length() >= groupPlusName.length()
9844 && !RTPathCompare(configDir.substr(configDir.length() - groupPlusName.length(), groupPlusName.length()).c_str(),
9845 groupPlusName.c_str()))
9846 {
9847 newConfigDir = newConfigDir.substr(0, configDir.length() - groupPlusName.length());
9848 Utf8Str newConfigBaseDir(newConfigDir);
9849 newConfigDir.append(newGroupPlusName);
9850 /* consistency: use \ if appropriate on the platform */
9851 RTPathChangeToDosSlashes(newConfigDir.mutableRaw(), false);
9852 /* new dir and old dir cannot be equal here because of 'if'
9853 * above and because name != newName */
9854 Assert(configDir != newConfigDir);
9855 if (!fSettingsFileIsNew)
9856 {
9857 /* perform real rename only if the machine is not new */
9858 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9859 if ( vrc == VERR_FILE_NOT_FOUND
9860 || vrc == VERR_PATH_NOT_FOUND)
9861 {
9862 /* create the parent directory, then retry renaming */
9863 Utf8Str parent(newConfigDir);
9864 parent.stripFilename();
9865 (void)RTDirCreateFullPath(parent.c_str(), 0700);
9866 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9867 }
9868 if (RT_FAILURE(vrc))
9869 {
9870 rc = setError(E_FAIL,
9871 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
9872 configDir.c_str(),
9873 newConfigDir.c_str(),
9874 vrc);
9875 break;
9876 }
9877 /* delete subdirectories which are no longer needed */
9878 Utf8Str dir(configDir);
9879 dir.stripFilename();
9880 while (dir != newConfigBaseDir && dir != ".")
9881 {
9882 vrc = RTDirRemove(dir.c_str());
9883 if (RT_FAILURE(vrc))
9884 break;
9885 dir.stripFilename();
9886 }
9887 dirRenamed = true;
9888 }
9889 }
9890
9891 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
9892 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
9893
9894 /* then try to rename the settings file itself */
9895 if (newConfigFile != configFile)
9896 {
9897 /* get the path to old settings file in renamed directory */
9898 configFile = Utf8StrFmt("%s%c%s",
9899 newConfigDir.c_str(),
9900 RTPATH_DELIMITER,
9901 RTPathFilename(configFile.c_str()));
9902 if (!fSettingsFileIsNew)
9903 {
9904 /* perform real rename only if the machine is not new */
9905 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
9906 if (RT_FAILURE(vrc))
9907 {
9908 rc = setError(E_FAIL,
9909 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
9910 configFile.c_str(),
9911 newConfigFile.c_str(),
9912 vrc);
9913 break;
9914 }
9915 fileRenamed = true;
9916 configFilePrev = configFile;
9917 configFilePrev += "-prev";
9918 newConfigFilePrev = newConfigFile;
9919 newConfigFilePrev += "-prev";
9920 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
9921 }
9922 }
9923
9924 // update m_strConfigFileFull amd mConfigFile
9925 mData->m_strConfigFileFull = newConfigFile;
9926 // compute the relative path too
9927 mParent->i_copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
9928
9929 // store the old and new so that VirtualBox::i_saveSettings() can update
9930 // the media registry
9931 if ( mData->mRegistered
9932 && (configDir != newConfigDir || configFile != newConfigFile))
9933 {
9934 mParent->i_rememberMachineNameChangeForMedia(configDir, newConfigDir);
9935
9936 if (pfNeedsGlobalSaveSettings)
9937 *pfNeedsGlobalSaveSettings = true;
9938 }
9939
9940 // in the saved state file path, replace the old directory with the new directory
9941 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
9942 {
9943 Utf8Str strStateFileName = mSSData->strStateFilePath.c_str() + configDir.length();
9944 mSSData->strStateFilePath = newConfigDir + strStateFileName;
9945 }
9946
9947 // and do the same thing for the saved state file paths of all the online snapshots
9948 if (mData->mFirstSnapshot)
9949 mData->mFirstSnapshot->i_updateSavedStatePaths(configDir.c_str(),
9950 newConfigDir.c_str());
9951 }
9952 while (0);
9953
9954 if (FAILED(rc))
9955 {
9956 /* silently try to rename everything back */
9957 if (fileRenamed)
9958 {
9959 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
9960 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
9961 }
9962 if (dirRenamed)
9963 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
9964 }
9965
9966 if (FAILED(rc)) return rc;
9967 }
9968
9969 if (fSettingsFileIsNew)
9970 {
9971 /* create a virgin config file */
9972 int vrc = VINF_SUCCESS;
9973
9974 /* ensure the settings directory exists */
9975 Utf8Str path(mData->m_strConfigFileFull);
9976 path.stripFilename();
9977 if (!RTDirExists(path.c_str()))
9978 {
9979 vrc = RTDirCreateFullPath(path.c_str(), 0700);
9980 if (RT_FAILURE(vrc))
9981 {
9982 return setError(E_FAIL,
9983 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
9984 path.c_str(),
9985 vrc);
9986 }
9987 }
9988
9989 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
9990 path = Utf8Str(mData->m_strConfigFileFull);
9991 RTFILE f = NIL_RTFILE;
9992 vrc = RTFileOpen(&f, path.c_str(),
9993 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
9994 if (RT_FAILURE(vrc))
9995 return setError(E_FAIL,
9996 tr("Could not create the settings file '%s' (%Rrc)"),
9997 path.c_str(),
9998 vrc);
9999 RTFileClose(f);
10000 }
10001
10002 return rc;
10003}
10004
10005/**
10006 * Saves and commits machine data, user data and hardware data.
10007 *
10008 * Note that on failure, the data remains uncommitted.
10009 *
10010 * @a aFlags may combine the following flags:
10011 *
10012 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
10013 * Used when saving settings after an operation that makes them 100%
10014 * correspond to the settings from the current snapshot.
10015 * - SaveS_Force: settings will be saved without doing a deep compare of the
10016 * settings structures. This is used when this is called because snapshots
10017 * have changed to avoid the overhead of the deep compare.
10018 *
10019 * @note Must be called from under this object's write lock. Locks children for
10020 * writing.
10021 *
10022 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
10023 * initialized to false and that will be set to true by this function if
10024 * the caller must invoke VirtualBox::i_saveSettings() because the global
10025 * settings have changed. This will happen if a machine rename has been
10026 * saved and the global machine and media registries will therefore need
10027 * updating.
10028 * @param aFlags Flags.
10029 */
10030HRESULT Machine::i_saveSettings(bool *pfNeedsGlobalSaveSettings,
10031 int aFlags /*= 0*/)
10032{
10033 LogFlowThisFuncEnter();
10034
10035 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10036
10037 /* make sure child objects are unable to modify the settings while we are
10038 * saving them */
10039 i_ensureNoStateDependencies();
10040
10041 AssertReturn(!i_isSnapshotMachine(),
10042 E_FAIL);
10043
10044 HRESULT rc = S_OK;
10045 bool fNeedsWrite = false;
10046
10047 /* First, prepare to save settings. It will care about renaming the
10048 * settings directory and file if the machine name was changed and about
10049 * creating a new settings file if this is a new machine. */
10050 rc = i_prepareSaveSettings(pfNeedsGlobalSaveSettings);
10051 if (FAILED(rc)) return rc;
10052
10053 // keep a pointer to the current settings structures
10054 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
10055 settings::MachineConfigFile *pNewConfig = NULL;
10056
10057 try
10058 {
10059 // make a fresh one to have everyone write stuff into
10060 pNewConfig = new settings::MachineConfigFile(NULL);
10061 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
10062
10063 // now go and copy all the settings data from COM to the settings structures
10064 // (this calls i_saveSettings() on all the COM objects in the machine)
10065 i_copyMachineDataToSettings(*pNewConfig);
10066
10067 if (aFlags & SaveS_ResetCurStateModified)
10068 {
10069 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
10070 mData->mCurrentStateModified = FALSE;
10071 fNeedsWrite = true; // always, no need to compare
10072 }
10073 else if (aFlags & SaveS_Force)
10074 {
10075 fNeedsWrite = true; // always, no need to compare
10076 }
10077 else
10078 {
10079 if (!mData->mCurrentStateModified)
10080 {
10081 // do a deep compare of the settings that we just saved with the settings
10082 // previously stored in the config file; this invokes MachineConfigFile::operator==
10083 // which does a deep compare of all the settings, which is expensive but less expensive
10084 // than writing out XML in vain
10085 bool fAnySettingsChanged = !(*pNewConfig == *pOldConfig);
10086
10087 // could still be modified if any settings changed
10088 mData->mCurrentStateModified = fAnySettingsChanged;
10089
10090 fNeedsWrite = fAnySettingsChanged;
10091 }
10092 else
10093 fNeedsWrite = true;
10094 }
10095
10096 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
10097
10098 if (fNeedsWrite)
10099 // now spit it all out!
10100 pNewConfig->write(mData->m_strConfigFileFull);
10101
10102 mData->pMachineConfigFile = pNewConfig;
10103 delete pOldConfig;
10104 i_commit();
10105
10106 // after saving settings, we are no longer different from the XML on disk
10107 mData->flModifications = 0;
10108 }
10109 catch (HRESULT err)
10110 {
10111 // we assume that error info is set by the thrower
10112 rc = err;
10113
10114 // restore old config
10115 delete pNewConfig;
10116 mData->pMachineConfigFile = pOldConfig;
10117 }
10118 catch (...)
10119 {
10120 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10121 }
10122
10123 if (fNeedsWrite)
10124 {
10125 /* Fire the data change event, even on failure (since we've already
10126 * committed all data). This is done only for SessionMachines because
10127 * mutable Machine instances are always not registered (i.e. private
10128 * to the client process that creates them) and thus don't need to
10129 * inform callbacks. */
10130 if (i_isSessionMachine())
10131 mParent->i_onMachineDataChange(mData->mUuid);
10132 }
10133
10134 LogFlowThisFunc(("rc=%08X\n", rc));
10135 LogFlowThisFuncLeave();
10136 return rc;
10137}
10138
10139/**
10140 * Implementation for saving the machine settings into the given
10141 * settings::MachineConfigFile instance. This copies machine extradata
10142 * from the previous machine config file in the instance data, if any.
10143 *
10144 * This gets called from two locations:
10145 *
10146 * -- Machine::i_saveSettings(), during the regular XML writing;
10147 *
10148 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
10149 * exported to OVF and we write the VirtualBox proprietary XML
10150 * into a <vbox:Machine> tag.
10151 *
10152 * This routine fills all the fields in there, including snapshots, *except*
10153 * for the following:
10154 *
10155 * -- fCurrentStateModified. There is some special logic associated with that.
10156 *
10157 * The caller can then call MachineConfigFile::write() or do something else
10158 * with it.
10159 *
10160 * Caller must hold the machine lock!
10161 *
10162 * This throws XML errors and HRESULT, so the caller must have a catch block!
10163 */
10164void Machine::i_copyMachineDataToSettings(settings::MachineConfigFile &config)
10165{
10166 // deep copy extradata, being extra careful with self assignment (the STL
10167 // map assignment on Mac OS X clang based Xcode isn't checking)
10168 if (&config != mData->pMachineConfigFile)
10169 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
10170
10171 config.uuid = mData->mUuid;
10172
10173 // copy name, description, OS type, teleport, UTC etc.
10174 config.machineUserData = mUserData->s;
10175
10176 if ( mData->mMachineState == MachineState_Saved
10177 || mData->mMachineState == MachineState_Restoring
10178 // when doing certain snapshot operations we may or may not have
10179 // a saved state in the current state, so keep everything as is
10180 || ( ( mData->mMachineState == MachineState_Snapshotting
10181 || mData->mMachineState == MachineState_DeletingSnapshot
10182 || mData->mMachineState == MachineState_RestoringSnapshot)
10183 && (!mSSData->strStateFilePath.isEmpty())
10184 )
10185 )
10186 {
10187 Assert(!mSSData->strStateFilePath.isEmpty());
10188 /* try to make the file name relative to the settings file dir */
10189 i_copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
10190 }
10191 else
10192 {
10193 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
10194 config.strStateFile.setNull();
10195 }
10196
10197 if (mData->mCurrentSnapshot)
10198 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->i_getId();
10199 else
10200 config.uuidCurrentSnapshot.clear();
10201
10202 config.timeLastStateChange = mData->mLastStateChange;
10203 config.fAborted = (mData->mMachineState == MachineState_Aborted);
10204 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
10205
10206 HRESULT rc = i_saveHardware(config.hardwareMachine, &config.debugging, &config.autostart);
10207 if (FAILED(rc)) throw rc;
10208
10209 // save machine's media registry if this is VirtualBox 4.0 or later
10210 if (config.canHaveOwnMediaRegistry())
10211 {
10212 // determine machine folder
10213 Utf8Str strMachineFolder = i_getSettingsFileFull();
10214 strMachineFolder.stripFilename();
10215 mParent->i_saveMediaRegistry(config.mediaRegistry,
10216 i_getId(), // only media with registry ID == machine UUID
10217 strMachineFolder);
10218 // this throws HRESULT
10219 }
10220
10221 // save snapshots
10222 rc = i_saveAllSnapshots(config);
10223 if (FAILED(rc)) throw rc;
10224}
10225
10226/**
10227 * Saves all snapshots of the machine into the given machine config file. Called
10228 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
10229 * @param config
10230 * @return
10231 */
10232HRESULT Machine::i_saveAllSnapshots(settings::MachineConfigFile &config)
10233{
10234 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10235
10236 HRESULT rc = S_OK;
10237
10238 try
10239 {
10240 config.llFirstSnapshot.clear();
10241
10242 if (mData->mFirstSnapshot)
10243 {
10244 // the settings use a list for "the first snapshot"
10245 config.llFirstSnapshot.push_back(settings::Snapshot::Empty);
10246
10247 // get reference to the snapshot on the list and work on that
10248 // element straight in the list to avoid excessive copying later
10249 rc = mData->mFirstSnapshot->i_saveSnapshot(config.llFirstSnapshot.back());
10250 if (FAILED(rc)) throw rc;
10251 }
10252
10253// if (mType == IsSessionMachine)
10254// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
10255
10256 }
10257 catch (HRESULT err)
10258 {
10259 /* we assume that error info is set by the thrower */
10260 rc = err;
10261 }
10262 catch (...)
10263 {
10264 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10265 }
10266
10267 return rc;
10268}
10269
10270/**
10271 * Saves the VM hardware configuration. It is assumed that the
10272 * given node is empty.
10273 *
10274 * @param data Reference to the settings object for the hardware config.
10275 * @param pDbg Pointer to the settings object for the debugging config
10276 * which happens to live in mHWData.
10277 * @param pAutostart Pointer to the settings object for the autostart config
10278 * which happens to live in mHWData.
10279 */
10280HRESULT Machine::i_saveHardware(settings::Hardware &data, settings::Debugging *pDbg,
10281 settings::Autostart *pAutostart)
10282{
10283 HRESULT rc = S_OK;
10284
10285 try
10286 {
10287 /* The hardware version attribute (optional).
10288 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
10289 if ( mHWData->mHWVersion == "1"
10290 && mSSData->strStateFilePath.isEmpty()
10291 )
10292 mHWData->mHWVersion = "2"; /** @todo Is this safe, to update mHWVersion here? If not some
10293 other point needs to be found where this can be done. */
10294
10295 data.strVersion = mHWData->mHWVersion;
10296 data.uuid = mHWData->mHardwareUUID;
10297
10298 // CPU
10299 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
10300 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
10301 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
10302 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
10303 data.fUnrestrictedExecution = !!mHWData->mHWVirtExUXEnabled;
10304 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
10305 data.fPAE = !!mHWData->mPAEEnabled;
10306 data.enmLongMode = mHWData->mLongMode;
10307 data.fTripleFaultReset = !!mHWData->mTripleFaultReset;
10308 data.fAPIC = !!mHWData->mAPIC;
10309 data.fX2APIC = !!mHWData->mX2APIC;
10310 data.cCPUs = mHWData->mCPUCount;
10311 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
10312 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
10313 data.uCpuIdPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
10314 data.strCpuProfile = mHWData->mCpuProfile;
10315
10316 data.llCpus.clear();
10317 if (data.fCpuHotPlug)
10318 {
10319 for (unsigned idx = 0; idx < data.cCPUs; ++idx)
10320 {
10321 if (mHWData->mCPUAttached[idx])
10322 {
10323 settings::Cpu cpu;
10324 cpu.ulId = idx;
10325 data.llCpus.push_back(cpu);
10326 }
10327 }
10328 }
10329
10330 /* Standard and Extended CPUID leafs. */
10331 data.llCpuIdLeafs.clear();
10332 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++idx)
10333 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
10334 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
10335 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++idx)
10336 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
10337 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
10338
10339 // memory
10340 data.ulMemorySizeMB = mHWData->mMemorySize;
10341 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
10342
10343 // firmware
10344 data.firmwareType = mHWData->mFirmwareType;
10345
10346 // HID
10347 data.pointingHIDType = mHWData->mPointingHIDType;
10348 data.keyboardHIDType = mHWData->mKeyboardHIDType;
10349
10350 // chipset
10351 data.chipsetType = mHWData->mChipsetType;
10352
10353 // paravirt
10354 data.paravirtProvider = mHWData->mParavirtProvider;
10355 data.strParavirtDebug = mHWData->mParavirtDebug;
10356
10357 // emulated USB card reader
10358 data.fEmulatedUSBCardReader = !!mHWData->mEmulatedUSBCardReaderEnabled;
10359
10360 // HPET
10361 data.fHPETEnabled = !!mHWData->mHPETEnabled;
10362
10363 // boot order
10364 data.mapBootOrder.clear();
10365 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
10366 data.mapBootOrder[i] = mHWData->mBootOrder[i];
10367
10368 // display
10369 data.graphicsControllerType = mHWData->mGraphicsControllerType;
10370 data.ulVRAMSizeMB = mHWData->mVRAMSize;
10371 data.cMonitors = mHWData->mMonitorCount;
10372 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
10373 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
10374 data.ulVideoCaptureHorzRes = mHWData->mVideoCaptureWidth;
10375 data.ulVideoCaptureVertRes = mHWData->mVideoCaptureHeight;
10376 data.ulVideoCaptureRate = mHWData->mVideoCaptureRate;
10377 data.ulVideoCaptureFPS = mHWData->mVideoCaptureFPS;
10378 data.fVideoCaptureEnabled = !!mHWData->mVideoCaptureEnabled;
10379 for (unsigned i = 0; i < sizeof(data.u64VideoCaptureScreens) * 8; ++i)
10380 {
10381 if (mHWData->maVideoCaptureScreens[i])
10382 ASMBitSet(&data.u64VideoCaptureScreens, i);
10383 else
10384 ASMBitClear(&data.u64VideoCaptureScreens, i);
10385 }
10386 /* store relative video capture file if possible */
10387 i_copyPathRelativeToMachine(mHWData->mVideoCaptureFile, data.strVideoCaptureFile);
10388
10389 /* VRDEServer settings (optional) */
10390 rc = mVRDEServer->i_saveSettings(data.vrdeSettings);
10391 if (FAILED(rc)) throw rc;
10392
10393 /* BIOS (required) */
10394 rc = mBIOSSettings->i_saveSettings(data.biosSettings);
10395 if (FAILED(rc)) throw rc;
10396
10397 /* USB Controller (required) */
10398 data.usbSettings.llUSBControllers.clear();
10399 for (USBControllerList::const_iterator
10400 it = mUSBControllers->begin();
10401 it != mUSBControllers->end();
10402 ++it)
10403 {
10404 ComObjPtr<USBController> ctrl = *it;
10405 settings::USBController settingsCtrl;
10406
10407 settingsCtrl.strName = ctrl->i_getName();
10408 settingsCtrl.enmType = ctrl->i_getControllerType();
10409
10410 data.usbSettings.llUSBControllers.push_back(settingsCtrl);
10411 }
10412
10413 /* USB device filters (required) */
10414 rc = mUSBDeviceFilters->i_saveSettings(data.usbSettings);
10415 if (FAILED(rc)) throw rc;
10416
10417 /* Network adapters (required) */
10418 size_t uMaxNICs = RT_MIN(Global::getMaxNetworkAdapters(mHWData->mChipsetType), mNetworkAdapters.size());
10419 data.llNetworkAdapters.clear();
10420 /* Write out only the nominal number of network adapters for this
10421 * chipset type. Since Machine::commit() hasn't been called there
10422 * may be extra NIC settings in the vector. */
10423 for (size_t slot = 0; slot < uMaxNICs; ++slot)
10424 {
10425 settings::NetworkAdapter nic;
10426 nic.ulSlot = (uint32_t)slot;
10427 /* paranoia check... must not be NULL, but must not crash either. */
10428 if (mNetworkAdapters[slot])
10429 {
10430 if (mNetworkAdapters[slot]->i_hasDefaults())
10431 continue;
10432
10433 rc = mNetworkAdapters[slot]->i_saveSettings(nic);
10434 if (FAILED(rc)) throw rc;
10435
10436 data.llNetworkAdapters.push_back(nic);
10437 }
10438 }
10439
10440 /* Serial ports */
10441 data.llSerialPorts.clear();
10442 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
10443 {
10444 if (mSerialPorts[slot]->i_hasDefaults())
10445 continue;
10446
10447 settings::SerialPort s;
10448 s.ulSlot = slot;
10449 rc = mSerialPorts[slot]->i_saveSettings(s);
10450 if (FAILED(rc)) return rc;
10451
10452 data.llSerialPorts.push_back(s);
10453 }
10454
10455 /* Parallel ports */
10456 data.llParallelPorts.clear();
10457 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
10458 {
10459 if (mParallelPorts[slot]->i_hasDefaults())
10460 continue;
10461
10462 settings::ParallelPort p;
10463 p.ulSlot = slot;
10464 rc = mParallelPorts[slot]->i_saveSettings(p);
10465 if (FAILED(rc)) return rc;
10466
10467 data.llParallelPorts.push_back(p);
10468 }
10469
10470 /* Audio adapter */
10471 rc = mAudioAdapter->i_saveSettings(data.audioAdapter);
10472 if (FAILED(rc)) return rc;
10473
10474 rc = i_saveStorageControllers(data.storage);
10475 if (FAILED(rc)) return rc;
10476
10477 /* Shared folders */
10478 data.llSharedFolders.clear();
10479 for (HWData::SharedFolderList::const_iterator
10480 it = mHWData->mSharedFolders.begin();
10481 it != mHWData->mSharedFolders.end();
10482 ++it)
10483 {
10484 SharedFolder *pSF = *it;
10485 AutoCaller sfCaller(pSF);
10486 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
10487 settings::SharedFolder sf;
10488 sf.strName = pSF->i_getName();
10489 sf.strHostPath = pSF->i_getHostPath();
10490 sf.fWritable = !!pSF->i_isWritable();
10491 sf.fAutoMount = !!pSF->i_isAutoMounted();
10492
10493 data.llSharedFolders.push_back(sf);
10494 }
10495
10496 // clipboard
10497 data.clipboardMode = mHWData->mClipboardMode;
10498
10499 // drag'n'drop
10500 data.dndMode = mHWData->mDnDMode;
10501
10502 /* Guest */
10503 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
10504
10505 // IO settings
10506 data.ioSettings.fIOCacheEnabled = !!mHWData->mIOCacheEnabled;
10507 data.ioSettings.ulIOCacheSize = mHWData->mIOCacheSize;
10508
10509 /* BandwidthControl (required) */
10510 rc = mBandwidthControl->i_saveSettings(data.ioSettings);
10511 if (FAILED(rc)) throw rc;
10512
10513 /* Host PCI devices */
10514 data.pciAttachments.clear();
10515 for (HWData::PCIDeviceAssignmentList::const_iterator
10516 it = mHWData->mPCIDeviceAssignments.begin();
10517 it != mHWData->mPCIDeviceAssignments.end();
10518 ++it)
10519 {
10520 ComObjPtr<PCIDeviceAttachment> pda = *it;
10521 settings::HostPCIDeviceAttachment hpda;
10522
10523 rc = pda->i_saveSettings(hpda);
10524 if (FAILED(rc)) throw rc;
10525
10526 data.pciAttachments.push_back(hpda);
10527 }
10528
10529 // guest properties
10530 data.llGuestProperties.clear();
10531#ifdef VBOX_WITH_GUEST_PROPS
10532 for (HWData::GuestPropertyMap::const_iterator
10533 it = mHWData->mGuestProperties.begin();
10534 it != mHWData->mGuestProperties.end();
10535 ++it)
10536 {
10537 HWData::GuestProperty property = it->second;
10538
10539 /* Remove transient guest properties at shutdown unless we
10540 * are saving state. Note that restoring snapshot intentionally
10541 * keeps them, they will be removed if appropriate once the final
10542 * machine state is set (as crashes etc. need to work). */
10543 if ( ( mData->mMachineState == MachineState_PoweredOff
10544 || mData->mMachineState == MachineState_Aborted
10545 || mData->mMachineState == MachineState_Teleported)
10546 && ( property.mFlags & guestProp::TRANSIENT
10547 || property.mFlags & guestProp::TRANSRESET))
10548 continue;
10549 settings::GuestProperty prop;
10550 prop.strName = it->first;
10551 prop.strValue = property.strValue;
10552 prop.timestamp = property.mTimestamp;
10553 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
10554 guestProp::writeFlags(property.mFlags, szFlags);
10555 prop.strFlags = szFlags;
10556
10557 data.llGuestProperties.push_back(prop);
10558 }
10559
10560 /* I presume this doesn't require a backup(). */
10561 mData->mGuestPropertiesModified = FALSE;
10562#endif /* VBOX_WITH_GUEST_PROPS defined */
10563
10564 *pDbg = mHWData->mDebugging;
10565 *pAutostart = mHWData->mAutostart;
10566
10567 data.strDefaultFrontend = mHWData->mDefaultFrontend;
10568 }
10569 catch (std::bad_alloc &)
10570 {
10571 return E_OUTOFMEMORY;
10572 }
10573
10574 AssertComRC(rc);
10575 return rc;
10576}
10577
10578/**
10579 * Saves the storage controller configuration.
10580 *
10581 * @param data storage settings.
10582 */
10583HRESULT Machine::i_saveStorageControllers(settings::Storage &data)
10584{
10585 data.llStorageControllers.clear();
10586
10587 for (StorageControllerList::const_iterator
10588 it = mStorageControllers->begin();
10589 it != mStorageControllers->end();
10590 ++it)
10591 {
10592 HRESULT rc;
10593 ComObjPtr<StorageController> pCtl = *it;
10594
10595 settings::StorageController ctl;
10596 ctl.strName = pCtl->i_getName();
10597 ctl.controllerType = pCtl->i_getControllerType();
10598 ctl.storageBus = pCtl->i_getStorageBus();
10599 ctl.ulInstance = pCtl->i_getInstance();
10600 ctl.fBootable = pCtl->i_getBootable();
10601
10602 /* Save the port count. */
10603 ULONG portCount;
10604 rc = pCtl->COMGETTER(PortCount)(&portCount);
10605 ComAssertComRCRet(rc, rc);
10606 ctl.ulPortCount = portCount;
10607
10608 /* Save fUseHostIOCache */
10609 BOOL fUseHostIOCache;
10610 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
10611 ComAssertComRCRet(rc, rc);
10612 ctl.fUseHostIOCache = !!fUseHostIOCache;
10613
10614 /* save the devices now. */
10615 rc = i_saveStorageDevices(pCtl, ctl);
10616 ComAssertComRCRet(rc, rc);
10617
10618 data.llStorageControllers.push_back(ctl);
10619 }
10620
10621 return S_OK;
10622}
10623
10624/**
10625 * Saves the hard disk configuration.
10626 */
10627HRESULT Machine::i_saveStorageDevices(ComObjPtr<StorageController> aStorageController,
10628 settings::StorageController &data)
10629{
10630 MediumAttachmentList atts;
10631
10632 HRESULT rc = i_getMediumAttachmentsOfController(aStorageController->i_getName(), atts);
10633 if (FAILED(rc)) return rc;
10634
10635 data.llAttachedDevices.clear();
10636 for (MediumAttachmentList::const_iterator
10637 it = atts.begin();
10638 it != atts.end();
10639 ++it)
10640 {
10641 settings::AttachedDevice dev;
10642 IMediumAttachment *iA = *it;
10643 MediumAttachment *pAttach = static_cast<MediumAttachment *>(iA);
10644 Medium *pMedium = pAttach->i_getMedium();
10645
10646 dev.deviceType = pAttach->i_getType();
10647 dev.lPort = pAttach->i_getPort();
10648 dev.lDevice = pAttach->i_getDevice();
10649 dev.fPassThrough = pAttach->i_getPassthrough();
10650 dev.fHotPluggable = pAttach->i_getHotPluggable();
10651 if (pMedium)
10652 {
10653 if (pMedium->i_isHostDrive())
10654 dev.strHostDriveSrc = pMedium->i_getLocationFull();
10655 else
10656 dev.uuid = pMedium->i_getId();
10657 dev.fTempEject = pAttach->i_getTempEject();
10658 dev.fNonRotational = pAttach->i_getNonRotational();
10659 dev.fDiscard = pAttach->i_getDiscard();
10660 }
10661
10662 dev.strBwGroup = pAttach->i_getBandwidthGroup();
10663
10664 data.llAttachedDevices.push_back(dev);
10665 }
10666
10667 return S_OK;
10668}
10669
10670/**
10671 * Saves machine state settings as defined by aFlags
10672 * (SaveSTS_* values).
10673 *
10674 * @param aFlags Combination of SaveSTS_* flags.
10675 *
10676 * @note Locks objects for writing.
10677 */
10678HRESULT Machine::i_saveStateSettings(int aFlags)
10679{
10680 if (aFlags == 0)
10681 return S_OK;
10682
10683 AutoCaller autoCaller(this);
10684 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10685
10686 /* This object's write lock is also necessary to serialize file access
10687 * (prevent concurrent reads and writes) */
10688 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10689
10690 HRESULT rc = S_OK;
10691
10692 Assert(mData->pMachineConfigFile);
10693
10694 try
10695 {
10696 if (aFlags & SaveSTS_CurStateModified)
10697 mData->pMachineConfigFile->fCurrentStateModified = true;
10698
10699 if (aFlags & SaveSTS_StateFilePath)
10700 {
10701 if (!mSSData->strStateFilePath.isEmpty())
10702 /* try to make the file name relative to the settings file dir */
10703 i_copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
10704 else
10705 mData->pMachineConfigFile->strStateFile.setNull();
10706 }
10707
10708 if (aFlags & SaveSTS_StateTimeStamp)
10709 {
10710 Assert( mData->mMachineState != MachineState_Aborted
10711 || mSSData->strStateFilePath.isEmpty());
10712
10713 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
10714
10715 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
10716/// @todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
10717 }
10718
10719 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
10720 }
10721 catch (...)
10722 {
10723 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10724 }
10725
10726 return rc;
10727}
10728
10729/**
10730 * Ensures that the given medium is added to a media registry. If this machine
10731 * was created with 4.0 or later, then the machine registry is used. Otherwise
10732 * the global VirtualBox media registry is used.
10733 *
10734 * Caller must NOT hold machine lock, media tree or any medium locks!
10735 *
10736 * @param pMedium
10737 */
10738void Machine::i_addMediumToRegistry(ComObjPtr<Medium> &pMedium)
10739{
10740 /* Paranoia checks: do not hold machine or media tree locks. */
10741 AssertReturnVoid(!isWriteLockOnCurrentThread());
10742 AssertReturnVoid(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
10743
10744 ComObjPtr<Medium> pBase;
10745 {
10746 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10747 pBase = pMedium->i_getBase();
10748 }
10749
10750 /* Paranoia checks: do not hold medium locks. */
10751 AssertReturnVoid(!pMedium->isWriteLockOnCurrentThread());
10752 AssertReturnVoid(!pBase->isWriteLockOnCurrentThread());
10753
10754 // decide which medium registry to use now that the medium is attached:
10755 Guid uuid;
10756 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
10757 // machine XML is VirtualBox 4.0 or higher:
10758 uuid = i_getId(); // machine UUID
10759 else
10760 uuid = mParent->i_getGlobalRegistryId(); // VirtualBox global registry UUID
10761
10762 if (pMedium->i_addRegistry(uuid))
10763 mParent->i_markRegistryModified(uuid);
10764
10765 /* For more complex hard disk structures it can happen that the base
10766 * medium isn't yet associated with any medium registry. Do that now. */
10767 if (pMedium != pBase)
10768 {
10769 /* Tree lock needed by Medium::addRegistry when recursing. */
10770 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10771 if (pBase->i_addRegistryRecursive(uuid))
10772 {
10773 treeLock.release();
10774 mParent->i_markRegistryModified(uuid);
10775 }
10776 }
10777}
10778
10779/**
10780 * Creates differencing hard disks for all normal hard disks attached to this
10781 * machine and a new set of attachments to refer to created disks.
10782 *
10783 * Used when taking a snapshot or when deleting the current state. Gets called
10784 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
10785 *
10786 * This method assumes that mMediumAttachments contains the original hard disk
10787 * attachments it needs to create diffs for. On success, these attachments will
10788 * be replaced with the created diffs.
10789 *
10790 * Attachments with non-normal hard disks are left as is.
10791 *
10792 * If @a aOnline is @c false then the original hard disks that require implicit
10793 * diffs will be locked for reading. Otherwise it is assumed that they are
10794 * already locked for writing (when the VM was started). Note that in the latter
10795 * case it is responsibility of the caller to lock the newly created diffs for
10796 * writing if this method succeeds.
10797 *
10798 * @param aProgress Progress object to run (must contain at least as
10799 * many operations left as the number of hard disks
10800 * attached).
10801 * @param aWeight Weight of this operation.
10802 * @param aOnline Whether the VM was online prior to this operation.
10803 *
10804 * @note The progress object is not marked as completed, neither on success nor
10805 * on failure. This is a responsibility of the caller.
10806 *
10807 * @note Locks this object and the media tree for writing.
10808 */
10809HRESULT Machine::i_createImplicitDiffs(IProgress *aProgress,
10810 ULONG aWeight,
10811 bool aOnline)
10812{
10813 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10814
10815 AutoCaller autoCaller(this);
10816 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10817
10818 AutoMultiWriteLock2 alock(this->lockHandle(),
10819 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10820
10821 /* must be in a protective state because we release the lock below */
10822 AssertReturn( mData->mMachineState == MachineState_Snapshotting
10823 || mData->mMachineState == MachineState_OnlineSnapshotting
10824 || mData->mMachineState == MachineState_LiveSnapshotting
10825 || mData->mMachineState == MachineState_RestoringSnapshot
10826 || mData->mMachineState == MachineState_DeletingSnapshot
10827 , E_FAIL);
10828
10829 HRESULT rc = S_OK;
10830
10831 // use appropriate locked media map (online or offline)
10832 MediumLockListMap lockedMediaOffline;
10833 MediumLockListMap *lockedMediaMap;
10834 if (aOnline)
10835 lockedMediaMap = &mData->mSession.mLockedMedia;
10836 else
10837 lockedMediaMap = &lockedMediaOffline;
10838
10839 try
10840 {
10841 if (!aOnline)
10842 {
10843 /* lock all attached hard disks early to detect "in use"
10844 * situations before creating actual diffs */
10845 for (MediumAttachmentList::const_iterator
10846 it = mMediumAttachments->begin();
10847 it != mMediumAttachments->end();
10848 ++it)
10849 {
10850 MediumAttachment *pAtt = *it;
10851 if (pAtt->i_getType() == DeviceType_HardDisk)
10852 {
10853 Medium *pMedium = pAtt->i_getMedium();
10854 Assert(pMedium);
10855
10856 MediumLockList *pMediumLockList(new MediumLockList());
10857 alock.release();
10858 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
10859 NULL /* pToLockWrite */,
10860 false /* fMediumLockWriteAll */,
10861 NULL,
10862 *pMediumLockList);
10863 alock.acquire();
10864 if (FAILED(rc))
10865 {
10866 delete pMediumLockList;
10867 throw rc;
10868 }
10869 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10870 if (FAILED(rc))
10871 {
10872 throw setError(rc,
10873 tr("Collecting locking information for all attached media failed"));
10874 }
10875 }
10876 }
10877
10878 /* Now lock all media. If this fails, nothing is locked. */
10879 alock.release();
10880 rc = lockedMediaMap->Lock();
10881 alock.acquire();
10882 if (FAILED(rc))
10883 {
10884 throw setError(rc,
10885 tr("Locking of attached media failed"));
10886 }
10887 }
10888
10889 /* remember the current list (note that we don't use backup() since
10890 * mMediumAttachments may be already backed up) */
10891 MediumAttachmentList atts = *mMediumAttachments.data();
10892
10893 /* start from scratch */
10894 mMediumAttachments->clear();
10895
10896 /* go through remembered attachments and create diffs for normal hard
10897 * disks and attach them */
10898 for (MediumAttachmentList::const_iterator
10899 it = atts.begin();
10900 it != atts.end();
10901 ++it)
10902 {
10903 MediumAttachment *pAtt = *it;
10904
10905 DeviceType_T devType = pAtt->i_getType();
10906 Medium *pMedium = pAtt->i_getMedium();
10907
10908 if ( devType != DeviceType_HardDisk
10909 || pMedium == NULL
10910 || pMedium->i_getType() != MediumType_Normal)
10911 {
10912 /* copy the attachment as is */
10913
10914 /** @todo the progress object created in SessionMachine::TakeSnaphot
10915 * only expects operations for hard disks. Later other
10916 * device types need to show up in the progress as well. */
10917 if (devType == DeviceType_HardDisk)
10918 {
10919 if (pMedium == NULL)
10920 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
10921 aWeight); // weight
10922 else
10923 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
10924 pMedium->i_getBase()->i_getName().c_str()).raw(),
10925 aWeight); // weight
10926 }
10927
10928 mMediumAttachments->push_back(pAtt);
10929 continue;
10930 }
10931
10932 /* need a diff */
10933 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
10934 pMedium->i_getBase()->i_getName().c_str()).raw(),
10935 aWeight); // weight
10936
10937 Utf8Str strFullSnapshotFolder;
10938 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10939
10940 ComObjPtr<Medium> diff;
10941 diff.createObject();
10942 // store the diff in the same registry as the parent
10943 // (this cannot fail here because we can't create implicit diffs for
10944 // unregistered images)
10945 Guid uuidRegistryParent;
10946 bool fInRegistry = pMedium->i_getFirstRegistryMachineId(uuidRegistryParent);
10947 Assert(fInRegistry); NOREF(fInRegistry);
10948 rc = diff->init(mParent,
10949 pMedium->i_getPreferredDiffFormat(),
10950 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
10951 uuidRegistryParent,
10952 DeviceType_HardDisk);
10953 if (FAILED(rc)) throw rc;
10954
10955 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
10956 * the push_back? Looks like we're going to release medium with the
10957 * wrong kind of lock (general issue with if we fail anywhere at all)
10958 * and an orphaned VDI in the snapshots folder. */
10959
10960 /* update the appropriate lock list */
10961 MediumLockList *pMediumLockList;
10962 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
10963 AssertComRCThrowRC(rc);
10964 if (aOnline)
10965 {
10966 alock.release();
10967 /* The currently attached medium will be read-only, change
10968 * the lock type to read. */
10969 rc = pMediumLockList->Update(pMedium, false);
10970 alock.acquire();
10971 AssertComRCThrowRC(rc);
10972 }
10973
10974 /* release the locks before the potentially lengthy operation */
10975 alock.release();
10976 rc = pMedium->i_createDiffStorage(diff,
10977 pMedium->i_getPreferredDiffVariant(),
10978 pMediumLockList,
10979 NULL /* aProgress */,
10980 true /* aWait */);
10981 alock.acquire();
10982 if (FAILED(rc)) throw rc;
10983
10984 /* actual lock list update is done in Machine::i_commitMedia */
10985
10986 rc = diff->i_addBackReference(mData->mUuid);
10987 AssertComRCThrowRC(rc);
10988
10989 /* add a new attachment */
10990 ComObjPtr<MediumAttachment> attachment;
10991 attachment.createObject();
10992 rc = attachment->init(this,
10993 diff,
10994 pAtt->i_getControllerName(),
10995 pAtt->i_getPort(),
10996 pAtt->i_getDevice(),
10997 DeviceType_HardDisk,
10998 true /* aImplicit */,
10999 false /* aPassthrough */,
11000 false /* aTempEject */,
11001 pAtt->i_getNonRotational(),
11002 pAtt->i_getDiscard(),
11003 pAtt->i_getHotPluggable(),
11004 pAtt->i_getBandwidthGroup());
11005 if (FAILED(rc)) throw rc;
11006
11007 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
11008 AssertComRCThrowRC(rc);
11009 mMediumAttachments->push_back(attachment);
11010 }
11011 }
11012 catch (HRESULT aRC) { rc = aRC; }
11013
11014 /* unlock all hard disks we locked when there is no VM */
11015 if (!aOnline)
11016 {
11017 ErrorInfoKeeper eik;
11018
11019 HRESULT rc1 = lockedMediaMap->Clear();
11020 AssertComRC(rc1);
11021 }
11022
11023 return rc;
11024}
11025
11026/**
11027 * Deletes implicit differencing hard disks created either by
11028 * #i_createImplicitDiffs() or by #attachDevice() and rolls back
11029 * mMediumAttachments.
11030 *
11031 * Note that to delete hard disks created by #attachDevice() this method is
11032 * called from #i_rollbackMedia() when the changes are rolled back.
11033 *
11034 * @note Locks this object and the media tree for writing.
11035 */
11036HRESULT Machine::i_deleteImplicitDiffs(bool aOnline)
11037{
11038 LogFlowThisFunc(("aOnline=%d\n", aOnline));
11039
11040 AutoCaller autoCaller(this);
11041 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11042
11043 AutoMultiWriteLock2 alock(this->lockHandle(),
11044 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
11045
11046 /* We absolutely must have backed up state. */
11047 AssertReturn(mMediumAttachments.isBackedUp(), E_FAIL);
11048
11049 /* Check if there are any implicitly created diff images. */
11050 bool fImplicitDiffs = false;
11051 for (MediumAttachmentList::const_iterator
11052 it = mMediumAttachments->begin();
11053 it != mMediumAttachments->end();
11054 ++it)
11055 {
11056 const ComObjPtr<MediumAttachment> &pAtt = *it;
11057 if (pAtt->i_isImplicit())
11058 {
11059 fImplicitDiffs = true;
11060 break;
11061 }
11062 }
11063 /* If there is nothing to do, leave early. This saves lots of image locking
11064 * effort. It also avoids a MachineStateChanged event without real reason.
11065 * This is important e.g. when loading a VM config, because there should be
11066 * no events. Otherwise API clients can become thoroughly confused for
11067 * inaccessible VMs (the code for loading VM configs uses this method for
11068 * cleanup if the config makes no sense), as they take such events as an
11069 * indication that the VM is alive, and they would force the VM config to
11070 * be reread, leading to an endless loop. */
11071 if (!fImplicitDiffs)
11072 return S_OK;
11073
11074 HRESULT rc = S_OK;
11075 MachineState_T oldState = mData->mMachineState;
11076
11077 /* will release the lock before the potentially lengthy operation,
11078 * so protect with the special state (unless already protected) */
11079 if ( oldState != MachineState_Snapshotting
11080 && oldState != MachineState_OnlineSnapshotting
11081 && oldState != MachineState_LiveSnapshotting
11082 && oldState != MachineState_RestoringSnapshot
11083 && oldState != MachineState_DeletingSnapshot
11084 && oldState != MachineState_DeletingSnapshotOnline
11085 && oldState != MachineState_DeletingSnapshotPaused
11086 )
11087 i_setMachineState(MachineState_SettingUp);
11088
11089 // use appropriate locked media map (online or offline)
11090 MediumLockListMap lockedMediaOffline;
11091 MediumLockListMap *lockedMediaMap;
11092 if (aOnline)
11093 lockedMediaMap = &mData->mSession.mLockedMedia;
11094 else
11095 lockedMediaMap = &lockedMediaOffline;
11096
11097 try
11098 {
11099 if (!aOnline)
11100 {
11101 /* lock all attached hard disks early to detect "in use"
11102 * situations before deleting actual diffs */
11103 for (MediumAttachmentList::const_iterator
11104 it = mMediumAttachments->begin();
11105 it != mMediumAttachments->end();
11106 ++it)
11107 {
11108 MediumAttachment *pAtt = *it;
11109 if (pAtt->i_getType() == DeviceType_HardDisk)
11110 {
11111 Medium *pMedium = pAtt->i_getMedium();
11112 Assert(pMedium);
11113
11114 MediumLockList *pMediumLockList(new MediumLockList());
11115 alock.release();
11116 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
11117 NULL /* pToLockWrite */,
11118 false /* fMediumLockWriteAll */,
11119 NULL,
11120 *pMediumLockList);
11121 alock.acquire();
11122
11123 if (FAILED(rc))
11124 {
11125 delete pMediumLockList;
11126 throw rc;
11127 }
11128
11129 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
11130 if (FAILED(rc))
11131 throw rc;
11132 }
11133 }
11134
11135 if (FAILED(rc))
11136 throw rc;
11137 } // end of offline
11138
11139 /* Lock lists are now up to date and include implicitly created media */
11140
11141 /* Go through remembered attachments and delete all implicitly created
11142 * diffs and fix up the attachment information */
11143 const MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
11144 MediumAttachmentList implicitAtts;
11145 for (MediumAttachmentList::const_iterator
11146 it = mMediumAttachments->begin();
11147 it != mMediumAttachments->end();
11148 ++it)
11149 {
11150 ComObjPtr<MediumAttachment> pAtt = *it;
11151 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11152 if (pMedium.isNull())
11153 continue;
11154
11155 // Implicit attachments go on the list for deletion and back references are removed.
11156 if (pAtt->i_isImplicit())
11157 {
11158 /* Deassociate and mark for deletion */
11159 LogFlowThisFunc(("Detaching '%s', pending deletion\n", pAtt->i_getLogName()));
11160 rc = pMedium->i_removeBackReference(mData->mUuid);
11161 if (FAILED(rc))
11162 throw rc;
11163 implicitAtts.push_back(pAtt);
11164 continue;
11165 }
11166
11167 /* Was this medium attached before? */
11168 if (!i_findAttachment(oldAtts, pMedium))
11169 {
11170 /* no: de-associate */
11171 LogFlowThisFunc(("Detaching '%s', no deletion\n", pAtt->i_getLogName()));
11172 rc = pMedium->i_removeBackReference(mData->mUuid);
11173 if (FAILED(rc))
11174 throw rc;
11175 continue;
11176 }
11177 LogFlowThisFunc(("Not detaching '%s'\n", pAtt->i_getLogName()));
11178 }
11179
11180 /* If there are implicit attachments to delete, throw away the lock
11181 * map contents (which will unlock all media) since the medium
11182 * attachments will be rolled back. Below we need to completely
11183 * recreate the lock map anyway since it is infinitely complex to
11184 * do this incrementally (would need reconstructing each attachment
11185 * change, which would be extremely hairy). */
11186 if (implicitAtts.size() != 0)
11187 {
11188 ErrorInfoKeeper eik;
11189
11190 HRESULT rc1 = lockedMediaMap->Clear();
11191 AssertComRC(rc1);
11192 }
11193
11194 /* rollback hard disk changes */
11195 mMediumAttachments.rollback();
11196
11197 MultiResult mrc(S_OK);
11198
11199 // Delete unused implicit diffs.
11200 if (implicitAtts.size() != 0)
11201 {
11202 alock.release();
11203
11204 for (MediumAttachmentList::const_iterator
11205 it = implicitAtts.begin();
11206 it != implicitAtts.end();
11207 ++it)
11208 {
11209 // Remove medium associated with this attachment.
11210 ComObjPtr<MediumAttachment> pAtt = *it;
11211 Assert(pAtt);
11212 LogFlowThisFunc(("Deleting '%s'\n", pAtt->i_getLogName()));
11213 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11214 Assert(pMedium);
11215
11216 rc = pMedium->i_deleteStorage(NULL /*aProgress*/, true /*aWait*/);
11217 // continue on delete failure, just collect error messages
11218 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, pAtt->i_getLogName(),
11219 pMedium->i_getLocationFull().c_str() ));
11220 mrc = rc;
11221 }
11222 // Clear the list of deleted implicit attachments now, while not
11223 // holding the lock, as it will ultimately trigger Medium::uninit()
11224 // calls which assume that the media tree lock isn't held.
11225 implicitAtts.clear();
11226
11227 alock.acquire();
11228
11229 /* if there is a VM recreate media lock map as mentioned above,
11230 * otherwise it is a waste of time and we leave things unlocked */
11231 if (aOnline)
11232 {
11233 const ComObjPtr<SessionMachine> pMachine = mData->mSession.mMachine;
11234 /* must never be NULL, but better safe than sorry */
11235 if (!pMachine.isNull())
11236 {
11237 alock.release();
11238 rc = mData->mSession.mMachine->i_lockMedia();
11239 alock.acquire();
11240 if (FAILED(rc))
11241 throw rc;
11242 }
11243 }
11244 }
11245 }
11246 catch (HRESULT aRC) {rc = aRC;}
11247
11248 if (mData->mMachineState == MachineState_SettingUp)
11249 i_setMachineState(oldState);
11250
11251 /* unlock all hard disks we locked when there is no VM */
11252 if (!aOnline)
11253 {
11254 ErrorInfoKeeper eik;
11255
11256 HRESULT rc1 = lockedMediaMap->Clear();
11257 AssertComRC(rc1);
11258 }
11259
11260 return rc;
11261}
11262
11263
11264/**
11265 * Looks through the given list of media attachments for one with the given parameters
11266 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11267 * can be searched as well if needed.
11268 *
11269 * @param ll
11270 * @param aControllerName
11271 * @param aControllerPort
11272 * @param aDevice
11273 * @return
11274 */
11275MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11276 const Utf8Str &aControllerName,
11277 LONG aControllerPort,
11278 LONG aDevice)
11279{
11280 for (MediumAttachmentList::const_iterator
11281 it = ll.begin();
11282 it != ll.end();
11283 ++it)
11284 {
11285 MediumAttachment *pAttach = *it;
11286 if (pAttach->i_matches(aControllerName, aControllerPort, aDevice))
11287 return pAttach;
11288 }
11289
11290 return NULL;
11291}
11292
11293/**
11294 * Looks through the given list of media attachments for one with the given parameters
11295 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11296 * can be searched as well if needed.
11297 *
11298 * @param ll
11299 * @param pMedium
11300 * @return
11301 */
11302MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11303 ComObjPtr<Medium> pMedium)
11304{
11305 for (MediumAttachmentList::const_iterator
11306 it = ll.begin();
11307 it != ll.end();
11308 ++it)
11309 {
11310 MediumAttachment *pAttach = *it;
11311 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11312 if (pMediumThis == pMedium)
11313 return pAttach;
11314 }
11315
11316 return NULL;
11317}
11318
11319/**
11320 * Looks through the given list of media attachments for one with the given parameters
11321 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11322 * can be searched as well if needed.
11323 *
11324 * @param ll
11325 * @param id
11326 * @return
11327 */
11328MediumAttachment *Machine::i_findAttachment(const MediumAttachmentList &ll,
11329 Guid &id)
11330{
11331 for (MediumAttachmentList::const_iterator
11332 it = ll.begin();
11333 it != ll.end();
11334 ++it)
11335 {
11336 MediumAttachment *pAttach = *it;
11337 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11338 if (pMediumThis->i_getId() == id)
11339 return pAttach;
11340 }
11341
11342 return NULL;
11343}
11344
11345/**
11346 * Main implementation for Machine::DetachDevice. This also gets called
11347 * from Machine::prepareUnregister() so it has been taken out for simplicity.
11348 *
11349 * @param pAttach Medium attachment to detach.
11350 * @param writeLock Machine write lock which the caller must have locked once.
11351 * This may be released temporarily in here.
11352 * @param pSnapshot If NULL, then the detachment is for the current machine.
11353 * Otherwise this is for a SnapshotMachine, and this must be
11354 * its snapshot.
11355 * @return
11356 */
11357HRESULT Machine::i_detachDevice(MediumAttachment *pAttach,
11358 AutoWriteLock &writeLock,
11359 Snapshot *pSnapshot)
11360{
11361 ComObjPtr<Medium> oldmedium = pAttach->i_getMedium();
11362 DeviceType_T mediumType = pAttach->i_getType();
11363
11364 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->i_getLocationFull().c_str() : "NULL"));
11365
11366 if (pAttach->i_isImplicit())
11367 {
11368 /* attempt to implicitly delete the implicitly created diff */
11369
11370 /// @todo move the implicit flag from MediumAttachment to Medium
11371 /// and forbid any hard disk operation when it is implicit. Or maybe
11372 /// a special media state for it to make it even more simple.
11373
11374 Assert(mMediumAttachments.isBackedUp());
11375
11376 /* will release the lock before the potentially lengthy operation, so
11377 * protect with the special state */
11378 MachineState_T oldState = mData->mMachineState;
11379 i_setMachineState(MachineState_SettingUp);
11380
11381 writeLock.release();
11382
11383 HRESULT rc = oldmedium->i_deleteStorage(NULL /*aProgress*/,
11384 true /*aWait*/);
11385
11386 writeLock.acquire();
11387
11388 i_setMachineState(oldState);
11389
11390 if (FAILED(rc)) return rc;
11391 }
11392
11393 i_setModified(IsModified_Storage);
11394 mMediumAttachments.backup();
11395 mMediumAttachments->remove(pAttach);
11396
11397 if (!oldmedium.isNull())
11398 {
11399 // if this is from a snapshot, do not defer detachment to i_commitMedia()
11400 if (pSnapshot)
11401 oldmedium->i_removeBackReference(mData->mUuid, pSnapshot->i_getId());
11402 // else if non-hard disk media, do not defer detachment to i_commitMedia() either
11403 else if (mediumType != DeviceType_HardDisk)
11404 oldmedium->i_removeBackReference(mData->mUuid);
11405 }
11406
11407 return S_OK;
11408}
11409
11410/**
11411 * Goes thru all media of the given list and
11412 *
11413 * 1) calls i_detachDevice() on each of them for this machine and
11414 * 2) adds all Medium objects found in the process to the given list,
11415 * depending on cleanupMode.
11416 *
11417 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
11418 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
11419 * media to the list.
11420 *
11421 * This gets called from Machine::Unregister, both for the actual Machine and
11422 * the SnapshotMachine objects that might be found in the snapshots.
11423 *
11424 * Requires caller and locking. The machine lock must be passed in because it
11425 * will be passed on to i_detachDevice which needs it for temporary unlocking.
11426 *
11427 * @param writeLock Machine lock from top-level caller; this gets passed to
11428 * i_detachDevice.
11429 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot
11430 * object if called for a SnapshotMachine.
11431 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get
11432 * added to llMedia; if Full, then all media get added;
11433 * otherwise no media get added.
11434 * @param llMedia Caller's list to receive Medium objects which got detached so
11435 * caller can close() them, depending on cleanupMode.
11436 * @return
11437 */
11438HRESULT Machine::i_detachAllMedia(AutoWriteLock &writeLock,
11439 Snapshot *pSnapshot,
11440 CleanupMode_T cleanupMode,
11441 MediaList &llMedia)
11442{
11443 Assert(isWriteLockOnCurrentThread());
11444
11445 HRESULT rc;
11446
11447 // make a temporary list because i_detachDevice invalidates iterators into
11448 // mMediumAttachments
11449 MediumAttachmentList llAttachments2 = *mMediumAttachments.data();
11450
11451 for (MediumAttachmentList::iterator
11452 it = llAttachments2.begin();
11453 it != llAttachments2.end();
11454 ++it)
11455 {
11456 ComObjPtr<MediumAttachment> &pAttach = *it;
11457 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
11458
11459 if (!pMedium.isNull())
11460 {
11461 AutoCaller mac(pMedium);
11462 if (FAILED(mac.rc())) return mac.rc();
11463 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
11464 DeviceType_T devType = pMedium->i_getDeviceType();
11465 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
11466 && devType == DeviceType_HardDisk)
11467 || (cleanupMode == CleanupMode_Full)
11468 )
11469 {
11470 llMedia.push_back(pMedium);
11471 ComObjPtr<Medium> pParent = pMedium->i_getParent();
11472 /* Not allowed to keep this lock as below we need the parent
11473 * medium lock, and the lock order is parent to child. */
11474 lock.release();
11475 /*
11476 * Search for medias which are not attached to any machine, but
11477 * in the chain to an attached disk. Mediums are only consided
11478 * if they are:
11479 * - have only one child
11480 * - no references to any machines
11481 * - are of normal medium type
11482 */
11483 while (!pParent.isNull())
11484 {
11485 AutoCaller mac1(pParent);
11486 if (FAILED(mac1.rc())) return mac1.rc();
11487 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
11488 if (pParent->i_getChildren().size() == 1)
11489 {
11490 if ( pParent->i_getMachineBackRefCount() == 0
11491 && pParent->i_getType() == MediumType_Normal
11492 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
11493 llMedia.push_back(pParent);
11494 }
11495 else
11496 break;
11497 pParent = pParent->i_getParent();
11498 }
11499 }
11500 }
11501
11502 // real machine: then we need to use the proper method
11503 rc = i_detachDevice(pAttach, writeLock, pSnapshot);
11504
11505 if (FAILED(rc))
11506 return rc;
11507 }
11508
11509 return S_OK;
11510}
11511
11512/**
11513 * Perform deferred hard disk detachments.
11514 *
11515 * Does nothing if the hard disk attachment data (mMediumAttachments) is not
11516 * changed (not backed up).
11517 *
11518 * If @a aOnline is @c true then this method will also unlock the old hard
11519 * disks for which the new implicit diffs were created and will lock these new
11520 * diffs for writing.
11521 *
11522 * @param aOnline Whether the VM was online prior to this operation.
11523 *
11524 * @note Locks this object for writing!
11525 */
11526void Machine::i_commitMedia(bool aOnline /*= false*/)
11527{
11528 AutoCaller autoCaller(this);
11529 AssertComRCReturnVoid(autoCaller.rc());
11530
11531 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11532
11533 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
11534
11535 HRESULT rc = S_OK;
11536
11537 /* no attach/detach operations -- nothing to do */
11538 if (!mMediumAttachments.isBackedUp())
11539 return;
11540
11541 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
11542 bool fMediaNeedsLocking = false;
11543
11544 /* enumerate new attachments */
11545 for (MediumAttachmentList::const_iterator
11546 it = mMediumAttachments->begin();
11547 it != mMediumAttachments->end();
11548 ++it)
11549 {
11550 MediumAttachment *pAttach = *it;
11551
11552 pAttach->i_commit();
11553
11554 Medium *pMedium = pAttach->i_getMedium();
11555 bool fImplicit = pAttach->i_isImplicit();
11556
11557 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
11558 (pMedium) ? pMedium->i_getName().c_str() : "NULL",
11559 fImplicit));
11560
11561 /** @todo convert all this Machine-based voodoo to MediumAttachment
11562 * based commit logic. */
11563 if (fImplicit)
11564 {
11565 /* convert implicit attachment to normal */
11566 pAttach->i_setImplicit(false);
11567
11568 if ( aOnline
11569 && pMedium
11570 && pAttach->i_getType() == DeviceType_HardDisk
11571 )
11572 {
11573 /* update the appropriate lock list */
11574 MediumLockList *pMediumLockList;
11575 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11576 AssertComRC(rc);
11577 if (pMediumLockList)
11578 {
11579 /* unlock if there's a need to change the locking */
11580 if (!fMediaNeedsLocking)
11581 {
11582 rc = mData->mSession.mLockedMedia.Unlock();
11583 AssertComRC(rc);
11584 fMediaNeedsLocking = true;
11585 }
11586 rc = pMediumLockList->Update(pMedium->i_getParent(), false);
11587 AssertComRC(rc);
11588 rc = pMediumLockList->Append(pMedium, true);
11589 AssertComRC(rc);
11590 }
11591 }
11592
11593 continue;
11594 }
11595
11596 if (pMedium)
11597 {
11598 /* was this medium attached before? */
11599 for (MediumAttachmentList::iterator
11600 oldIt = oldAtts.begin();
11601 oldIt != oldAtts.end();
11602 ++oldIt)
11603 {
11604 MediumAttachment *pOldAttach = *oldIt;
11605 if (pOldAttach->i_getMedium() == pMedium)
11606 {
11607 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->i_getName().c_str()));
11608
11609 /* yes: remove from old to avoid de-association */
11610 oldAtts.erase(oldIt);
11611 break;
11612 }
11613 }
11614 }
11615 }
11616
11617 /* enumerate remaining old attachments and de-associate from the
11618 * current machine state */
11619 for (MediumAttachmentList::const_iterator
11620 it = oldAtts.begin();
11621 it != oldAtts.end();
11622 ++it)
11623 {
11624 MediumAttachment *pAttach = *it;
11625 Medium *pMedium = pAttach->i_getMedium();
11626
11627 /* Detach only hard disks, since DVD/floppy media is detached
11628 * instantly in MountMedium. */
11629 if (pAttach->i_getType() == DeviceType_HardDisk && pMedium)
11630 {
11631 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->i_getName().c_str()));
11632
11633 /* now de-associate from the current machine state */
11634 rc = pMedium->i_removeBackReference(mData->mUuid);
11635 AssertComRC(rc);
11636
11637 if (aOnline)
11638 {
11639 /* unlock since medium is not used anymore */
11640 MediumLockList *pMediumLockList;
11641 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11642 if (RT_UNLIKELY(rc == VBOX_E_INVALID_OBJECT_STATE))
11643 {
11644 /* this happens for online snapshots, there the attachment
11645 * is changing, but only to a diff image created under
11646 * the old one, so there is no separate lock list */
11647 Assert(!pMediumLockList);
11648 }
11649 else
11650 {
11651 AssertComRC(rc);
11652 if (pMediumLockList)
11653 {
11654 rc = mData->mSession.mLockedMedia.Remove(pAttach);
11655 AssertComRC(rc);
11656 }
11657 }
11658 }
11659 }
11660 }
11661
11662 /* take media locks again so that the locking state is consistent */
11663 if (fMediaNeedsLocking)
11664 {
11665 Assert(aOnline);
11666 rc = mData->mSession.mLockedMedia.Lock();
11667 AssertComRC(rc);
11668 }
11669
11670 /* commit the hard disk changes */
11671 mMediumAttachments.commit();
11672
11673 if (i_isSessionMachine())
11674 {
11675 /*
11676 * Update the parent machine to point to the new owner.
11677 * This is necessary because the stored parent will point to the
11678 * session machine otherwise and cause crashes or errors later
11679 * when the session machine gets invalid.
11680 */
11681 /** @todo Change the MediumAttachment class to behave like any other
11682 * class in this regard by creating peer MediumAttachment
11683 * objects for session machines and share the data with the peer
11684 * machine.
11685 */
11686 for (MediumAttachmentList::const_iterator
11687 it = mMediumAttachments->begin();
11688 it != mMediumAttachments->end();
11689 ++it)
11690 (*it)->i_updateParentMachine(mPeer);
11691
11692 /* attach new data to the primary machine and reshare it */
11693 mPeer->mMediumAttachments.attach(mMediumAttachments);
11694 }
11695
11696 return;
11697}
11698
11699/**
11700 * Perform deferred deletion of implicitly created diffs.
11701 *
11702 * Does nothing if the hard disk attachment data (mMediumAttachments) is not
11703 * changed (not backed up).
11704 *
11705 * @note Locks this object for writing!
11706 */
11707void Machine::i_rollbackMedia()
11708{
11709 AutoCaller autoCaller(this);
11710 AssertComRCReturnVoid(autoCaller.rc());
11711
11712 // AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11713 LogFlowThisFunc(("Entering rollbackMedia\n"));
11714
11715 HRESULT rc = S_OK;
11716
11717 /* no attach/detach operations -- nothing to do */
11718 if (!mMediumAttachments.isBackedUp())
11719 return;
11720
11721 /* enumerate new attachments */
11722 for (MediumAttachmentList::const_iterator
11723 it = mMediumAttachments->begin();
11724 it != mMediumAttachments->end();
11725 ++it)
11726 {
11727 MediumAttachment *pAttach = *it;
11728 /* Fix up the backrefs for DVD/floppy media. */
11729 if (pAttach->i_getType() != DeviceType_HardDisk)
11730 {
11731 Medium *pMedium = pAttach->i_getMedium();
11732 if (pMedium)
11733 {
11734 rc = pMedium->i_removeBackReference(mData->mUuid);
11735 AssertComRC(rc);
11736 }
11737 }
11738
11739 (*it)->i_rollback();
11740
11741 pAttach = *it;
11742 /* Fix up the backrefs for DVD/floppy media. */
11743 if (pAttach->i_getType() != DeviceType_HardDisk)
11744 {
11745 Medium *pMedium = pAttach->i_getMedium();
11746 if (pMedium)
11747 {
11748 rc = pMedium->i_addBackReference(mData->mUuid);
11749 AssertComRC(rc);
11750 }
11751 }
11752 }
11753
11754 /** @todo convert all this Machine-based voodoo to MediumAttachment
11755 * based rollback logic. */
11756 i_deleteImplicitDiffs(Global::IsOnline(mData->mMachineState));
11757
11758 return;
11759}
11760
11761/**
11762 * Returns true if the settings file is located in the directory named exactly
11763 * as the machine; this means, among other things, that the machine directory
11764 * should be auto-renamed.
11765 *
11766 * @param aSettingsDir if not NULL, the full machine settings file directory
11767 * name will be assigned there.
11768 *
11769 * @note Doesn't lock anything.
11770 * @note Not thread safe (must be called from this object's lock).
11771 */
11772bool Machine::i_isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
11773{
11774 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11775 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
11776 if (aSettingsDir)
11777 *aSettingsDir = strMachineDirName;
11778 strMachineDirName.stripPath(); // vmname
11779 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11780 strConfigFileOnly.stripPath() // vmname.vbox
11781 .stripSuffix(); // vmname
11782 /** @todo hack, make somehow use of ComposeMachineFilename */
11783 if (mUserData->s.fDirectoryIncludesUUID)
11784 strConfigFileOnly += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
11785
11786 AssertReturn(!strMachineDirName.isEmpty(), false);
11787 AssertReturn(!strConfigFileOnly.isEmpty(), false);
11788
11789 return strMachineDirName == strConfigFileOnly;
11790}
11791
11792/**
11793 * Discards all changes to machine settings.
11794 *
11795 * @param aNotify Whether to notify the direct session about changes or not.
11796 *
11797 * @note Locks objects for writing!
11798 */
11799void Machine::i_rollback(bool aNotify)
11800{
11801 AutoCaller autoCaller(this);
11802 AssertComRCReturn(autoCaller.rc(), (void)0);
11803
11804 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11805
11806 if (!mStorageControllers.isNull())
11807 {
11808 if (mStorageControllers.isBackedUp())
11809 {
11810 /* unitialize all new devices (absent in the backed up list). */
11811 StorageControllerList *backedList = mStorageControllers.backedUpData();
11812 for (StorageControllerList::const_iterator
11813 it = mStorageControllers->begin();
11814 it != mStorageControllers->end();
11815 ++it)
11816 {
11817 if ( std::find(backedList->begin(), backedList->end(), *it)
11818 == backedList->end()
11819 )
11820 {
11821 (*it)->uninit();
11822 }
11823 }
11824
11825 /* restore the list */
11826 mStorageControllers.rollback();
11827 }
11828
11829 /* rollback any changes to devices after restoring the list */
11830 if (mData->flModifications & IsModified_Storage)
11831 {
11832 for (StorageControllerList::const_iterator
11833 it = mStorageControllers->begin();
11834 it != mStorageControllers->end();
11835 ++it)
11836 {
11837 (*it)->i_rollback();
11838 }
11839 }
11840 }
11841
11842 if (!mUSBControllers.isNull())
11843 {
11844 if (mUSBControllers.isBackedUp())
11845 {
11846 /* unitialize all new devices (absent in the backed up list). */
11847 USBControllerList *backedList = mUSBControllers.backedUpData();
11848 for (USBControllerList::const_iterator
11849 it = mUSBControllers->begin();
11850 it != mUSBControllers->end();
11851 ++it)
11852 {
11853 if ( std::find(backedList->begin(), backedList->end(), *it)
11854 == backedList->end()
11855 )
11856 {
11857 (*it)->uninit();
11858 }
11859 }
11860
11861 /* restore the list */
11862 mUSBControllers.rollback();
11863 }
11864
11865 /* rollback any changes to devices after restoring the list */
11866 if (mData->flModifications & IsModified_USB)
11867 {
11868 for (USBControllerList::const_iterator
11869 it = mUSBControllers->begin();
11870 it != mUSBControllers->end();
11871 ++it)
11872 {
11873 (*it)->i_rollback();
11874 }
11875 }
11876 }
11877
11878 mUserData.rollback();
11879
11880 mHWData.rollback();
11881
11882 if (mData->flModifications & IsModified_Storage)
11883 i_rollbackMedia();
11884
11885 if (mBIOSSettings)
11886 mBIOSSettings->i_rollback();
11887
11888 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
11889 mVRDEServer->i_rollback();
11890
11891 if (mAudioAdapter)
11892 mAudioAdapter->i_rollback();
11893
11894 if (mUSBDeviceFilters && (mData->flModifications & IsModified_USB))
11895 mUSBDeviceFilters->i_rollback();
11896
11897 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
11898 mBandwidthControl->i_rollback();
11899
11900 if (!mHWData.isNull())
11901 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
11902 NetworkAdapterVector networkAdapters(mNetworkAdapters.size());
11903 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
11904 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
11905
11906 if (mData->flModifications & IsModified_NetworkAdapters)
11907 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
11908 if ( mNetworkAdapters[slot]
11909 && mNetworkAdapters[slot]->i_isModified())
11910 {
11911 mNetworkAdapters[slot]->i_rollback();
11912 networkAdapters[slot] = mNetworkAdapters[slot];
11913 }
11914
11915 if (mData->flModifications & IsModified_SerialPorts)
11916 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
11917 if ( mSerialPorts[slot]
11918 && mSerialPorts[slot]->i_isModified())
11919 {
11920 mSerialPorts[slot]->i_rollback();
11921 serialPorts[slot] = mSerialPorts[slot];
11922 }
11923
11924 if (mData->flModifications & IsModified_ParallelPorts)
11925 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
11926 if ( mParallelPorts[slot]
11927 && mParallelPorts[slot]->i_isModified())
11928 {
11929 mParallelPorts[slot]->i_rollback();
11930 parallelPorts[slot] = mParallelPorts[slot];
11931 }
11932
11933 if (aNotify)
11934 {
11935 /* inform the direct session about changes */
11936
11937 ComObjPtr<Machine> that = this;
11938 uint32_t flModifications = mData->flModifications;
11939 alock.release();
11940
11941 if (flModifications & IsModified_SharedFolders)
11942 that->i_onSharedFolderChange();
11943
11944 if (flModifications & IsModified_VRDEServer)
11945 that->i_onVRDEServerChange(/* aRestart */ TRUE);
11946 if (flModifications & IsModified_USB)
11947 that->i_onUSBControllerChange();
11948
11949 for (ULONG slot = 0; slot < networkAdapters.size(); ++slot)
11950 if (networkAdapters[slot])
11951 that->i_onNetworkAdapterChange(networkAdapters[slot], FALSE);
11952 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); ++slot)
11953 if (serialPorts[slot])
11954 that->i_onSerialPortChange(serialPorts[slot]);
11955 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); ++slot)
11956 if (parallelPorts[slot])
11957 that->i_onParallelPortChange(parallelPorts[slot]);
11958
11959 if (flModifications & IsModified_Storage)
11960 that->i_onStorageControllerChange();
11961
11962#if 0
11963 if (flModifications & IsModified_BandwidthControl)
11964 that->onBandwidthControlChange();
11965#endif
11966 }
11967}
11968
11969/**
11970 * Commits all the changes to machine settings.
11971 *
11972 * Note that this operation is supposed to never fail.
11973 *
11974 * @note Locks this object and children for writing.
11975 */
11976void Machine::i_commit()
11977{
11978 AutoCaller autoCaller(this);
11979 AssertComRCReturnVoid(autoCaller.rc());
11980
11981 AutoCaller peerCaller(mPeer);
11982 AssertComRCReturnVoid(peerCaller.rc());
11983
11984 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
11985
11986 /*
11987 * use safe commit to ensure Snapshot machines (that share mUserData)
11988 * will still refer to a valid memory location
11989 */
11990 mUserData.commitCopy();
11991
11992 mHWData.commit();
11993
11994 if (mMediumAttachments.isBackedUp())
11995 i_commitMedia(Global::IsOnline(mData->mMachineState));
11996
11997 mBIOSSettings->i_commit();
11998 mVRDEServer->i_commit();
11999 mAudioAdapter->i_commit();
12000 mUSBDeviceFilters->i_commit();
12001 mBandwidthControl->i_commit();
12002
12003 /* Since mNetworkAdapters is a list which might have been changed (resized)
12004 * without using the Backupable<> template we need to handle the copying
12005 * of the list entries manually, including the creation of peers for the
12006 * new objects. */
12007 bool commitNetworkAdapters = false;
12008 size_t newSize = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
12009 if (mPeer)
12010 {
12011 /* commit everything, even the ones which will go away */
12012 for (size_t slot = 0; slot < mNetworkAdapters.size(); slot++)
12013 mNetworkAdapters[slot]->i_commit();
12014 /* copy over the new entries, creating a peer and uninit the original */
12015 mPeer->mNetworkAdapters.resize(RT_MAX(newSize, mPeer->mNetworkAdapters.size()));
12016 for (size_t slot = 0; slot < newSize; slot++)
12017 {
12018 /* look if this adapter has a peer device */
12019 ComObjPtr<NetworkAdapter> peer = mNetworkAdapters[slot]->i_getPeer();
12020 if (!peer)
12021 {
12022 /* no peer means the adapter is a newly created one;
12023 * create a peer owning data this data share it with */
12024 peer.createObject();
12025 peer->init(mPeer, mNetworkAdapters[slot], true /* aReshare */);
12026 }
12027 mPeer->mNetworkAdapters[slot] = peer;
12028 }
12029 /* uninit any no longer needed network adapters */
12030 for (size_t slot = newSize; slot < mNetworkAdapters.size(); ++slot)
12031 mNetworkAdapters[slot]->uninit();
12032 for (size_t slot = newSize; slot < mPeer->mNetworkAdapters.size(); ++slot)
12033 {
12034 if (mPeer->mNetworkAdapters[slot])
12035 mPeer->mNetworkAdapters[slot]->uninit();
12036 }
12037 /* Keep the original network adapter count until this point, so that
12038 * discarding a chipset type change will not lose settings. */
12039 mNetworkAdapters.resize(newSize);
12040 mPeer->mNetworkAdapters.resize(newSize);
12041 }
12042 else
12043 {
12044 /* we have no peer (our parent is the newly created machine);
12045 * just commit changes to the network adapters */
12046 commitNetworkAdapters = true;
12047 }
12048 if (commitNetworkAdapters)
12049 for (size_t slot = 0; slot < mNetworkAdapters.size(); ++slot)
12050 mNetworkAdapters[slot]->i_commit();
12051
12052 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12053 mSerialPorts[slot]->i_commit();
12054 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12055 mParallelPorts[slot]->i_commit();
12056
12057 bool commitStorageControllers = false;
12058
12059 if (mStorageControllers.isBackedUp())
12060 {
12061 mStorageControllers.commit();
12062
12063 if (mPeer)
12064 {
12065 /* Commit all changes to new controllers (this will reshare data with
12066 * peers for those who have peers) */
12067 StorageControllerList *newList = new StorageControllerList();
12068 for (StorageControllerList::const_iterator
12069 it = mStorageControllers->begin();
12070 it != mStorageControllers->end();
12071 ++it)
12072 {
12073 (*it)->i_commit();
12074
12075 /* look if this controller has a peer device */
12076 ComObjPtr<StorageController> peer = (*it)->i_getPeer();
12077 if (!peer)
12078 {
12079 /* no peer means the device is a newly created one;
12080 * create a peer owning data this device share it with */
12081 peer.createObject();
12082 peer->init(mPeer, *it, true /* aReshare */);
12083 }
12084 else
12085 {
12086 /* remove peer from the old list */
12087 mPeer->mStorageControllers->remove(peer);
12088 }
12089 /* and add it to the new list */
12090 newList->push_back(peer);
12091 }
12092
12093 /* uninit old peer's controllers that are left */
12094 for (StorageControllerList::const_iterator
12095 it = mPeer->mStorageControllers->begin();
12096 it != mPeer->mStorageControllers->end();
12097 ++it)
12098 {
12099 (*it)->uninit();
12100 }
12101
12102 /* attach new list of controllers to our peer */
12103 mPeer->mStorageControllers.attach(newList);
12104 }
12105 else
12106 {
12107 /* we have no peer (our parent is the newly created machine);
12108 * just commit changes to devices */
12109 commitStorageControllers = true;
12110 }
12111 }
12112 else
12113 {
12114 /* the list of controllers itself is not changed,
12115 * just commit changes to controllers themselves */
12116 commitStorageControllers = true;
12117 }
12118
12119 if (commitStorageControllers)
12120 {
12121 for (StorageControllerList::const_iterator
12122 it = mStorageControllers->begin();
12123 it != mStorageControllers->end();
12124 ++it)
12125 {
12126 (*it)->i_commit();
12127 }
12128 }
12129
12130 bool commitUSBControllers = false;
12131
12132 if (mUSBControllers.isBackedUp())
12133 {
12134 mUSBControllers.commit();
12135
12136 if (mPeer)
12137 {
12138 /* Commit all changes to new controllers (this will reshare data with
12139 * peers for those who have peers) */
12140 USBControllerList *newList = new USBControllerList();
12141 for (USBControllerList::const_iterator
12142 it = mUSBControllers->begin();
12143 it != mUSBControllers->end();
12144 ++it)
12145 {
12146 (*it)->i_commit();
12147
12148 /* look if this controller has a peer device */
12149 ComObjPtr<USBController> peer = (*it)->i_getPeer();
12150 if (!peer)
12151 {
12152 /* no peer means the device is a newly created one;
12153 * create a peer owning data this device share it with */
12154 peer.createObject();
12155 peer->init(mPeer, *it, true /* aReshare */);
12156 }
12157 else
12158 {
12159 /* remove peer from the old list */
12160 mPeer->mUSBControllers->remove(peer);
12161 }
12162 /* and add it to the new list */
12163 newList->push_back(peer);
12164 }
12165
12166 /* uninit old peer's controllers that are left */
12167 for (USBControllerList::const_iterator
12168 it = mPeer->mUSBControllers->begin();
12169 it != mPeer->mUSBControllers->end();
12170 ++it)
12171 {
12172 (*it)->uninit();
12173 }
12174
12175 /* attach new list of controllers to our peer */
12176 mPeer->mUSBControllers.attach(newList);
12177 }
12178 else
12179 {
12180 /* we have no peer (our parent is the newly created machine);
12181 * just commit changes to devices */
12182 commitUSBControllers = true;
12183 }
12184 }
12185 else
12186 {
12187 /* the list of controllers itself is not changed,
12188 * just commit changes to controllers themselves */
12189 commitUSBControllers = true;
12190 }
12191
12192 if (commitUSBControllers)
12193 {
12194 for (USBControllerList::const_iterator
12195 it = mUSBControllers->begin();
12196 it != mUSBControllers->end();
12197 ++it)
12198 {
12199 (*it)->i_commit();
12200 }
12201 }
12202
12203 if (i_isSessionMachine())
12204 {
12205 /* attach new data to the primary machine and reshare it */
12206 mPeer->mUserData.attach(mUserData);
12207 mPeer->mHWData.attach(mHWData);
12208 /* mmMediumAttachments is reshared by fixupMedia */
12209 // mPeer->mMediumAttachments.attach(mMediumAttachments);
12210 Assert(mPeer->mMediumAttachments.data() == mMediumAttachments.data());
12211 }
12212}
12213
12214/**
12215 * Copies all the hardware data from the given machine.
12216 *
12217 * Currently, only called when the VM is being restored from a snapshot. In
12218 * particular, this implies that the VM is not running during this method's
12219 * call.
12220 *
12221 * @note This method must be called from under this object's lock.
12222 *
12223 * @note This method doesn't call #i_commit(), so all data remains backed up and
12224 * unsaved.
12225 */
12226void Machine::i_copyFrom(Machine *aThat)
12227{
12228 AssertReturnVoid(!i_isSnapshotMachine());
12229 AssertReturnVoid(aThat->i_isSnapshotMachine());
12230
12231 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
12232
12233 mHWData.assignCopy(aThat->mHWData);
12234
12235 // create copies of all shared folders (mHWData after attaching a copy
12236 // contains just references to original objects)
12237 for (HWData::SharedFolderList::iterator
12238 it = mHWData->mSharedFolders.begin();
12239 it != mHWData->mSharedFolders.end();
12240 ++it)
12241 {
12242 ComObjPtr<SharedFolder> folder;
12243 folder.createObject();
12244 HRESULT rc = folder->initCopy(i_getMachine(), *it);
12245 AssertComRC(rc);
12246 *it = folder;
12247 }
12248
12249 mBIOSSettings->i_copyFrom(aThat->mBIOSSettings);
12250 mVRDEServer->i_copyFrom(aThat->mVRDEServer);
12251 mAudioAdapter->i_copyFrom(aThat->mAudioAdapter);
12252 mUSBDeviceFilters->i_copyFrom(aThat->mUSBDeviceFilters);
12253 mBandwidthControl->i_copyFrom(aThat->mBandwidthControl);
12254
12255 /* create private copies of all controllers */
12256 mStorageControllers.backup();
12257 mStorageControllers->clear();
12258 for (StorageControllerList::const_iterator
12259 it = aThat->mStorageControllers->begin();
12260 it != aThat->mStorageControllers->end();
12261 ++it)
12262 {
12263 ComObjPtr<StorageController> ctrl;
12264 ctrl.createObject();
12265 ctrl->initCopy(this, *it);
12266 mStorageControllers->push_back(ctrl);
12267 }
12268
12269 /* create private copies of all USB controllers */
12270 mUSBControllers.backup();
12271 mUSBControllers->clear();
12272 for (USBControllerList::const_iterator
12273 it = aThat->mUSBControllers->begin();
12274 it != aThat->mUSBControllers->end();
12275 ++it)
12276 {
12277 ComObjPtr<USBController> ctrl;
12278 ctrl.createObject();
12279 ctrl->initCopy(this, *it);
12280 mUSBControllers->push_back(ctrl);
12281 }
12282
12283 mNetworkAdapters.resize(aThat->mNetworkAdapters.size());
12284 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12285 {
12286 if (mNetworkAdapters[slot].isNotNull())
12287 mNetworkAdapters[slot]->i_copyFrom(aThat->mNetworkAdapters[slot]);
12288 else
12289 {
12290 unconst(mNetworkAdapters[slot]).createObject();
12291 mNetworkAdapters[slot]->initCopy(this, aThat->mNetworkAdapters[slot]);
12292 }
12293 }
12294 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12295 mSerialPorts[slot]->i_copyFrom(aThat->mSerialPorts[slot]);
12296 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12297 mParallelPorts[slot]->i_copyFrom(aThat->mParallelPorts[slot]);
12298}
12299
12300/**
12301 * Returns whether the given storage controller is hotplug capable.
12302 *
12303 * @returns true if the controller supports hotplugging
12304 * false otherwise.
12305 * @param enmCtrlType The controller type to check for.
12306 */
12307bool Machine::i_isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
12308{
12309 ComPtr<ISystemProperties> systemProperties;
12310 HRESULT rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
12311 if (FAILED(rc))
12312 return false;
12313
12314 BOOL aHotplugCapable = FALSE;
12315 systemProperties->GetStorageControllerHotplugCapable(enmCtrlType, &aHotplugCapable);
12316
12317 return RT_BOOL(aHotplugCapable);
12318}
12319
12320#ifdef VBOX_WITH_RESOURCE_USAGE_API
12321
12322void Machine::i_getDiskList(MediaList &list)
12323{
12324 for (MediumAttachmentList::const_iterator
12325 it = mMediumAttachments->begin();
12326 it != mMediumAttachments->end();
12327 ++it)
12328 {
12329 MediumAttachment *pAttach = *it;
12330 /* just in case */
12331 AssertContinue(pAttach);
12332
12333 AutoCaller localAutoCallerA(pAttach);
12334 if (FAILED(localAutoCallerA.rc())) continue;
12335
12336 AutoReadLock local_alockA(pAttach COMMA_LOCKVAL_SRC_POS);
12337
12338 if (pAttach->i_getType() == DeviceType_HardDisk)
12339 list.push_back(pAttach->i_getMedium());
12340 }
12341}
12342
12343void Machine::i_registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
12344{
12345 AssertReturnVoid(isWriteLockOnCurrentThread());
12346 AssertPtrReturnVoid(aCollector);
12347
12348 pm::CollectorHAL *hal = aCollector->getHAL();
12349 /* Create sub metrics */
12350 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
12351 "Percentage of processor time spent in user mode by the VM process.");
12352 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
12353 "Percentage of processor time spent in kernel mode by the VM process.");
12354 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
12355 "Size of resident portion of VM process in memory.");
12356 pm::SubMetric *diskUsageUsed = new pm::SubMetric("Disk/Usage/Used",
12357 "Actual size of all VM disks combined.");
12358 pm::SubMetric *machineNetRx = new pm::SubMetric("Net/Rate/Rx",
12359 "Network receive rate.");
12360 pm::SubMetric *machineNetTx = new pm::SubMetric("Net/Rate/Tx",
12361 "Network transmit rate.");
12362 /* Create and register base metrics */
12363 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
12364 cpuLoadUser, cpuLoadKernel);
12365 aCollector->registerBaseMetric(cpuLoad);
12366 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
12367 ramUsageUsed);
12368 aCollector->registerBaseMetric(ramUsage);
12369 MediaList disks;
12370 i_getDiskList(disks);
12371 pm::BaseMetric *diskUsage = new pm::MachineDiskUsage(hal, aMachine, disks,
12372 diskUsageUsed);
12373 aCollector->registerBaseMetric(diskUsage);
12374
12375 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
12376 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12377 new pm::AggregateAvg()));
12378 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12379 new pm::AggregateMin()));
12380 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12381 new pm::AggregateMax()));
12382 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
12383 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12384 new pm::AggregateAvg()));
12385 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12386 new pm::AggregateMin()));
12387 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12388 new pm::AggregateMax()));
12389
12390 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
12391 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12392 new pm::AggregateAvg()));
12393 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12394 new pm::AggregateMin()));
12395 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12396 new pm::AggregateMax()));
12397
12398 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed, 0));
12399 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12400 new pm::AggregateAvg()));
12401 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12402 new pm::AggregateMin()));
12403 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12404 new pm::AggregateMax()));
12405
12406
12407 /* Guest metrics collector */
12408 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
12409 aCollector->registerGuest(mCollectorGuest);
12410 Log7(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n", this, __PRETTY_FUNCTION__, mCollectorGuest));
12411
12412 /* Create sub metrics */
12413 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
12414 "Percentage of processor time spent in user mode as seen by the guest.");
12415 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
12416 "Percentage of processor time spent in kernel mode as seen by the guest.");
12417 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
12418 "Percentage of processor time spent idling as seen by the guest.");
12419
12420 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
12421 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
12422 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
12423 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
12424 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
12425 pm::SubMetric *guestMemCache = new pm::SubMetric(
12426 "Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
12427
12428 pm::SubMetric *guestPagedTotal = new pm::SubMetric(
12429 "Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
12430
12431 /* Create and register base metrics */
12432 pm::BaseMetric *machineNetRate = new pm::MachineNetRate(mCollectorGuest, aMachine,
12433 machineNetRx, machineNetTx);
12434 aCollector->registerBaseMetric(machineNetRate);
12435
12436 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
12437 guestLoadUser, guestLoadKernel, guestLoadIdle);
12438 aCollector->registerBaseMetric(guestCpuLoad);
12439
12440 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
12441 guestMemTotal, guestMemFree,
12442 guestMemBalloon, guestMemShared,
12443 guestMemCache, guestPagedTotal);
12444 aCollector->registerBaseMetric(guestCpuMem);
12445
12446 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, 0));
12447 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateAvg()));
12448 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMin()));
12449 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMax()));
12450
12451 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, 0));
12452 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateAvg()));
12453 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMin()));
12454 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMax()));
12455
12456 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
12457 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
12458 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
12459 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
12460
12461 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
12462 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
12463 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
12464 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
12465
12466 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
12467 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
12468 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
12469 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
12470
12471 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
12472 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
12473 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
12474 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
12475
12476 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
12477 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
12478 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
12479 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
12480
12481 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
12482 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
12483 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
12484 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
12485
12486 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
12487 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
12488 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
12489 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
12490
12491 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
12492 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
12493 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
12494 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
12495
12496 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
12497 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
12498 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
12499 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
12500}
12501
12502void Machine::i_unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
12503{
12504 AssertReturnVoid(isWriteLockOnCurrentThread());
12505
12506 if (aCollector)
12507 {
12508 aCollector->unregisterMetricsFor(aMachine);
12509 aCollector->unregisterBaseMetricsFor(aMachine);
12510 }
12511}
12512
12513#endif /* VBOX_WITH_RESOURCE_USAGE_API */
12514
12515
12516////////////////////////////////////////////////////////////////////////////////
12517
12518DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
12519
12520HRESULT SessionMachine::FinalConstruct()
12521{
12522 LogFlowThisFunc(("\n"));
12523
12524 mClientToken = NULL;
12525
12526 return BaseFinalConstruct();
12527}
12528
12529void SessionMachine::FinalRelease()
12530{
12531 LogFlowThisFunc(("\n"));
12532
12533 Assert(!mClientToken);
12534 /* paranoia, should not hang around any more */
12535 if (mClientToken)
12536 {
12537 delete mClientToken;
12538 mClientToken = NULL;
12539 }
12540
12541 uninit(Uninit::Unexpected);
12542
12543 BaseFinalRelease();
12544}
12545
12546/**
12547 * @note Must be called only by Machine::LockMachine() from its own write lock.
12548 */
12549HRESULT SessionMachine::init(Machine *aMachine)
12550{
12551 LogFlowThisFuncEnter();
12552 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
12553
12554 AssertReturn(aMachine, E_INVALIDARG);
12555
12556 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
12557
12558 /* Enclose the state transition NotReady->InInit->Ready */
12559 AutoInitSpan autoInitSpan(this);
12560 AssertReturn(autoInitSpan.isOk(), E_FAIL);
12561
12562 HRESULT rc = S_OK;
12563
12564 RT_ZERO(mAuthLibCtx);
12565
12566 /* create the machine client token */
12567 try
12568 {
12569 mClientToken = new ClientToken(aMachine, this);
12570 if (!mClientToken->isReady())
12571 {
12572 delete mClientToken;
12573 mClientToken = NULL;
12574 rc = E_FAIL;
12575 }
12576 }
12577 catch (std::bad_alloc &)
12578 {
12579 rc = E_OUTOFMEMORY;
12580 }
12581 if (FAILED(rc))
12582 return rc;
12583
12584 /* memorize the peer Machine */
12585 unconst(mPeer) = aMachine;
12586 /* share the parent pointer */
12587 unconst(mParent) = aMachine->mParent;
12588
12589 /* take the pointers to data to share */
12590 mData.share(aMachine->mData);
12591 mSSData.share(aMachine->mSSData);
12592
12593 mUserData.share(aMachine->mUserData);
12594 mHWData.share(aMachine->mHWData);
12595 mMediumAttachments.share(aMachine->mMediumAttachments);
12596
12597 mStorageControllers.allocate();
12598 for (StorageControllerList::const_iterator
12599 it = aMachine->mStorageControllers->begin();
12600 it != aMachine->mStorageControllers->end();
12601 ++it)
12602 {
12603 ComObjPtr<StorageController> ctl;
12604 ctl.createObject();
12605 ctl->init(this, *it);
12606 mStorageControllers->push_back(ctl);
12607 }
12608
12609 mUSBControllers.allocate();
12610 for (USBControllerList::const_iterator
12611 it = aMachine->mUSBControllers->begin();
12612 it != aMachine->mUSBControllers->end();
12613 ++it)
12614 {
12615 ComObjPtr<USBController> ctl;
12616 ctl.createObject();
12617 ctl->init(this, *it);
12618 mUSBControllers->push_back(ctl);
12619 }
12620
12621 unconst(mBIOSSettings).createObject();
12622 mBIOSSettings->init(this, aMachine->mBIOSSettings);
12623 /* create another VRDEServer object that will be mutable */
12624 unconst(mVRDEServer).createObject();
12625 mVRDEServer->init(this, aMachine->mVRDEServer);
12626 /* create another audio adapter object that will be mutable */
12627 unconst(mAudioAdapter).createObject();
12628 mAudioAdapter->init(this, aMachine->mAudioAdapter);
12629 /* create a list of serial ports that will be mutable */
12630 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12631 {
12632 unconst(mSerialPorts[slot]).createObject();
12633 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
12634 }
12635 /* create a list of parallel ports that will be mutable */
12636 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12637 {
12638 unconst(mParallelPorts[slot]).createObject();
12639 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
12640 }
12641
12642 /* create another USB device filters object that will be mutable */
12643 unconst(mUSBDeviceFilters).createObject();
12644 mUSBDeviceFilters->init(this, aMachine->mUSBDeviceFilters);
12645
12646 /* create a list of network adapters that will be mutable */
12647 mNetworkAdapters.resize(aMachine->mNetworkAdapters.size());
12648 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12649 {
12650 unconst(mNetworkAdapters[slot]).createObject();
12651 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
12652 }
12653
12654 /* create another bandwidth control object that will be mutable */
12655 unconst(mBandwidthControl).createObject();
12656 mBandwidthControl->init(this, aMachine->mBandwidthControl);
12657
12658#ifdef VBOX_WITH_UNATTENDED
12659 /* create another unattended object that will be mutable */
12660 unconst(mUnattended).createObject();
12661 mUnattended->init(this, aMachine->mUnattended);
12662#endif
12663
12664 /* default is to delete saved state on Saved -> PoweredOff transition */
12665 mRemoveSavedState = true;
12666
12667 /* Confirm a successful initialization when it's the case */
12668 autoInitSpan.setSucceeded();
12669
12670 miNATNetworksStarted = 0;
12671
12672 LogFlowThisFuncLeave();
12673 return rc;
12674}
12675
12676/**
12677 * Uninitializes this session object. If the reason is other than
12678 * Uninit::Unexpected, then this method MUST be called from #i_checkForDeath()
12679 * or the client watcher code.
12680 *
12681 * @param aReason uninitialization reason
12682 *
12683 * @note Locks mParent + this object for writing.
12684 */
12685void SessionMachine::uninit(Uninit::Reason aReason)
12686{
12687 LogFlowThisFuncEnter();
12688 LogFlowThisFunc(("reason=%d\n", aReason));
12689
12690 /*
12691 * Strongly reference ourselves to prevent this object deletion after
12692 * mData->mSession.mMachine.setNull() below (which can release the last
12693 * reference and call the destructor). Important: this must be done before
12694 * accessing any members (and before AutoUninitSpan that does it as well).
12695 * This self reference will be released as the very last step on return.
12696 */
12697 ComObjPtr<SessionMachine> selfRef;
12698 if (aReason != Uninit::Unexpected)
12699 selfRef = this;
12700
12701 /* Enclose the state transition Ready->InUninit->NotReady */
12702 AutoUninitSpan autoUninitSpan(this);
12703 if (autoUninitSpan.uninitDone())
12704 {
12705 LogFlowThisFunc(("Already uninitialized\n"));
12706 LogFlowThisFuncLeave();
12707 return;
12708 }
12709
12710 if (autoUninitSpan.initFailed())
12711 {
12712 /* We've been called by init() because it's failed. It's not really
12713 * necessary (nor it's safe) to perform the regular uninit sequence
12714 * below, the following is enough.
12715 */
12716 LogFlowThisFunc(("Initialization failed.\n"));
12717 /* destroy the machine client token */
12718 if (mClientToken)
12719 {
12720 delete mClientToken;
12721 mClientToken = NULL;
12722 }
12723 uninitDataAndChildObjects();
12724 mData.free();
12725 unconst(mParent) = NULL;
12726 unconst(mPeer) = NULL;
12727 LogFlowThisFuncLeave();
12728 return;
12729 }
12730
12731 MachineState_T lastState;
12732 {
12733 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
12734 lastState = mData->mMachineState;
12735 }
12736 NOREF(lastState);
12737
12738#ifdef VBOX_WITH_USB
12739 // release all captured USB devices, but do this before requesting the locks below
12740 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
12741 {
12742 /* Console::captureUSBDevices() is called in the VM process only after
12743 * setting the machine state to Starting or Restoring.
12744 * Console::detachAllUSBDevices() will be called upon successful
12745 * termination. So, we need to release USB devices only if there was
12746 * an abnormal termination of a running VM.
12747 *
12748 * This is identical to SessionMachine::DetachAllUSBDevices except
12749 * for the aAbnormal argument. */
12750 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
12751 AssertComRC(rc);
12752 NOREF(rc);
12753
12754 USBProxyService *service = mParent->i_host()->i_usbProxyService();
12755 if (service)
12756 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
12757 }
12758#endif /* VBOX_WITH_USB */
12759
12760 // we need to lock this object in uninit() because the lock is shared
12761 // with mPeer (as well as data we modify below). mParent lock is needed
12762 // by several calls to it.
12763 AutoMultiWriteLock2 multilock(mParent, this COMMA_LOCKVAL_SRC_POS);
12764
12765#ifdef VBOX_WITH_RESOURCE_USAGE_API
12766 /*
12767 * It is safe to call Machine::i_unregisterMetrics() here because
12768 * PerformanceCollector::samplerCallback no longer accesses guest methods
12769 * holding the lock.
12770 */
12771 i_unregisterMetrics(mParent->i_performanceCollector(), mPeer);
12772 /* The guest must be unregistered after its metrics (@bugref{5949}). */
12773 Log7(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n", this, __PRETTY_FUNCTION__, mCollectorGuest));
12774 if (mCollectorGuest)
12775 {
12776 mParent->i_performanceCollector()->unregisterGuest(mCollectorGuest);
12777 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
12778 mCollectorGuest = NULL;
12779 }
12780#endif
12781
12782 if (aReason == Uninit::Abnormal)
12783 {
12784 Log1WarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n", Global::IsOnlineOrTransient(lastState)));
12785
12786 /* reset the state to Aborted */
12787 if (mData->mMachineState != MachineState_Aborted)
12788 i_setMachineState(MachineState_Aborted);
12789 }
12790
12791 // any machine settings modified?
12792 if (mData->flModifications)
12793 {
12794 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
12795 i_rollback(false /* aNotify */);
12796 }
12797
12798 mData->mSession.mPID = NIL_RTPROCESS;
12799
12800 if (aReason == Uninit::Unexpected)
12801 {
12802 /* Uninitialization didn't come from #i_checkForDeath(), so tell the
12803 * client watcher thread to update the set of machines that have open
12804 * sessions. */
12805 mParent->i_updateClientWatcher();
12806 }
12807
12808 /* uninitialize all remote controls */
12809 if (mData->mSession.mRemoteControls.size())
12810 {
12811 LogFlowThisFunc(("Closing remote sessions (%d):\n",
12812 mData->mSession.mRemoteControls.size()));
12813
12814 /* Always restart a the beginning, since the iterator is invalidated
12815 * by using erase(). */
12816 for (Data::Session::RemoteControlList::iterator
12817 it = mData->mSession.mRemoteControls.begin();
12818 it != mData->mSession.mRemoteControls.end();
12819 it = mData->mSession.mRemoteControls.begin())
12820 {
12821 ComPtr<IInternalSessionControl> pControl = *it;
12822 mData->mSession.mRemoteControls.erase(it);
12823 multilock.release();
12824 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
12825 HRESULT rc = pControl->Uninitialize();
12826 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
12827 if (FAILED(rc))
12828 Log1WarningThisFunc(("Forgot to close the remote session?\n"));
12829 multilock.acquire();
12830 }
12831 mData->mSession.mRemoteControls.clear();
12832 }
12833
12834 /* Remove all references to the NAT network service. The service will stop
12835 * if all references (also from other VMs) are removed. */
12836 for (; miNATNetworksStarted > 0; miNATNetworksStarted--)
12837 {
12838 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12839 {
12840 BOOL enabled;
12841 HRESULT hrc = mNetworkAdapters[slot]->COMGETTER(Enabled)(&enabled);
12842 if ( FAILED(hrc)
12843 || !enabled)
12844 continue;
12845
12846 NetworkAttachmentType_T type;
12847 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
12848 if ( SUCCEEDED(hrc)
12849 && type == NetworkAttachmentType_NATNetwork)
12850 {
12851 Bstr name;
12852 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
12853 if (SUCCEEDED(hrc))
12854 {
12855 multilock.release();
12856 Utf8Str strName(name);
12857 LogRel(("VM '%s' stops using NAT network '%s'\n",
12858 mUserData->s.strName.c_str(), strName.c_str()));
12859 mParent->i_natNetworkRefDec(strName);
12860 multilock.acquire();
12861 }
12862 }
12863 }
12864 }
12865
12866 /*
12867 * An expected uninitialization can come only from #i_checkForDeath().
12868 * Otherwise it means that something's gone really wrong (for example,
12869 * the Session implementation has released the VirtualBox reference
12870 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
12871 * etc). However, it's also possible, that the client releases the IPC
12872 * semaphore correctly (i.e. before it releases the VirtualBox reference),
12873 * but the VirtualBox release event comes first to the server process.
12874 * This case is practically possible, so we should not assert on an
12875 * unexpected uninit, just log a warning.
12876 */
12877
12878 if (aReason == Uninit::Unexpected)
12879 Log1WarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
12880
12881 if (aReason != Uninit::Normal)
12882 {
12883 mData->mSession.mDirectControl.setNull();
12884 }
12885 else
12886 {
12887 /* this must be null here (see #OnSessionEnd()) */
12888 Assert(mData->mSession.mDirectControl.isNull());
12889 Assert(mData->mSession.mState == SessionState_Unlocking);
12890 Assert(!mData->mSession.mProgress.isNull());
12891 }
12892 if (mData->mSession.mProgress)
12893 {
12894 if (aReason == Uninit::Normal)
12895 mData->mSession.mProgress->i_notifyComplete(S_OK);
12896 else
12897 mData->mSession.mProgress->i_notifyComplete(E_FAIL,
12898 COM_IIDOF(ISession),
12899 getComponentName(),
12900 tr("The VM session was aborted"));
12901 mData->mSession.mProgress.setNull();
12902 }
12903
12904 if (mConsoleTaskData.mProgress)
12905 {
12906 Assert(aReason == Uninit::Abnormal);
12907 mConsoleTaskData.mProgress->i_notifyComplete(E_FAIL,
12908 COM_IIDOF(ISession),
12909 getComponentName(),
12910 tr("The VM session was aborted"));
12911 mConsoleTaskData.mProgress.setNull();
12912 }
12913
12914 /* remove the association between the peer machine and this session machine */
12915 Assert( (SessionMachine*)mData->mSession.mMachine == this
12916 || aReason == Uninit::Unexpected);
12917
12918 /* reset the rest of session data */
12919 mData->mSession.mLockType = LockType_Null;
12920 mData->mSession.mMachine.setNull();
12921 mData->mSession.mState = SessionState_Unlocked;
12922 mData->mSession.mName.setNull();
12923
12924 /* destroy the machine client token before leaving the exclusive lock */
12925 if (mClientToken)
12926 {
12927 delete mClientToken;
12928 mClientToken = NULL;
12929 }
12930
12931 /* fire an event */
12932 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
12933
12934 uninitDataAndChildObjects();
12935
12936 /* free the essential data structure last */
12937 mData.free();
12938
12939 /* release the exclusive lock before setting the below two to NULL */
12940 multilock.release();
12941
12942 unconst(mParent) = NULL;
12943 unconst(mPeer) = NULL;
12944
12945 AuthLibUnload(&mAuthLibCtx);
12946
12947 LogFlowThisFuncLeave();
12948}
12949
12950// util::Lockable interface
12951////////////////////////////////////////////////////////////////////////////////
12952
12953/**
12954 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
12955 * with the primary Machine instance (mPeer).
12956 */
12957RWLockHandle *SessionMachine::lockHandle() const
12958{
12959 AssertReturn(mPeer != NULL, NULL);
12960 return mPeer->lockHandle();
12961}
12962
12963// IInternalMachineControl methods
12964////////////////////////////////////////////////////////////////////////////////
12965
12966/**
12967 * Passes collected guest statistics to performance collector object
12968 */
12969HRESULT SessionMachine::reportVmStatistics(ULONG aValidStats, ULONG aCpuUser,
12970 ULONG aCpuKernel, ULONG aCpuIdle,
12971 ULONG aMemTotal, ULONG aMemFree,
12972 ULONG aMemBalloon, ULONG aMemShared,
12973 ULONG aMemCache, ULONG aPageTotal,
12974 ULONG aAllocVMM, ULONG aFreeVMM,
12975 ULONG aBalloonedVMM, ULONG aSharedVMM,
12976 ULONG aVmNetRx, ULONG aVmNetTx)
12977{
12978#ifdef VBOX_WITH_RESOURCE_USAGE_API
12979 if (mCollectorGuest)
12980 mCollectorGuest->updateStats(aValidStats, aCpuUser, aCpuKernel, aCpuIdle,
12981 aMemTotal, aMemFree, aMemBalloon, aMemShared,
12982 aMemCache, aPageTotal, aAllocVMM, aFreeVMM,
12983 aBalloonedVMM, aSharedVMM, aVmNetRx, aVmNetTx);
12984
12985 return S_OK;
12986#else
12987 NOREF(aValidStats);
12988 NOREF(aCpuUser);
12989 NOREF(aCpuKernel);
12990 NOREF(aCpuIdle);
12991 NOREF(aMemTotal);
12992 NOREF(aMemFree);
12993 NOREF(aMemBalloon);
12994 NOREF(aMemShared);
12995 NOREF(aMemCache);
12996 NOREF(aPageTotal);
12997 NOREF(aAllocVMM);
12998 NOREF(aFreeVMM);
12999 NOREF(aBalloonedVMM);
13000 NOREF(aSharedVMM);
13001 NOREF(aVmNetRx);
13002 NOREF(aVmNetTx);
13003 return E_NOTIMPL;
13004#endif
13005}
13006
13007////////////////////////////////////////////////////////////////////////////////
13008//
13009// SessionMachine task records
13010//
13011////////////////////////////////////////////////////////////////////////////////
13012
13013/**
13014 * Task record for saving the machine state.
13015 */
13016class SessionMachine::SaveStateTask
13017 : public Machine::Task
13018{
13019public:
13020 SaveStateTask(SessionMachine *m,
13021 Progress *p,
13022 const Utf8Str &t,
13023 Reason_T enmReason,
13024 const Utf8Str &strStateFilePath)
13025 : Task(m, p, t),
13026 m_enmReason(enmReason),
13027 m_strStateFilePath(strStateFilePath)
13028 {}
13029
13030private:
13031 void handler()
13032 {
13033 ((SessionMachine *)(Machine *)m_pMachine)->i_saveStateHandler(*this);
13034 }
13035
13036 Reason_T m_enmReason;
13037 Utf8Str m_strStateFilePath;
13038
13039 friend class SessionMachine;
13040};
13041
13042/**
13043 * Task thread implementation for SessionMachine::SaveState(), called from
13044 * SessionMachine::taskHandler().
13045 *
13046 * @note Locks this object for writing.
13047 *
13048 * @param task
13049 * @return
13050 */
13051void SessionMachine::i_saveStateHandler(SaveStateTask &task)
13052{
13053 LogFlowThisFuncEnter();
13054
13055 AutoCaller autoCaller(this);
13056 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
13057 if (FAILED(autoCaller.rc()))
13058 {
13059 /* we might have been uninitialized because the session was accidentally
13060 * closed by the client, so don't assert */
13061 HRESULT rc = setError(E_FAIL,
13062 tr("The session has been accidentally closed"));
13063 task.m_pProgress->i_notifyComplete(rc);
13064 LogFlowThisFuncLeave();
13065 return;
13066 }
13067
13068 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13069
13070 HRESULT rc = S_OK;
13071
13072 try
13073 {
13074 ComPtr<IInternalSessionControl> directControl;
13075 if (mData->mSession.mLockType == LockType_VM)
13076 directControl = mData->mSession.mDirectControl;
13077 if (directControl.isNull())
13078 throw setError(VBOX_E_INVALID_VM_STATE,
13079 tr("Trying to save state without a running VM"));
13080 alock.release();
13081 BOOL fSuspendedBySave;
13082 rc = directControl->SaveStateWithReason(task.m_enmReason, task.m_pProgress, Bstr(task.m_strStateFilePath).raw(), task.m_machineStateBackup != MachineState_Paused, &fSuspendedBySave);
13083 Assert(!fSuspendedBySave);
13084 alock.acquire();
13085
13086 AssertStmt( (SUCCEEDED(rc) && mData->mMachineState == MachineState_Saved)
13087 || (FAILED(rc) && mData->mMachineState == MachineState_Saving),
13088 throw E_FAIL);
13089
13090 if (SUCCEEDED(rc))
13091 {
13092 mSSData->strStateFilePath = task.m_strStateFilePath;
13093
13094 /* save all VM settings */
13095 rc = i_saveSettings(NULL);
13096 // no need to check whether VirtualBox.xml needs saving also since
13097 // we can't have a name change pending at this point
13098 }
13099 else
13100 {
13101 // On failure, set the state to the state we had at the beginning.
13102 i_setMachineState(task.m_machineStateBackup);
13103 i_updateMachineStateOnClient();
13104
13105 // Delete the saved state file (might have been already created).
13106 // No need to check whether this is shared with a snapshot here
13107 // because we certainly created a fresh saved state file here.
13108 RTFileDelete(task.m_strStateFilePath.c_str());
13109 }
13110 }
13111 catch (HRESULT aRC) { rc = aRC; }
13112
13113 task.m_pProgress->i_notifyComplete(rc);
13114
13115 LogFlowThisFuncLeave();
13116}
13117
13118/**
13119 * @note Locks this object for writing.
13120 */
13121HRESULT SessionMachine::saveState(ComPtr<IProgress> &aProgress)
13122{
13123 return i_saveStateWithReason(Reason_Unspecified, aProgress);
13124}
13125
13126HRESULT SessionMachine::i_saveStateWithReason(Reason_T aReason, ComPtr<IProgress> &aProgress)
13127{
13128 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13129
13130 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
13131 if (FAILED(rc)) return rc;
13132
13133 if ( mData->mMachineState != MachineState_Running
13134 && mData->mMachineState != MachineState_Paused
13135 )
13136 return setError(VBOX_E_INVALID_VM_STATE,
13137 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
13138 Global::stringifyMachineState(mData->mMachineState));
13139
13140 ComObjPtr<Progress> pProgress;
13141 pProgress.createObject();
13142 rc = pProgress->init(i_getVirtualBox(),
13143 static_cast<IMachine *>(this) /* aInitiator */,
13144 tr("Saving the execution state of the virtual machine"),
13145 FALSE /* aCancelable */);
13146 if (FAILED(rc))
13147 return rc;
13148
13149 Utf8Str strStateFilePath;
13150 i_composeSavedStateFilename(strStateFilePath);
13151
13152 /* create and start the task on a separate thread (note that it will not
13153 * start working until we release alock) */
13154 SaveStateTask *pTask = new SaveStateTask(this, pProgress, "SaveState", aReason, strStateFilePath);
13155 rc = pTask->createThread();
13156 if (FAILED(rc))
13157 return rc;
13158
13159 /* set the state to Saving (expected by Session::SaveStateWithReason()) */
13160 i_setMachineState(MachineState_Saving);
13161 i_updateMachineStateOnClient();
13162
13163 pProgress.queryInterfaceTo(aProgress.asOutParam());
13164
13165 return S_OK;
13166}
13167
13168/**
13169 * @note Locks this object for writing.
13170 */
13171HRESULT SessionMachine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
13172{
13173 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13174
13175 HRESULT rc = i_checkStateDependency(MutableStateDep);
13176 if (FAILED(rc)) return rc;
13177
13178 if ( mData->mMachineState != MachineState_PoweredOff
13179 && mData->mMachineState != MachineState_Teleported
13180 && mData->mMachineState != MachineState_Aborted
13181 )
13182 return setError(VBOX_E_INVALID_VM_STATE,
13183 tr("Cannot adopt the saved machine state as the machine is not in Powered Off, Teleported or Aborted state (machine state: %s)"),
13184 Global::stringifyMachineState(mData->mMachineState));
13185
13186 com::Utf8Str stateFilePathFull;
13187 int vrc = i_calculateFullPath(aSavedStateFile, stateFilePathFull);
13188 if (RT_FAILURE(vrc))
13189 return setError(VBOX_E_FILE_ERROR,
13190 tr("Invalid saved state file path '%s' (%Rrc)"),
13191 aSavedStateFile.c_str(),
13192 vrc);
13193
13194 mSSData->strStateFilePath = stateFilePathFull;
13195
13196 /* The below i_setMachineState() will detect the state transition and will
13197 * update the settings file */
13198
13199 return i_setMachineState(MachineState_Saved);
13200}
13201
13202/**
13203 * @note Locks this object for writing.
13204 */
13205HRESULT SessionMachine::discardSavedState(BOOL aFRemoveFile)
13206{
13207 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13208
13209 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
13210 if (FAILED(rc)) return rc;
13211
13212 if (mData->mMachineState != MachineState_Saved)
13213 return setError(VBOX_E_INVALID_VM_STATE,
13214 tr("Cannot delete the machine state as the machine is not in the saved state (machine state: %s)"),
13215 Global::stringifyMachineState(mData->mMachineState));
13216
13217 mRemoveSavedState = RT_BOOL(aFRemoveFile);
13218
13219 /*
13220 * Saved -> PoweredOff transition will be detected in the SessionMachine
13221 * and properly handled.
13222 */
13223 rc = i_setMachineState(MachineState_PoweredOff);
13224 return rc;
13225}
13226
13227
13228/**
13229 * @note Locks the same as #i_setMachineState() does.
13230 */
13231HRESULT SessionMachine::updateState(MachineState_T aState)
13232{
13233 return i_setMachineState(aState);
13234}
13235
13236/**
13237 * @note Locks this object for writing.
13238 */
13239HRESULT SessionMachine::beginPowerUp(const ComPtr<IProgress> &aProgress)
13240{
13241 IProgress *pProgress(aProgress);
13242
13243 LogFlowThisFunc(("aProgress=%p\n", pProgress));
13244
13245 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13246
13247 if (mData->mSession.mState != SessionState_Locked)
13248 return VBOX_E_INVALID_OBJECT_STATE;
13249
13250 if (!mData->mSession.mProgress.isNull())
13251 mData->mSession.mProgress->setOtherProgressObject(pProgress);
13252
13253 /* If we didn't reference the NAT network service yet, add a reference to
13254 * force a start */
13255 if (miNATNetworksStarted < 1)
13256 {
13257 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
13258 {
13259 BOOL enabled;
13260 HRESULT hrc = mNetworkAdapters[slot]->COMGETTER(Enabled)(&enabled);
13261 if ( FAILED(hrc)
13262 || !enabled)
13263 continue;
13264
13265 NetworkAttachmentType_T type;
13266 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
13267 if ( SUCCEEDED(hrc)
13268 && type == NetworkAttachmentType_NATNetwork)
13269 {
13270 Bstr name;
13271 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
13272 if (SUCCEEDED(hrc))
13273 {
13274 Utf8Str strName(name);
13275 LogRel(("VM '%s' starts using NAT network '%s'\n",
13276 mUserData->s.strName.c_str(), strName.c_str()));
13277 mPeer->lockHandle()->unlockWrite();
13278 mParent->i_natNetworkRefInc(strName);
13279#ifdef RT_LOCK_STRICT
13280 mPeer->lockHandle()->lockWrite(RT_SRC_POS);
13281#else
13282 mPeer->lockHandle()->lockWrite();
13283#endif
13284 }
13285 }
13286 }
13287 miNATNetworksStarted++;
13288 }
13289
13290 LogFlowThisFunc(("returns S_OK.\n"));
13291 return S_OK;
13292}
13293
13294/**
13295 * @note Locks this object for writing.
13296 */
13297HRESULT SessionMachine::endPowerUp(LONG aResult)
13298{
13299 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13300
13301 if (mData->mSession.mState != SessionState_Locked)
13302 return VBOX_E_INVALID_OBJECT_STATE;
13303
13304 /* Finalize the LaunchVMProcess progress object. */
13305 if (mData->mSession.mProgress)
13306 {
13307 mData->mSession.mProgress->notifyComplete((HRESULT)aResult);
13308 mData->mSession.mProgress.setNull();
13309 }
13310
13311 if (SUCCEEDED((HRESULT)aResult))
13312 {
13313#ifdef VBOX_WITH_RESOURCE_USAGE_API
13314 /* The VM has been powered up successfully, so it makes sense
13315 * now to offer the performance metrics for a running machine
13316 * object. Doing it earlier wouldn't be safe. */
13317 i_registerMetrics(mParent->i_performanceCollector(), mPeer,
13318 mData->mSession.mPID);
13319#endif /* VBOX_WITH_RESOURCE_USAGE_API */
13320 }
13321
13322 return S_OK;
13323}
13324
13325/**
13326 * @note Locks this object for writing.
13327 */
13328HRESULT SessionMachine::beginPoweringDown(ComPtr<IProgress> &aProgress)
13329{
13330 LogFlowThisFuncEnter();
13331
13332 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13333
13334 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
13335 E_FAIL);
13336
13337 /* create a progress object to track operation completion */
13338 ComObjPtr<Progress> pProgress;
13339 pProgress.createObject();
13340 pProgress->init(i_getVirtualBox(),
13341 static_cast<IMachine *>(this) /* aInitiator */,
13342 tr("Stopping the virtual machine"),
13343 FALSE /* aCancelable */);
13344
13345 /* fill in the console task data */
13346 mConsoleTaskData.mLastState = mData->mMachineState;
13347 mConsoleTaskData.mProgress = pProgress;
13348
13349 /* set the state to Stopping (this is expected by Console::PowerDown()) */
13350 i_setMachineState(MachineState_Stopping);
13351
13352 pProgress.queryInterfaceTo(aProgress.asOutParam());
13353
13354 return S_OK;
13355}
13356
13357/**
13358 * @note Locks this object for writing.
13359 */
13360HRESULT SessionMachine::endPoweringDown(LONG aResult,
13361 const com::Utf8Str &aErrMsg)
13362{
13363 LogFlowThisFuncEnter();
13364
13365 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13366
13367 AssertReturn( ( (SUCCEEDED(aResult) && mData->mMachineState == MachineState_PoweredOff)
13368 || (FAILED(aResult) && mData->mMachineState == MachineState_Stopping))
13369 && mConsoleTaskData.mLastState != MachineState_Null,
13370 E_FAIL);
13371
13372 /*
13373 * On failure, set the state to the state we had when BeginPoweringDown()
13374 * was called (this is expected by Console::PowerDown() and the associated
13375 * task). On success the VM process already changed the state to
13376 * MachineState_PoweredOff, so no need to do anything.
13377 */
13378 if (FAILED(aResult))
13379 i_setMachineState(mConsoleTaskData.mLastState);
13380
13381 /* notify the progress object about operation completion */
13382 Assert(mConsoleTaskData.mProgress);
13383 if (SUCCEEDED(aResult))
13384 mConsoleTaskData.mProgress->i_notifyComplete(S_OK);
13385 else
13386 {
13387 if (aErrMsg.length())
13388 mConsoleTaskData.mProgress->i_notifyComplete(aResult,
13389 COM_IIDOF(ISession),
13390 getComponentName(),
13391 aErrMsg.c_str());
13392 else
13393 mConsoleTaskData.mProgress->i_notifyComplete(aResult);
13394 }
13395
13396 /* clear out the temporary saved state data */
13397 mConsoleTaskData.mLastState = MachineState_Null;
13398 mConsoleTaskData.mProgress.setNull();
13399
13400 LogFlowThisFuncLeave();
13401 return S_OK;
13402}
13403
13404
13405/**
13406 * Goes through the USB filters of the given machine to see if the given
13407 * device matches any filter or not.
13408 *
13409 * @note Locks the same as USBController::hasMatchingFilter() does.
13410 */
13411HRESULT SessionMachine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
13412 BOOL *aMatched,
13413 ULONG *aMaskedInterfaces)
13414{
13415 LogFlowThisFunc(("\n"));
13416
13417#ifdef VBOX_WITH_USB
13418 *aMatched = mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedInterfaces);
13419#else
13420 NOREF(aDevice);
13421 NOREF(aMaskedInterfaces);
13422 *aMatched = FALSE;
13423#endif
13424
13425 return S_OK;
13426}
13427
13428/**
13429 * @note Locks the same as Host::captureUSBDevice() does.
13430 */
13431HRESULT SessionMachine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
13432{
13433 LogFlowThisFunc(("\n"));
13434
13435#ifdef VBOX_WITH_USB
13436 /* if captureDeviceForVM() fails, it must have set extended error info */
13437 clearError();
13438 MultiResult rc = mParent->i_host()->i_checkUSBProxyService();
13439 if (FAILED(rc)) return rc;
13440
13441 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13442 AssertReturn(service, E_FAIL);
13443 return service->captureDeviceForVM(this, aId.ref(), aCaptureFilename);
13444#else
13445 NOREF(aId);
13446 return E_NOTIMPL;
13447#endif
13448}
13449
13450/**
13451 * @note Locks the same as Host::detachUSBDevice() does.
13452 */
13453HRESULT SessionMachine::detachUSBDevice(const com::Guid &aId,
13454 BOOL aDone)
13455{
13456 LogFlowThisFunc(("\n"));
13457
13458#ifdef VBOX_WITH_USB
13459 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13460 AssertReturn(service, E_FAIL);
13461 return service->detachDeviceFromVM(this, aId.ref(), !!aDone);
13462#else
13463 NOREF(aId);
13464 NOREF(aDone);
13465 return E_NOTIMPL;
13466#endif
13467}
13468
13469/**
13470 * Inserts all machine filters to the USB proxy service and then calls
13471 * Host::autoCaptureUSBDevices().
13472 *
13473 * Called by Console from the VM process upon VM startup.
13474 *
13475 * @note Locks what called methods lock.
13476 */
13477HRESULT SessionMachine::autoCaptureUSBDevices()
13478{
13479 LogFlowThisFunc(("\n"));
13480
13481#ifdef VBOX_WITH_USB
13482 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(true /* aInsertFilters */);
13483 AssertComRC(rc);
13484 NOREF(rc);
13485
13486 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13487 AssertReturn(service, E_FAIL);
13488 return service->autoCaptureDevicesForVM(this);
13489#else
13490 return S_OK;
13491#endif
13492}
13493
13494/**
13495 * Removes all machine filters from the USB proxy service and then calls
13496 * Host::detachAllUSBDevices().
13497 *
13498 * Called by Console from the VM process upon normal VM termination or by
13499 * SessionMachine::uninit() upon abnormal VM termination (from under the
13500 * Machine/SessionMachine lock).
13501 *
13502 * @note Locks what called methods lock.
13503 */
13504HRESULT SessionMachine::detachAllUSBDevices(BOOL aDone)
13505{
13506 LogFlowThisFunc(("\n"));
13507
13508#ifdef VBOX_WITH_USB
13509 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
13510 AssertComRC(rc);
13511 NOREF(rc);
13512
13513 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13514 AssertReturn(service, E_FAIL);
13515 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
13516#else
13517 NOREF(aDone);
13518 return S_OK;
13519#endif
13520}
13521
13522/**
13523 * @note Locks this object for writing.
13524 */
13525HRESULT SessionMachine::onSessionEnd(const ComPtr<ISession> &aSession,
13526 ComPtr<IProgress> &aProgress)
13527{
13528 LogFlowThisFuncEnter();
13529
13530 LogFlowThisFunc(("callerstate=%d\n", getObjectState().getState()));
13531 /*
13532 * We don't assert below because it might happen that a non-direct session
13533 * informs us it is closed right after we've been uninitialized -- it's ok.
13534 */
13535
13536 /* get IInternalSessionControl interface */
13537 ComPtr<IInternalSessionControl> control(aSession);
13538
13539 ComAssertRet(!control.isNull(), E_INVALIDARG);
13540
13541 /* Creating a Progress object requires the VirtualBox lock, and
13542 * thus locking it here is required by the lock order rules. */
13543 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
13544
13545 if (control == mData->mSession.mDirectControl)
13546 {
13547 /* The direct session is being normally closed by the client process
13548 * ----------------------------------------------------------------- */
13549
13550 /* go to the closing state (essential for all open*Session() calls and
13551 * for #i_checkForDeath()) */
13552 Assert(mData->mSession.mState == SessionState_Locked);
13553 mData->mSession.mState = SessionState_Unlocking;
13554
13555 /* set direct control to NULL to release the remote instance */
13556 mData->mSession.mDirectControl.setNull();
13557 LogFlowThisFunc(("Direct control is set to NULL\n"));
13558
13559 if (mData->mSession.mProgress)
13560 {
13561 /* finalize the progress, someone might wait if a frontend
13562 * closes the session before powering on the VM. */
13563 mData->mSession.mProgress->notifyComplete(E_FAIL,
13564 COM_IIDOF(ISession),
13565 getComponentName(),
13566 tr("The VM session was closed before any attempt to power it on"));
13567 mData->mSession.mProgress.setNull();
13568 }
13569
13570 /* Create the progress object the client will use to wait until
13571 * #i_checkForDeath() is called to uninitialize this session object after
13572 * it releases the IPC semaphore.
13573 * Note! Because we're "reusing" mProgress here, this must be a proxy
13574 * object just like for LaunchVMProcess. */
13575 Assert(mData->mSession.mProgress.isNull());
13576 ComObjPtr<ProgressProxy> progress;
13577 progress.createObject();
13578 ComPtr<IUnknown> pPeer(mPeer);
13579 progress->init(mParent, pPeer,
13580 Bstr(tr("Closing session")).raw(),
13581 FALSE /* aCancelable */);
13582 progress.queryInterfaceTo(aProgress.asOutParam());
13583 mData->mSession.mProgress = progress;
13584 }
13585 else
13586 {
13587 /* the remote session is being normally closed */
13588 bool found = false;
13589 for (Data::Session::RemoteControlList::iterator
13590 it = mData->mSession.mRemoteControls.begin();
13591 it != mData->mSession.mRemoteControls.end();
13592 ++it)
13593 {
13594 if (control == *it)
13595 {
13596 found = true;
13597 // This MUST be erase(it), not remove(*it) as the latter
13598 // triggers a very nasty use after free due to the place where
13599 // the value "lives".
13600 mData->mSession.mRemoteControls.erase(it);
13601 break;
13602 }
13603 }
13604 ComAssertMsgRet(found, ("The session is not found in the session list!"),
13605 E_INVALIDARG);
13606 }
13607
13608 /* signal the client watcher thread, because the client is going away */
13609 mParent->i_updateClientWatcher();
13610
13611 LogFlowThisFuncLeave();
13612 return S_OK;
13613}
13614
13615HRESULT SessionMachine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
13616 std::vector<com::Utf8Str> &aValues,
13617 std::vector<LONG64> &aTimestamps,
13618 std::vector<com::Utf8Str> &aFlags)
13619{
13620 LogFlowThisFunc(("\n"));
13621
13622#ifdef VBOX_WITH_GUEST_PROPS
13623 using namespace guestProp;
13624
13625 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13626
13627 size_t cEntries = mHWData->mGuestProperties.size();
13628 aNames.resize(cEntries);
13629 aValues.resize(cEntries);
13630 aTimestamps.resize(cEntries);
13631 aFlags.resize(cEntries);
13632
13633 size_t i = 0;
13634 for (HWData::GuestPropertyMap::const_iterator
13635 it = mHWData->mGuestProperties.begin();
13636 it != mHWData->mGuestProperties.end();
13637 ++it, ++i)
13638 {
13639 char szFlags[MAX_FLAGS_LEN + 1];
13640 aNames[i] = it->first;
13641 aValues[i] = it->second.strValue;
13642 aTimestamps[i] = it->second.mTimestamp;
13643
13644 /* If it is NULL, keep it NULL. */
13645 if (it->second.mFlags)
13646 {
13647 writeFlags(it->second.mFlags, szFlags);
13648 aFlags[i] = szFlags;
13649 }
13650 else
13651 aFlags[i] = "";
13652 }
13653 return S_OK;
13654#else
13655 ReturnComNotImplemented();
13656#endif
13657}
13658
13659HRESULT SessionMachine::pushGuestProperty(const com::Utf8Str &aName,
13660 const com::Utf8Str &aValue,
13661 LONG64 aTimestamp,
13662 const com::Utf8Str &aFlags)
13663{
13664 LogFlowThisFunc(("\n"));
13665
13666#ifdef VBOX_WITH_GUEST_PROPS
13667 using namespace guestProp;
13668
13669 try
13670 {
13671 /*
13672 * Convert input up front.
13673 */
13674 uint32_t fFlags = NILFLAG;
13675 if (aFlags.length())
13676 {
13677 int vrc = validateFlags(aFlags.c_str(), &fFlags);
13678 AssertRCReturn(vrc, E_INVALIDARG);
13679 }
13680
13681 /*
13682 * Now grab the object lock, validate the state and do the update.
13683 */
13684
13685 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13686
13687 if (!Global::IsOnline(mData->mMachineState))
13688 {
13689 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
13690 VBOX_E_INVALID_VM_STATE);
13691 }
13692
13693 i_setModified(IsModified_MachineData);
13694 mHWData.backup();
13695
13696 bool fDelete = !aValue.length();
13697 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
13698 if (it != mHWData->mGuestProperties.end())
13699 {
13700 if (!fDelete)
13701 {
13702 it->second.strValue = aValue;
13703 it->second.mTimestamp = aTimestamp;
13704 it->second.mFlags = fFlags;
13705 }
13706 else
13707 mHWData->mGuestProperties.erase(it);
13708
13709 mData->mGuestPropertiesModified = TRUE;
13710 }
13711 else if (!fDelete)
13712 {
13713 HWData::GuestProperty prop;
13714 prop.strValue = aValue;
13715 prop.mTimestamp = aTimestamp;
13716 prop.mFlags = fFlags;
13717
13718 mHWData->mGuestProperties[aName] = prop;
13719 mData->mGuestPropertiesModified = TRUE;
13720 }
13721
13722 alock.release();
13723
13724 mParent->i_onGuestPropertyChange(mData->mUuid,
13725 Bstr(aName).raw(),
13726 Bstr(aValue).raw(),
13727 Bstr(aFlags).raw());
13728 }
13729 catch (...)
13730 {
13731 return VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
13732 }
13733 return S_OK;
13734#else
13735 ReturnComNotImplemented();
13736#endif
13737}
13738
13739
13740HRESULT SessionMachine::lockMedia()
13741{
13742 AutoMultiWriteLock2 alock(this->lockHandle(),
13743 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13744
13745 AssertReturn( mData->mMachineState == MachineState_Starting
13746 || mData->mMachineState == MachineState_Restoring
13747 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
13748
13749 clearError();
13750 alock.release();
13751 return i_lockMedia();
13752}
13753
13754HRESULT SessionMachine::unlockMedia()
13755{
13756 HRESULT hrc = i_unlockMedia();
13757 return hrc;
13758}
13759
13760HRESULT SessionMachine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
13761 ComPtr<IMediumAttachment> &aNewAttachment)
13762{
13763 // request the host lock first, since might be calling Host methods for getting host drives;
13764 // next, protect the media tree all the while we're in here, as well as our member variables
13765 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
13766 this->lockHandle(),
13767 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13768
13769 IMediumAttachment *iAttach = aAttachment;
13770 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(iAttach);
13771
13772 Utf8Str ctrlName;
13773 LONG lPort;
13774 LONG lDevice;
13775 bool fTempEject;
13776 {
13777 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13778
13779 /* Need to query the details first, as the IMediumAttachment reference
13780 * might be to the original settings, which we are going to change. */
13781 ctrlName = pAttach->i_getControllerName();
13782 lPort = pAttach->i_getPort();
13783 lDevice = pAttach->i_getDevice();
13784 fTempEject = pAttach->i_getTempEject();
13785 }
13786
13787 if (!fTempEject)
13788 {
13789 /* Remember previously mounted medium. The medium before taking the
13790 * backup is not necessarily the same thing. */
13791 ComObjPtr<Medium> oldmedium;
13792 oldmedium = pAttach->i_getMedium();
13793
13794 i_setModified(IsModified_Storage);
13795 mMediumAttachments.backup();
13796
13797 // The backup operation makes the pAttach reference point to the
13798 // old settings. Re-get the correct reference.
13799 pAttach = i_findAttachment(*mMediumAttachments.data(),
13800 ctrlName,
13801 lPort,
13802 lDevice);
13803
13804 {
13805 AutoCaller autoAttachCaller(this);
13806 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
13807
13808 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13809 if (!oldmedium.isNull())
13810 oldmedium->i_removeBackReference(mData->mUuid);
13811
13812 pAttach->i_updateMedium(NULL);
13813 pAttach->i_updateEjected();
13814 }
13815
13816 i_setModified(IsModified_Storage);
13817 }
13818 else
13819 {
13820 {
13821 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13822 pAttach->i_updateEjected();
13823 }
13824 }
13825
13826 pAttach.queryInterfaceTo(aNewAttachment.asOutParam());
13827
13828 return S_OK;
13829}
13830
13831HRESULT SessionMachine::authenticateExternal(const std::vector<com::Utf8Str> &aAuthParams,
13832 com::Utf8Str &aResult)
13833{
13834 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13835
13836 HRESULT hr = S_OK;
13837
13838 if (!mAuthLibCtx.hAuthLibrary)
13839 {
13840 /* Load the external authentication library. */
13841 Bstr authLibrary;
13842 mVRDEServer->COMGETTER(AuthLibrary)(authLibrary.asOutParam());
13843
13844 Utf8Str filename = authLibrary;
13845
13846 int rc = AuthLibLoad(&mAuthLibCtx, filename.c_str());
13847 if (RT_FAILURE(rc))
13848 {
13849 hr = setError(E_FAIL,
13850 tr("Could not load the external authentication library '%s' (%Rrc)"),
13851 filename.c_str(), rc);
13852 }
13853 }
13854
13855 /* The auth library might need the machine lock. */
13856 alock.release();
13857
13858 if (FAILED(hr))
13859 return hr;
13860
13861 if (aAuthParams[0] == "VRDEAUTH" && aAuthParams.size() == 7)
13862 {
13863 enum VRDEAuthParams
13864 {
13865 parmUuid = 1,
13866 parmGuestJudgement,
13867 parmUser,
13868 parmPassword,
13869 parmDomain,
13870 parmClientId
13871 };
13872
13873 AuthResult result = AuthResultAccessDenied;
13874
13875 Guid uuid(aAuthParams[parmUuid]);
13876 AuthGuestJudgement guestJudgement = (AuthGuestJudgement)aAuthParams[parmGuestJudgement].toUInt32();
13877 uint32_t u32ClientId = aAuthParams[parmClientId].toUInt32();
13878
13879 result = AuthLibAuthenticate(&mAuthLibCtx,
13880 uuid.raw(), guestJudgement,
13881 aAuthParams[parmUser].c_str(),
13882 aAuthParams[parmPassword].c_str(),
13883 aAuthParams[parmDomain].c_str(),
13884 u32ClientId);
13885
13886 /* Hack: aAuthParams[parmPassword] is const but the code believes in writable memory. */
13887 size_t cbPassword = aAuthParams[parmPassword].length();
13888 if (cbPassword)
13889 {
13890 RTMemWipeThoroughly((void *)aAuthParams[parmPassword].c_str(), cbPassword, 10 /* cPasses */);
13891 memset((void *)aAuthParams[parmPassword].c_str(), 'x', cbPassword);
13892 }
13893
13894 if (result == AuthResultAccessGranted)
13895 aResult = "granted";
13896 else
13897 aResult = "denied";
13898
13899 LogRel(("AUTH: VRDE authentification for user '%s' result '%s'\n",
13900 aAuthParams[parmUser].c_str(), aResult.c_str()));
13901 }
13902 else if (aAuthParams[0] == "VRDEAUTHDISCONNECT" && aAuthParams.size() == 3)
13903 {
13904 enum VRDEAuthDisconnectParams
13905 {
13906 parmUuid = 1,
13907 parmClientId
13908 };
13909
13910 Guid uuid(aAuthParams[parmUuid]);
13911 uint32_t u32ClientId = 0;
13912 AuthLibDisconnect(&mAuthLibCtx, uuid.raw(), u32ClientId);
13913 }
13914 else
13915 {
13916 hr = E_INVALIDARG;
13917 }
13918
13919 return hr;
13920}
13921
13922// public methods only for internal purposes
13923/////////////////////////////////////////////////////////////////////////////
13924
13925#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
13926/**
13927 * Called from the client watcher thread to check for expected or unexpected
13928 * death of the client process that has a direct session to this machine.
13929 *
13930 * On Win32 and on OS/2, this method is called only when we've got the
13931 * mutex (i.e. the client has either died or terminated normally) so it always
13932 * returns @c true (the client is terminated, the session machine is
13933 * uninitialized).
13934 *
13935 * On other platforms, the method returns @c true if the client process has
13936 * terminated normally or abnormally and the session machine was uninitialized,
13937 * and @c false if the client process is still alive.
13938 *
13939 * @note Locks this object for writing.
13940 */
13941bool SessionMachine::i_checkForDeath()
13942{
13943 Uninit::Reason reason;
13944 bool terminated = false;
13945
13946 /* Enclose autoCaller with a block because calling uninit() from under it
13947 * will deadlock. */
13948 {
13949 AutoCaller autoCaller(this);
13950 if (!autoCaller.isOk())
13951 {
13952 /* return true if not ready, to cause the client watcher to exclude
13953 * the corresponding session from watching */
13954 LogFlowThisFunc(("Already uninitialized!\n"));
13955 return true;
13956 }
13957
13958 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13959
13960 /* Determine the reason of death: if the session state is Closing here,
13961 * everything is fine. Otherwise it means that the client did not call
13962 * OnSessionEnd() before it released the IPC semaphore. This may happen
13963 * either because the client process has abnormally terminated, or
13964 * because it simply forgot to call ISession::Close() before exiting. We
13965 * threat the latter also as an abnormal termination (see
13966 * Session::uninit() for details). */
13967 reason = mData->mSession.mState == SessionState_Unlocking ?
13968 Uninit::Normal :
13969 Uninit::Abnormal;
13970
13971 if (mClientToken)
13972 terminated = mClientToken->release();
13973 } /* AutoCaller block */
13974
13975 if (terminated)
13976 uninit(reason);
13977
13978 return terminated;
13979}
13980
13981void SessionMachine::i_getTokenId(Utf8Str &strTokenId)
13982{
13983 LogFlowThisFunc(("\n"));
13984
13985 strTokenId.setNull();
13986
13987 AutoCaller autoCaller(this);
13988 AssertComRCReturnVoid(autoCaller.rc());
13989
13990 Assert(mClientToken);
13991 if (mClientToken)
13992 mClientToken->getId(strTokenId);
13993}
13994#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
13995IToken *SessionMachine::i_getToken()
13996{
13997 LogFlowThisFunc(("\n"));
13998
13999 AutoCaller autoCaller(this);
14000 AssertComRCReturn(autoCaller.rc(), NULL);
14001
14002 Assert(mClientToken);
14003 if (mClientToken)
14004 return mClientToken->getToken();
14005 else
14006 return NULL;
14007}
14008#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
14009
14010Machine::ClientToken *SessionMachine::i_getClientToken()
14011{
14012 LogFlowThisFunc(("\n"));
14013
14014 AutoCaller autoCaller(this);
14015 AssertComRCReturn(autoCaller.rc(), NULL);
14016
14017 return mClientToken;
14018}
14019
14020
14021/**
14022 * @note Locks this object for reading.
14023 */
14024HRESULT SessionMachine::i_onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
14025{
14026 LogFlowThisFunc(("\n"));
14027
14028 AutoCaller autoCaller(this);
14029 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14030
14031 ComPtr<IInternalSessionControl> directControl;
14032 {
14033 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14034 if (mData->mSession.mLockType == LockType_VM)
14035 directControl = mData->mSession.mDirectControl;
14036 }
14037
14038 /* ignore notifications sent after #OnSessionEnd() is called */
14039 if (!directControl)
14040 return S_OK;
14041
14042 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
14043}
14044
14045/**
14046 * @note Locks this object for reading.
14047 */
14048HRESULT SessionMachine::i_onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
14049 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort,
14050 IN_BSTR aGuestIp, LONG aGuestPort)
14051{
14052 LogFlowThisFunc(("\n"));
14053
14054 AutoCaller autoCaller(this);
14055 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14056
14057 ComPtr<IInternalSessionControl> directControl;
14058 {
14059 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14060 if (mData->mSession.mLockType == LockType_VM)
14061 directControl = mData->mSession.mDirectControl;
14062 }
14063
14064 /* ignore notifications sent after #OnSessionEnd() is called */
14065 if (!directControl)
14066 return S_OK;
14067 /*
14068 * instead acting like callback we ask IVirtualBox deliver corresponding event
14069 */
14070
14071 mParent->i_onNatRedirectChange(i_getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp,
14072 (uint16_t)aHostPort, aGuestIp, (uint16_t)aGuestPort);
14073 return S_OK;
14074}
14075
14076/**
14077 * @note Locks this object for reading.
14078 */
14079HRESULT SessionMachine::i_onSerialPortChange(ISerialPort *serialPort)
14080{
14081 LogFlowThisFunc(("\n"));
14082
14083 AutoCaller autoCaller(this);
14084 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14085
14086 ComPtr<IInternalSessionControl> directControl;
14087 {
14088 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14089 if (mData->mSession.mLockType == LockType_VM)
14090 directControl = mData->mSession.mDirectControl;
14091 }
14092
14093 /* ignore notifications sent after #OnSessionEnd() is called */
14094 if (!directControl)
14095 return S_OK;
14096
14097 return directControl->OnSerialPortChange(serialPort);
14098}
14099
14100/**
14101 * @note Locks this object for reading.
14102 */
14103HRESULT SessionMachine::i_onParallelPortChange(IParallelPort *parallelPort)
14104{
14105 LogFlowThisFunc(("\n"));
14106
14107 AutoCaller autoCaller(this);
14108 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14109
14110 ComPtr<IInternalSessionControl> directControl;
14111 {
14112 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14113 if (mData->mSession.mLockType == LockType_VM)
14114 directControl = mData->mSession.mDirectControl;
14115 }
14116
14117 /* ignore notifications sent after #OnSessionEnd() is called */
14118 if (!directControl)
14119 return S_OK;
14120
14121 return directControl->OnParallelPortChange(parallelPort);
14122}
14123
14124/**
14125 * @note Locks this object for reading.
14126 */
14127HRESULT SessionMachine::i_onStorageControllerChange()
14128{
14129 LogFlowThisFunc(("\n"));
14130
14131 AutoCaller autoCaller(this);
14132 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14133
14134 ComPtr<IInternalSessionControl> directControl;
14135 {
14136 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14137 if (mData->mSession.mLockType == LockType_VM)
14138 directControl = mData->mSession.mDirectControl;
14139 }
14140
14141 /* ignore notifications sent after #OnSessionEnd() is called */
14142 if (!directControl)
14143 return S_OK;
14144
14145 return directControl->OnStorageControllerChange();
14146}
14147
14148/**
14149 * @note Locks this object for reading.
14150 */
14151HRESULT SessionMachine::i_onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
14152{
14153 LogFlowThisFunc(("\n"));
14154
14155 AutoCaller autoCaller(this);
14156 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14157
14158 ComPtr<IInternalSessionControl> directControl;
14159 {
14160 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14161 if (mData->mSession.mLockType == LockType_VM)
14162 directControl = mData->mSession.mDirectControl;
14163 }
14164
14165 /* ignore notifications sent after #OnSessionEnd() is called */
14166 if (!directControl)
14167 return S_OK;
14168
14169 return directControl->OnMediumChange(aAttachment, aForce);
14170}
14171
14172/**
14173 * @note Locks this object for reading.
14174 */
14175HRESULT SessionMachine::i_onCPUChange(ULONG aCPU, BOOL aRemove)
14176{
14177 LogFlowThisFunc(("\n"));
14178
14179 AutoCaller autoCaller(this);
14180 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14181
14182 ComPtr<IInternalSessionControl> directControl;
14183 {
14184 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14185 if (mData->mSession.mLockType == LockType_VM)
14186 directControl = mData->mSession.mDirectControl;
14187 }
14188
14189 /* ignore notifications sent after #OnSessionEnd() is called */
14190 if (!directControl)
14191 return S_OK;
14192
14193 return directControl->OnCPUChange(aCPU, aRemove);
14194}
14195
14196HRESULT SessionMachine::i_onCPUExecutionCapChange(ULONG aExecutionCap)
14197{
14198 LogFlowThisFunc(("\n"));
14199
14200 AutoCaller autoCaller(this);
14201 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14202
14203 ComPtr<IInternalSessionControl> directControl;
14204 {
14205 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14206 if (mData->mSession.mLockType == LockType_VM)
14207 directControl = mData->mSession.mDirectControl;
14208 }
14209
14210 /* ignore notifications sent after #OnSessionEnd() is called */
14211 if (!directControl)
14212 return S_OK;
14213
14214 return directControl->OnCPUExecutionCapChange(aExecutionCap);
14215}
14216
14217/**
14218 * @note Locks this object for reading.
14219 */
14220HRESULT SessionMachine::i_onVRDEServerChange(BOOL aRestart)
14221{
14222 LogFlowThisFunc(("\n"));
14223
14224 AutoCaller autoCaller(this);
14225 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14226
14227 ComPtr<IInternalSessionControl> directControl;
14228 {
14229 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14230 if (mData->mSession.mLockType == LockType_VM)
14231 directControl = mData->mSession.mDirectControl;
14232 }
14233
14234 /* ignore notifications sent after #OnSessionEnd() is called */
14235 if (!directControl)
14236 return S_OK;
14237
14238 return directControl->OnVRDEServerChange(aRestart);
14239}
14240
14241/**
14242 * @note Locks this object for reading.
14243 */
14244HRESULT SessionMachine::i_onVideoCaptureChange()
14245{
14246 LogFlowThisFunc(("\n"));
14247
14248 AutoCaller autoCaller(this);
14249 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14250
14251 ComPtr<IInternalSessionControl> directControl;
14252 {
14253 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14254 if (mData->mSession.mLockType == LockType_VM)
14255 directControl = mData->mSession.mDirectControl;
14256 }
14257
14258 /* ignore notifications sent after #OnSessionEnd() is called */
14259 if (!directControl)
14260 return S_OK;
14261
14262 return directControl->OnVideoCaptureChange();
14263}
14264
14265/**
14266 * @note Locks this object for reading.
14267 */
14268HRESULT SessionMachine::i_onUSBControllerChange()
14269{
14270 LogFlowThisFunc(("\n"));
14271
14272 AutoCaller autoCaller(this);
14273 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14274
14275 ComPtr<IInternalSessionControl> directControl;
14276 {
14277 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14278 if (mData->mSession.mLockType == LockType_VM)
14279 directControl = mData->mSession.mDirectControl;
14280 }
14281
14282 /* ignore notifications sent after #OnSessionEnd() is called */
14283 if (!directControl)
14284 return S_OK;
14285
14286 return directControl->OnUSBControllerChange();
14287}
14288
14289/**
14290 * @note Locks this object for reading.
14291 */
14292HRESULT SessionMachine::i_onSharedFolderChange()
14293{
14294 LogFlowThisFunc(("\n"));
14295
14296 AutoCaller autoCaller(this);
14297 AssertComRCReturnRC(autoCaller.rc());
14298
14299 ComPtr<IInternalSessionControl> directControl;
14300 {
14301 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14302 if (mData->mSession.mLockType == LockType_VM)
14303 directControl = mData->mSession.mDirectControl;
14304 }
14305
14306 /* ignore notifications sent after #OnSessionEnd() is called */
14307 if (!directControl)
14308 return S_OK;
14309
14310 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
14311}
14312
14313/**
14314 * @note Locks this object for reading.
14315 */
14316HRESULT SessionMachine::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
14317{
14318 LogFlowThisFunc(("\n"));
14319
14320 AutoCaller autoCaller(this);
14321 AssertComRCReturnRC(autoCaller.rc());
14322
14323 ComPtr<IInternalSessionControl> directControl;
14324 {
14325 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14326 if (mData->mSession.mLockType == LockType_VM)
14327 directControl = mData->mSession.mDirectControl;
14328 }
14329
14330 /* ignore notifications sent after #OnSessionEnd() is called */
14331 if (!directControl)
14332 return S_OK;
14333
14334 return directControl->OnClipboardModeChange(aClipboardMode);
14335}
14336
14337/**
14338 * @note Locks this object for reading.
14339 */
14340HRESULT SessionMachine::i_onDnDModeChange(DnDMode_T aDnDMode)
14341{
14342 LogFlowThisFunc(("\n"));
14343
14344 AutoCaller autoCaller(this);
14345 AssertComRCReturnRC(autoCaller.rc());
14346
14347 ComPtr<IInternalSessionControl> directControl;
14348 {
14349 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14350 if (mData->mSession.mLockType == LockType_VM)
14351 directControl = mData->mSession.mDirectControl;
14352 }
14353
14354 /* ignore notifications sent after #OnSessionEnd() is called */
14355 if (!directControl)
14356 return S_OK;
14357
14358 return directControl->OnDnDModeChange(aDnDMode);
14359}
14360
14361/**
14362 * @note Locks this object for reading.
14363 */
14364HRESULT SessionMachine::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
14365{
14366 LogFlowThisFunc(("\n"));
14367
14368 AutoCaller autoCaller(this);
14369 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14370
14371 ComPtr<IInternalSessionControl> directControl;
14372 {
14373 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14374 if (mData->mSession.mLockType == LockType_VM)
14375 directControl = mData->mSession.mDirectControl;
14376 }
14377
14378 /* ignore notifications sent after #OnSessionEnd() is called */
14379 if (!directControl)
14380 return S_OK;
14381
14382 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
14383}
14384
14385/**
14386 * @note Locks this object for reading.
14387 */
14388HRESULT SessionMachine::i_onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove, BOOL aSilent)
14389{
14390 LogFlowThisFunc(("\n"));
14391
14392 AutoCaller autoCaller(this);
14393 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14394
14395 ComPtr<IInternalSessionControl> directControl;
14396 {
14397 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14398 if (mData->mSession.mLockType == LockType_VM)
14399 directControl = mData->mSession.mDirectControl;
14400 }
14401
14402 /* ignore notifications sent after #OnSessionEnd() is called */
14403 if (!directControl)
14404 return S_OK;
14405
14406 return directControl->OnStorageDeviceChange(aAttachment, aRemove, aSilent);
14407}
14408
14409/**
14410 * Returns @c true if this machine's USB controller reports it has a matching
14411 * filter for the given USB device and @c false otherwise.
14412 *
14413 * @note locks this object for reading.
14414 */
14415bool SessionMachine::i_hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
14416{
14417 AutoCaller autoCaller(this);
14418 /* silently return if not ready -- this method may be called after the
14419 * direct machine session has been called */
14420 if (!autoCaller.isOk())
14421 return false;
14422
14423#ifdef VBOX_WITH_USB
14424 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14425
14426 switch (mData->mMachineState)
14427 {
14428 case MachineState_Starting:
14429 case MachineState_Restoring:
14430 case MachineState_TeleportingIn:
14431 case MachineState_Paused:
14432 case MachineState_Running:
14433 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
14434 * elsewhere... */
14435 alock.release();
14436 return mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedIfs);
14437 default: break;
14438 }
14439#else
14440 NOREF(aDevice);
14441 NOREF(aMaskedIfs);
14442#endif
14443 return false;
14444}
14445
14446/**
14447 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14448 */
14449HRESULT SessionMachine::i_onUSBDeviceAttach(IUSBDevice *aDevice,
14450 IVirtualBoxErrorInfo *aError,
14451 ULONG aMaskedIfs,
14452 const com::Utf8Str &aCaptureFilename)
14453{
14454 LogFlowThisFunc(("\n"));
14455
14456 AutoCaller autoCaller(this);
14457
14458 /* This notification may happen after the machine object has been
14459 * uninitialized (the session was closed), so don't assert. */
14460 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14461
14462 ComPtr<IInternalSessionControl> directControl;
14463 {
14464 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14465 if (mData->mSession.mLockType == LockType_VM)
14466 directControl = mData->mSession.mDirectControl;
14467 }
14468
14469 /* fail on notifications sent after #OnSessionEnd() is called, it is
14470 * expected by the caller */
14471 if (!directControl)
14472 return E_FAIL;
14473
14474 /* No locks should be held at this point. */
14475 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14476 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14477
14478 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs, Bstr(aCaptureFilename).raw());
14479}
14480
14481/**
14482 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14483 */
14484HRESULT SessionMachine::i_onUSBDeviceDetach(IN_BSTR aId,
14485 IVirtualBoxErrorInfo *aError)
14486{
14487 LogFlowThisFunc(("\n"));
14488
14489 AutoCaller autoCaller(this);
14490
14491 /* This notification may happen after the machine object has been
14492 * uninitialized (the session was closed), so don't assert. */
14493 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14494
14495 ComPtr<IInternalSessionControl> directControl;
14496 {
14497 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14498 if (mData->mSession.mLockType == LockType_VM)
14499 directControl = mData->mSession.mDirectControl;
14500 }
14501
14502 /* fail on notifications sent after #OnSessionEnd() is called, it is
14503 * expected by the caller */
14504 if (!directControl)
14505 return E_FAIL;
14506
14507 /* No locks should be held at this point. */
14508 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14509 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14510
14511 return directControl->OnUSBDeviceDetach(aId, aError);
14512}
14513
14514// protected methods
14515/////////////////////////////////////////////////////////////////////////////
14516
14517/**
14518 * Deletes the given file if it is no longer in use by either the current machine state
14519 * (if the machine is "saved") or any of the machine's snapshots.
14520 *
14521 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
14522 * but is different for each SnapshotMachine. When calling this, the order of calling this
14523 * function on the one hand and changing that variable OR the snapshots tree on the other hand
14524 * is therefore critical. I know, it's all rather messy.
14525 *
14526 * @param strStateFile
14527 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in
14528 * the test for whether the saved state file is in use.
14529 */
14530void SessionMachine::i_releaseSavedStateFile(const Utf8Str &strStateFile,
14531 Snapshot *pSnapshotToIgnore)
14532{
14533 // it is safe to delete this saved state file if it is not currently in use by the machine ...
14534 if ( (strStateFile.isNotEmpty())
14535 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
14536 )
14537 // ... and it must also not be shared with other snapshots
14538 if ( !mData->mFirstSnapshot
14539 || !mData->mFirstSnapshot->i_sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
14540 // this checks the SnapshotMachine's state file paths
14541 )
14542 RTFileDelete(strStateFile.c_str());
14543}
14544
14545/**
14546 * Locks the attached media.
14547 *
14548 * All attached hard disks are locked for writing and DVD/floppy are locked for
14549 * reading. Parents of attached hard disks (if any) are locked for reading.
14550 *
14551 * This method also performs accessibility check of all media it locks: if some
14552 * media is inaccessible, the method will return a failure and a bunch of
14553 * extended error info objects per each inaccessible medium.
14554 *
14555 * Note that this method is atomic: if it returns a success, all media are
14556 * locked as described above; on failure no media is locked at all (all
14557 * succeeded individual locks will be undone).
14558 *
14559 * The caller is responsible for doing the necessary state sanity checks.
14560 *
14561 * The locks made by this method must be undone by calling #unlockMedia() when
14562 * no more needed.
14563 */
14564HRESULT SessionMachine::i_lockMedia()
14565{
14566 AutoCaller autoCaller(this);
14567 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14568
14569 AutoMultiWriteLock2 alock(this->lockHandle(),
14570 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
14571
14572 /* bail out if trying to lock things with already set up locking */
14573 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
14574
14575 MultiResult mrc(S_OK);
14576
14577 /* Collect locking information for all medium objects attached to the VM. */
14578 for (MediumAttachmentList::const_iterator
14579 it = mMediumAttachments->begin();
14580 it != mMediumAttachments->end();
14581 ++it)
14582 {
14583 MediumAttachment *pAtt = *it;
14584 DeviceType_T devType = pAtt->i_getType();
14585 Medium *pMedium = pAtt->i_getMedium();
14586
14587 MediumLockList *pMediumLockList(new MediumLockList());
14588 // There can be attachments without a medium (floppy/dvd), and thus
14589 // it's impossible to create a medium lock list. It still makes sense
14590 // to have the empty medium lock list in the map in case a medium is
14591 // attached later.
14592 if (pMedium != NULL)
14593 {
14594 MediumType_T mediumType = pMedium->i_getType();
14595 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
14596 || mediumType == MediumType_Shareable;
14597 bool fIsVitalImage = (devType == DeviceType_HardDisk);
14598
14599 alock.release();
14600 mrc = pMedium->i_createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
14601 !fIsReadOnlyLock ? pMedium : NULL /* pToLockWrite */,
14602 false /* fMediumLockWriteAll */,
14603 NULL,
14604 *pMediumLockList);
14605 alock.acquire();
14606 if (FAILED(mrc))
14607 {
14608 delete pMediumLockList;
14609 mData->mSession.mLockedMedia.Clear();
14610 break;
14611 }
14612 }
14613
14614 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
14615 if (FAILED(rc))
14616 {
14617 mData->mSession.mLockedMedia.Clear();
14618 mrc = setError(rc,
14619 tr("Collecting locking information for all attached media failed"));
14620 break;
14621 }
14622 }
14623
14624 if (SUCCEEDED(mrc))
14625 {
14626 /* Now lock all media. If this fails, nothing is locked. */
14627 alock.release();
14628 HRESULT rc = mData->mSession.mLockedMedia.Lock();
14629 alock.acquire();
14630 if (FAILED(rc))
14631 {
14632 mrc = setError(rc,
14633 tr("Locking of attached media failed. A possible reason is that one of the media is attached to a running VM"));
14634 }
14635 }
14636
14637 return mrc;
14638}
14639
14640/**
14641 * Undoes the locks made by by #lockMedia().
14642 */
14643HRESULT SessionMachine::i_unlockMedia()
14644{
14645 AutoCaller autoCaller(this);
14646 AssertComRCReturn(autoCaller.rc(),autoCaller.rc());
14647
14648 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14649
14650 /* we may be holding important error info on the current thread;
14651 * preserve it */
14652 ErrorInfoKeeper eik;
14653
14654 HRESULT rc = mData->mSession.mLockedMedia.Clear();
14655 AssertComRC(rc);
14656 return rc;
14657}
14658
14659/**
14660 * Helper to change the machine state (reimplementation).
14661 *
14662 * @note Locks this object for writing.
14663 * @note This method must not call i_saveSettings or SaveSettings, otherwise
14664 * it can cause crashes in random places due to unexpectedly committing
14665 * the current settings. The caller is responsible for that. The call
14666 * to saveStateSettings is fine, because this method does not commit.
14667 */
14668HRESULT SessionMachine::i_setMachineState(MachineState_T aMachineState)
14669{
14670 LogFlowThisFuncEnter();
14671 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
14672
14673 AutoCaller autoCaller(this);
14674 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14675
14676 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14677
14678 MachineState_T oldMachineState = mData->mMachineState;
14679
14680 AssertMsgReturn(oldMachineState != aMachineState,
14681 ("oldMachineState=%s, aMachineState=%s\n",
14682 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
14683 E_FAIL);
14684
14685 HRESULT rc = S_OK;
14686
14687 int stsFlags = 0;
14688 bool deleteSavedState = false;
14689
14690 /* detect some state transitions */
14691
14692 if ( ( oldMachineState == MachineState_Saved
14693 && aMachineState == MachineState_Restoring)
14694 || ( ( oldMachineState == MachineState_PoweredOff
14695 || oldMachineState == MachineState_Teleported
14696 || oldMachineState == MachineState_Aborted
14697 )
14698 && ( aMachineState == MachineState_TeleportingIn
14699 || aMachineState == MachineState_Starting
14700 )
14701 )
14702 )
14703 {
14704 /* The EMT thread is about to start */
14705
14706 /* Nothing to do here for now... */
14707
14708 /// @todo NEWMEDIA don't let mDVDDrive and other children
14709 /// change anything when in the Starting/Restoring state
14710 }
14711 else if ( ( oldMachineState == MachineState_Running
14712 || oldMachineState == MachineState_Paused
14713 || oldMachineState == MachineState_Teleporting
14714 || oldMachineState == MachineState_OnlineSnapshotting
14715 || oldMachineState == MachineState_LiveSnapshotting
14716 || oldMachineState == MachineState_Stuck
14717 || oldMachineState == MachineState_Starting
14718 || oldMachineState == MachineState_Stopping
14719 || oldMachineState == MachineState_Saving
14720 || oldMachineState == MachineState_Restoring
14721 || oldMachineState == MachineState_TeleportingPausedVM
14722 || oldMachineState == MachineState_TeleportingIn
14723 )
14724 && ( aMachineState == MachineState_PoweredOff
14725 || aMachineState == MachineState_Saved
14726 || aMachineState == MachineState_Teleported
14727 || aMachineState == MachineState_Aborted
14728 )
14729 )
14730 {
14731 /* The EMT thread has just stopped, unlock attached media. Note that as
14732 * opposed to locking that is done from Console, we do unlocking here
14733 * because the VM process may have aborted before having a chance to
14734 * properly unlock all media it locked. */
14735
14736 unlockMedia();
14737 }
14738
14739 if (oldMachineState == MachineState_Restoring)
14740 {
14741 if (aMachineState != MachineState_Saved)
14742 {
14743 /*
14744 * delete the saved state file once the machine has finished
14745 * restoring from it (note that Console sets the state from
14746 * Restoring to Saved if the VM couldn't restore successfully,
14747 * to give the user an ability to fix an error and retry --
14748 * we keep the saved state file in this case)
14749 */
14750 deleteSavedState = true;
14751 }
14752 }
14753 else if ( oldMachineState == MachineState_Saved
14754 && ( aMachineState == MachineState_PoweredOff
14755 || aMachineState == MachineState_Aborted
14756 || aMachineState == MachineState_Teleported
14757 )
14758 )
14759 {
14760 /*
14761 * delete the saved state after SessionMachine::ForgetSavedState() is called
14762 * or if the VM process (owning a direct VM session) crashed while the
14763 * VM was Saved
14764 */
14765
14766 /// @todo (dmik)
14767 // Not sure that deleting the saved state file just because of the
14768 // client death before it attempted to restore the VM is a good
14769 // thing. But when it crashes we need to go to the Aborted state
14770 // which cannot have the saved state file associated... The only
14771 // way to fix this is to make the Aborted condition not a VM state
14772 // but a bool flag: i.e., when a crash occurs, set it to true and
14773 // change the state to PoweredOff or Saved depending on the
14774 // saved state presence.
14775
14776 deleteSavedState = true;
14777 mData->mCurrentStateModified = TRUE;
14778 stsFlags |= SaveSTS_CurStateModified;
14779 }
14780
14781 if ( aMachineState == MachineState_Starting
14782 || aMachineState == MachineState_Restoring
14783 || aMachineState == MachineState_TeleportingIn
14784 )
14785 {
14786 /* set the current state modified flag to indicate that the current
14787 * state is no more identical to the state in the
14788 * current snapshot */
14789 if (!mData->mCurrentSnapshot.isNull())
14790 {
14791 mData->mCurrentStateModified = TRUE;
14792 stsFlags |= SaveSTS_CurStateModified;
14793 }
14794 }
14795
14796 if (deleteSavedState)
14797 {
14798 if (mRemoveSavedState)
14799 {
14800 Assert(!mSSData->strStateFilePath.isEmpty());
14801
14802 // it is safe to delete the saved state file if ...
14803 if ( !mData->mFirstSnapshot // ... we have no snapshots or
14804 || !mData->mFirstSnapshot->i_sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
14805 // ... none of the snapshots share the saved state file
14806 )
14807 RTFileDelete(mSSData->strStateFilePath.c_str());
14808 }
14809
14810 mSSData->strStateFilePath.setNull();
14811 stsFlags |= SaveSTS_StateFilePath;
14812 }
14813
14814 /* redirect to the underlying peer machine */
14815 mPeer->i_setMachineState(aMachineState);
14816
14817 if ( oldMachineState != MachineState_RestoringSnapshot
14818 && ( aMachineState == MachineState_PoweredOff
14819 || aMachineState == MachineState_Teleported
14820 || aMachineState == MachineState_Aborted
14821 || aMachineState == MachineState_Saved))
14822 {
14823 /* the machine has stopped execution
14824 * (or the saved state file was adopted) */
14825 stsFlags |= SaveSTS_StateTimeStamp;
14826 }
14827
14828 if ( ( oldMachineState == MachineState_PoweredOff
14829 || oldMachineState == MachineState_Aborted
14830 || oldMachineState == MachineState_Teleported
14831 )
14832 && aMachineState == MachineState_Saved)
14833 {
14834 /* the saved state file was adopted */
14835 Assert(!mSSData->strStateFilePath.isEmpty());
14836 stsFlags |= SaveSTS_StateFilePath;
14837 }
14838
14839#ifdef VBOX_WITH_GUEST_PROPS
14840 if ( aMachineState == MachineState_PoweredOff
14841 || aMachineState == MachineState_Aborted
14842 || aMachineState == MachineState_Teleported)
14843 {
14844 /* Make sure any transient guest properties get removed from the
14845 * property store on shutdown. */
14846 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
14847
14848 /* remove it from the settings representation */
14849 settings::GuestPropertiesList &llGuestProperties = mData->pMachineConfigFile->hardwareMachine.llGuestProperties;
14850 for (settings::GuestPropertiesList::iterator
14851 it = llGuestProperties.begin();
14852 it != llGuestProperties.end();
14853 /*nothing*/)
14854 {
14855 const settings::GuestProperty &prop = *it;
14856 if ( prop.strFlags.contains("TRANSRESET", Utf8Str::CaseInsensitive)
14857 || prop.strFlags.contains("TRANSIENT", Utf8Str::CaseInsensitive))
14858 {
14859 it = llGuestProperties.erase(it);
14860 fNeedsSaving = true;
14861 }
14862 else
14863 {
14864 ++it;
14865 }
14866 }
14867
14868 /* Additionally remove it from the HWData representation. Required to
14869 * keep everything in sync, as this is what the API keeps using. */
14870 HWData::GuestPropertyMap &llHWGuestProperties = mHWData->mGuestProperties;
14871 for (HWData::GuestPropertyMap::iterator
14872 it = llHWGuestProperties.begin();
14873 it != llHWGuestProperties.end();
14874 /*nothing*/)
14875 {
14876 uint32_t fFlags = it->second.mFlags;
14877 if ( fFlags & guestProp::TRANSIENT
14878 || fFlags & guestProp::TRANSRESET)
14879 {
14880 /* iterator where we need to continue after the erase call
14881 * (C++03 is a fact still, and it doesn't return the iterator
14882 * which would allow continuing) */
14883 HWData::GuestPropertyMap::iterator it2 = it;
14884 ++it2;
14885 llHWGuestProperties.erase(it);
14886 it = it2;
14887 fNeedsSaving = true;
14888 }
14889 else
14890 {
14891 ++it;
14892 }
14893 }
14894
14895 if (fNeedsSaving)
14896 {
14897 mData->mCurrentStateModified = TRUE;
14898 stsFlags |= SaveSTS_CurStateModified;
14899 }
14900 }
14901#endif /* VBOX_WITH_GUEST_PROPS */
14902
14903 rc = i_saveStateSettings(stsFlags);
14904
14905 if ( ( oldMachineState != MachineState_PoweredOff
14906 && oldMachineState != MachineState_Aborted
14907 && oldMachineState != MachineState_Teleported
14908 )
14909 && ( aMachineState == MachineState_PoweredOff
14910 || aMachineState == MachineState_Aborted
14911 || aMachineState == MachineState_Teleported
14912 )
14913 )
14914 {
14915 /* we've been shut down for any reason */
14916 /* no special action so far */
14917 }
14918
14919 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
14920 LogFlowThisFuncLeave();
14921 return rc;
14922}
14923
14924/**
14925 * Sends the current machine state value to the VM process.
14926 *
14927 * @note Locks this object for reading, then calls a client process.
14928 */
14929HRESULT SessionMachine::i_updateMachineStateOnClient()
14930{
14931 AutoCaller autoCaller(this);
14932 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14933
14934 ComPtr<IInternalSessionControl> directControl;
14935 {
14936 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14937 AssertReturn(!!mData, E_FAIL);
14938 if (mData->mSession.mLockType == LockType_VM)
14939 directControl = mData->mSession.mDirectControl;
14940
14941 /* directControl may be already set to NULL here in #OnSessionEnd()
14942 * called too early by the direct session process while there is still
14943 * some operation (like deleting the snapshot) in progress. The client
14944 * process in this case is waiting inside Session::close() for the
14945 * "end session" process object to complete, while #uninit() called by
14946 * #i_checkForDeath() on the Watcher thread is waiting for the pending
14947 * operation to complete. For now, we accept this inconsistent behavior
14948 * and simply do nothing here. */
14949
14950 if (mData->mSession.mState == SessionState_Unlocking)
14951 return S_OK;
14952 }
14953
14954 /* ignore notifications sent after #OnSessionEnd() is called */
14955 if (!directControl)
14956 return S_OK;
14957
14958 return directControl->UpdateMachineState(mData->mMachineState);
14959}
14960
14961
14962/*static*/
14963HRESULT Machine::i_setErrorStatic(HRESULT aResultCode, const char *pcszMsg, ...)
14964{
14965 va_list args;
14966 va_start(args, pcszMsg);
14967 HRESULT rc = setErrorInternal(aResultCode,
14968 getStaticClassIID(),
14969 getStaticComponentName(),
14970 Utf8Str(pcszMsg, args),
14971 false /* aWarning */,
14972 true /* aLogIt */);
14973 va_end(args);
14974 return rc;
14975}
14976
14977
14978HRESULT Machine::updateState(MachineState_T aState)
14979{
14980 NOREF(aState);
14981 ReturnComNotImplemented();
14982}
14983
14984HRESULT Machine::beginPowerUp(const ComPtr<IProgress> &aProgress)
14985{
14986 NOREF(aProgress);
14987 ReturnComNotImplemented();
14988}
14989
14990HRESULT Machine::endPowerUp(LONG aResult)
14991{
14992 NOREF(aResult);
14993 ReturnComNotImplemented();
14994}
14995
14996HRESULT Machine::beginPoweringDown(ComPtr<IProgress> &aProgress)
14997{
14998 NOREF(aProgress);
14999 ReturnComNotImplemented();
15000}
15001
15002HRESULT Machine::endPoweringDown(LONG aResult,
15003 const com::Utf8Str &aErrMsg)
15004{
15005 NOREF(aResult);
15006 NOREF(aErrMsg);
15007 ReturnComNotImplemented();
15008}
15009
15010HRESULT Machine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
15011 BOOL *aMatched,
15012 ULONG *aMaskedInterfaces)
15013{
15014 NOREF(aDevice);
15015 NOREF(aMatched);
15016 NOREF(aMaskedInterfaces);
15017 ReturnComNotImplemented();
15018
15019}
15020
15021HRESULT Machine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
15022{
15023 NOREF(aId); NOREF(aCaptureFilename);
15024 ReturnComNotImplemented();
15025}
15026
15027HRESULT Machine::detachUSBDevice(const com::Guid &aId,
15028 BOOL aDone)
15029{
15030 NOREF(aId);
15031 NOREF(aDone);
15032 ReturnComNotImplemented();
15033}
15034
15035HRESULT Machine::autoCaptureUSBDevices()
15036{
15037 ReturnComNotImplemented();
15038}
15039
15040HRESULT Machine::detachAllUSBDevices(BOOL aDone)
15041{
15042 NOREF(aDone);
15043 ReturnComNotImplemented();
15044}
15045
15046HRESULT Machine::onSessionEnd(const ComPtr<ISession> &aSession,
15047 ComPtr<IProgress> &aProgress)
15048{
15049 NOREF(aSession);
15050 NOREF(aProgress);
15051 ReturnComNotImplemented();
15052}
15053
15054HRESULT Machine::finishOnlineMergeMedium()
15055{
15056 ReturnComNotImplemented();
15057}
15058
15059HRESULT Machine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
15060 std::vector<com::Utf8Str> &aValues,
15061 std::vector<LONG64> &aTimestamps,
15062 std::vector<com::Utf8Str> &aFlags)
15063{
15064 NOREF(aNames);
15065 NOREF(aValues);
15066 NOREF(aTimestamps);
15067 NOREF(aFlags);
15068 ReturnComNotImplemented();
15069}
15070
15071HRESULT Machine::pushGuestProperty(const com::Utf8Str &aName,
15072 const com::Utf8Str &aValue,
15073 LONG64 aTimestamp,
15074 const com::Utf8Str &aFlags)
15075{
15076 NOREF(aName);
15077 NOREF(aValue);
15078 NOREF(aTimestamp);
15079 NOREF(aFlags);
15080 ReturnComNotImplemented();
15081}
15082
15083HRESULT Machine::lockMedia()
15084{
15085 ReturnComNotImplemented();
15086}
15087
15088HRESULT Machine::unlockMedia()
15089{
15090 ReturnComNotImplemented();
15091}
15092
15093HRESULT Machine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
15094 ComPtr<IMediumAttachment> &aNewAttachment)
15095{
15096 NOREF(aAttachment);
15097 NOREF(aNewAttachment);
15098 ReturnComNotImplemented();
15099}
15100
15101HRESULT Machine::reportVmStatistics(ULONG aValidStats,
15102 ULONG aCpuUser,
15103 ULONG aCpuKernel,
15104 ULONG aCpuIdle,
15105 ULONG aMemTotal,
15106 ULONG aMemFree,
15107 ULONG aMemBalloon,
15108 ULONG aMemShared,
15109 ULONG aMemCache,
15110 ULONG aPagedTotal,
15111 ULONG aMemAllocTotal,
15112 ULONG aMemFreeTotal,
15113 ULONG aMemBalloonTotal,
15114 ULONG aMemSharedTotal,
15115 ULONG aVmNetRx,
15116 ULONG aVmNetTx)
15117{
15118 NOREF(aValidStats);
15119 NOREF(aCpuUser);
15120 NOREF(aCpuKernel);
15121 NOREF(aCpuIdle);
15122 NOREF(aMemTotal);
15123 NOREF(aMemFree);
15124 NOREF(aMemBalloon);
15125 NOREF(aMemShared);
15126 NOREF(aMemCache);
15127 NOREF(aPagedTotal);
15128 NOREF(aMemAllocTotal);
15129 NOREF(aMemFreeTotal);
15130 NOREF(aMemBalloonTotal);
15131 NOREF(aMemSharedTotal);
15132 NOREF(aVmNetRx);
15133 NOREF(aVmNetTx);
15134 ReturnComNotImplemented();
15135}
15136
15137HRESULT Machine::authenticateExternal(const std::vector<com::Utf8Str> &aAuthParams,
15138 com::Utf8Str &aResult)
15139{
15140 NOREF(aAuthParams);
15141 NOREF(aResult);
15142 ReturnComNotImplemented();
15143}
15144
15145HRESULT Machine::applyDefaults(const com::Utf8Str &aFlags)
15146{
15147 NOREF(aFlags);
15148 ReturnComNotImplemented();
15149}
15150
15151/* This isn't handled entirely by the wrapper generator yet. */
15152#ifdef VBOX_WITH_XPCOM
15153NS_DECL_CLASSINFO(SessionMachine)
15154NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
15155
15156NS_DECL_CLASSINFO(SnapshotMachine)
15157NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
15158#endif
Note: See TracBrowser for help on using the repository browser.

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