VirtualBox

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

Last change on this file since 57832 was 57832, checked in by vboxsync, 10 years ago

Main,GUI: positioned the VBoxStartup.log as the 2nd log that can be retrieved via IMachine::queryLogFilename on windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 509.9 KB
Line 
1/* $Id: MachineImpl.cpp 57832 2015-09-18 19:27:02Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2004-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/* Make sure all the stdint.h macros are included - must come first! */
19#ifndef __STDC_LIMIT_MACROS
20# define __STDC_LIMIT_MACROS
21#endif
22#ifndef __STDC_CONSTANT_MACROS
23# define __STDC_CONSTANT_MACROS
24#endif
25
26#include "Logging.h"
27#include "VirtualBoxImpl.h"
28#include "MachineImpl.h"
29#include "ClientToken.h"
30#include "ProgressImpl.h"
31#include "ProgressProxyImpl.h"
32#include "MediumAttachmentImpl.h"
33#include "MediumImpl.h"
34#include "MediumLock.h"
35#include "USBControllerImpl.h"
36#include "USBDeviceFiltersImpl.h"
37#include "HostImpl.h"
38#include "SharedFolderImpl.h"
39#include "GuestOSTypeImpl.h"
40#include "VirtualBoxErrorInfoImpl.h"
41#include "StorageControllerImpl.h"
42#include "DisplayImpl.h"
43#include "DisplayUtils.h"
44#include "MachineImplCloneVM.h"
45#include "AutostartDb.h"
46#include "SystemPropertiesImpl.h"
47
48// generated header
49#include "VBoxEvents.h"
50
51#ifdef VBOX_WITH_USB
52# include "USBProxyService.h"
53#endif
54
55#include "AutoCaller.h"
56#include "HashedPw.h"
57#include "Performance.h"
58
59#include <iprt/asm.h>
60#include <iprt/path.h>
61#include <iprt/dir.h>
62#include <iprt/env.h>
63#include <iprt/lockvalidator.h>
64#include <iprt/process.h>
65#include <iprt/cpp/utils.h>
66#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
67#include <iprt/sha.h>
68#include <iprt/string.h>
69#include <iprt/base64.h>
70
71#include <VBox/com/array.h>
72#include <VBox/com/list.h>
73
74#include <VBox/err.h>
75#include <VBox/param.h>
76#include <VBox/settings.h>
77#include <VBox/vmm/ssm.h>
78
79#ifdef VBOX_WITH_GUEST_PROPS
80# include <VBox/HostServices/GuestPropertySvc.h>
81# include <VBox/com/array.h>
82#endif
83
84#include "VBox/com/MultiResult.h"
85
86#include <algorithm>
87
88#ifdef VBOX_WITH_DTRACE_R3_MAIN
89# include "dtrace/VBoxAPI.h"
90#endif
91
92#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
93# define HOSTSUFF_EXE ".exe"
94#else /* !RT_OS_WINDOWS */
95# define HOSTSUFF_EXE ""
96#endif /* !RT_OS_WINDOWS */
97
98// defines / prototypes
99/////////////////////////////////////////////////////////////////////////////
100
101/////////////////////////////////////////////////////////////////////////////
102// Machine::Data structure
103/////////////////////////////////////////////////////////////////////////////
104
105Machine::Data::Data()
106{
107 mRegistered = FALSE;
108 pMachineConfigFile = NULL;
109 /* Contains hints on what has changed when the user is using the VM (config
110 * changes, running the VM, ...). This is used to decide if a config needs
111 * to be written to disk. */
112 flModifications = 0;
113 /* VM modification usually also trigger setting the current state to
114 * "Modified". Although this is not always the case. An e.g. is the VM
115 * initialization phase or when snapshot related data is changed. The
116 * actually behavior is controlled by the following flag. */
117 m_fAllowStateModification = false;
118 mAccessible = FALSE;
119 /* mUuid is initialized in Machine::init() */
120
121 mMachineState = MachineState_PoweredOff;
122 RTTimeNow(&mLastStateChange);
123
124 mMachineStateDeps = 0;
125 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
126 mMachineStateChangePending = 0;
127
128 mCurrentStateModified = TRUE;
129 mGuestPropertiesModified = FALSE;
130
131 mSession.mPID = NIL_RTPROCESS;
132 mSession.mLockType = LockType_Null;
133 mSession.mState = SessionState_Unlocked;
134}
135
136Machine::Data::~Data()
137{
138 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
139 {
140 RTSemEventMultiDestroy(mMachineStateDepsSem);
141 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
142 }
143 if (pMachineConfigFile)
144 {
145 delete pMachineConfigFile;
146 pMachineConfigFile = NULL;
147 }
148}
149
150/////////////////////////////////////////////////////////////////////////////
151// Machine::HWData structure
152/////////////////////////////////////////////////////////////////////////////
153
154Machine::HWData::HWData()
155{
156 /* default values for a newly created machine */
157 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
158 mMemorySize = 128;
159 mCPUCount = 1;
160 mCPUHotPlugEnabled = false;
161 mMemoryBalloonSize = 0;
162 mPageFusionEnabled = false;
163 mGraphicsControllerType = GraphicsControllerType_VBoxVGA;
164 mVRAMSize = 8;
165 mAccelerate3DEnabled = false;
166 mAccelerate2DVideoEnabled = false;
167 mMonitorCount = 1;
168 mVideoCaptureWidth = 1024;
169 mVideoCaptureHeight = 768;
170 mVideoCaptureRate = 512;
171 mVideoCaptureFPS = 25;
172 mVideoCaptureMaxTime = 0;
173 mVideoCaptureMaxFileSize = 0;
174 mVideoCaptureEnabled = false;
175 for (unsigned i = 0; i < RT_ELEMENTS(maVideoCaptureScreens); ++i)
176 maVideoCaptureScreens[i] = true;
177
178 mHWVirtExEnabled = true;
179 mHWVirtExNestedPagingEnabled = true;
180#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
181 mHWVirtExLargePagesEnabled = true;
182#else
183 /* Not supported on 32 bits hosts. */
184 mHWVirtExLargePagesEnabled = false;
185#endif
186 mHWVirtExVPIDEnabled = true;
187 mHWVirtExUXEnabled = true;
188 mHWVirtExForceEnabled = false;
189#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
190 mPAEEnabled = true;
191#else
192 mPAEEnabled = false;
193#endif
194 mLongMode = HC_ARCH_BITS == 64 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
195 mTripleFaultReset = false;
196 mHPETEnabled = false;
197 mCpuExecutionCap = 100; /* Maximum CPU execution cap by default. */
198 mCpuIdPortabilityLevel = 0;
199
200 /* default boot order: floppy - DVD - HDD */
201 mBootOrder[0] = DeviceType_Floppy;
202 mBootOrder[1] = DeviceType_DVD;
203 mBootOrder[2] = DeviceType_HardDisk;
204 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
205 mBootOrder[i] = DeviceType_Null;
206
207 mClipboardMode = ClipboardMode_Disabled;
208 mDnDMode = DnDMode_Disabled;
209
210 mFirmwareType = FirmwareType_BIOS;
211 mKeyboardHIDType = KeyboardHIDType_PS2Keyboard;
212 mPointingHIDType = PointingHIDType_PS2Mouse;
213 mChipsetType = ChipsetType_PIIX3;
214 mParavirtProvider = ParavirtProvider_Default;
215 mEmulatedUSBCardReaderEnabled = FALSE;
216
217 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); ++i)
218 mCPUAttached[i] = false;
219
220 mIOCacheEnabled = true;
221 mIOCacheSize = 5; /* 5MB */
222}
223
224Machine::HWData::~HWData()
225{
226}
227
228/////////////////////////////////////////////////////////////////////////////
229// Machine::HDData structure
230/////////////////////////////////////////////////////////////////////////////
231
232Machine::MediaData::MediaData()
233{
234}
235
236Machine::MediaData::~MediaData()
237{
238}
239
240/////////////////////////////////////////////////////////////////////////////
241// Machine class
242/////////////////////////////////////////////////////////////////////////////
243
244// constructor / destructor
245/////////////////////////////////////////////////////////////////////////////
246
247Machine::Machine() :
248#ifdef VBOX_WITH_RESOURCE_USAGE_API
249 mCollectorGuest(NULL),
250#endif
251 mPeer(NULL),
252 mParent(NULL),
253 mSerialPorts(),
254 mParallelPorts(),
255 uRegistryNeedsSaving(0)
256{}
257
258Machine::~Machine()
259{}
260
261HRESULT Machine::FinalConstruct()
262{
263 LogFlowThisFunc(("\n"));
264 return BaseFinalConstruct();
265}
266
267void Machine::FinalRelease()
268{
269 LogFlowThisFunc(("\n"));
270 uninit();
271 BaseFinalRelease();
272}
273
274/**
275 * Initializes a new machine instance; this init() variant creates a new, empty machine.
276 * This gets called from VirtualBox::CreateMachine().
277 *
278 * @param aParent Associated parent object
279 * @param strConfigFile Local file system path to the VM settings file (can
280 * be relative to the VirtualBox config directory).
281 * @param strName name for the machine
282 * @param llGroups list of groups for the machine
283 * @param aOsType OS Type of this machine or NULL.
284 * @param aId UUID for the new machine.
285 * @param fForceOverwrite Whether to overwrite an existing machine settings file.
286 *
287 * @return Success indicator. if not S_OK, the machine object is invalid
288 */
289HRESULT Machine::init(VirtualBox *aParent,
290 const Utf8Str &strConfigFile,
291 const Utf8Str &strName,
292 const StringsList &llGroups,
293 GuestOSType *aOsType,
294 const Guid &aId,
295 bool fForceOverwrite,
296 bool fDirectoryIncludesUUID)
297{
298 LogFlowThisFuncEnter();
299 LogFlowThisFunc(("(Init_New) aConfigFile='%s'\n", strConfigFile.c_str()));
300
301 /* Enclose the state transition NotReady->InInit->Ready */
302 AutoInitSpan autoInitSpan(this);
303 AssertReturn(autoInitSpan.isOk(), E_FAIL);
304
305 HRESULT rc = initImpl(aParent, strConfigFile);
306 if (FAILED(rc)) return rc;
307
308 rc = i_tryCreateMachineConfigFile(fForceOverwrite);
309 if (FAILED(rc)) return rc;
310
311 if (SUCCEEDED(rc))
312 {
313 // create an empty machine config
314 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
315
316 rc = initDataAndChildObjects();
317 }
318
319 if (SUCCEEDED(rc))
320 {
321 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
322 mData->mAccessible = TRUE;
323
324 unconst(mData->mUuid) = aId;
325
326 mUserData->s.strName = strName;
327
328 mUserData->s.llGroups = llGroups;
329
330 mUserData->s.fDirectoryIncludesUUID = fDirectoryIncludesUUID;
331 // the "name sync" flag determines whether the machine directory gets renamed along
332 // with the machine file; say so if the settings file name is the same as the
333 // settings file parent directory (machine directory)
334 mUserData->s.fNameSync = i_isInOwnDir();
335
336 // initialize the default snapshots folder
337 rc = COMSETTER(SnapshotFolder)(NULL);
338 AssertComRC(rc);
339
340 if (aOsType)
341 {
342 /* Store OS type */
343 mUserData->s.strOsType = aOsType->i_id();
344
345 /* Apply BIOS defaults */
346 mBIOSSettings->i_applyDefaults(aOsType);
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 /* Let the OS type select 64-bit ness. */
357 mHWData->mLongMode = aOsType->i_is64Bit()
358 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
359 }
360
361 /* At this point the changing of the current state modification
362 * flag is allowed. */
363 i_allowStateModification();
364
365 /* commit all changes made during the initialization */
366 i_commit();
367 }
368
369 /* Confirm a successful initialization when it's the case */
370 if (SUCCEEDED(rc))
371 {
372 if (mData->mAccessible)
373 autoInitSpan.setSucceeded();
374 else
375 autoInitSpan.setLimited();
376 }
377
378 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool, rc=%08X\n",
379 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
380 mData->mRegistered,
381 mData->mAccessible,
382 rc));
383
384 LogFlowThisFuncLeave();
385
386 return rc;
387}
388
389/**
390 * Initializes a new instance with data from machine XML (formerly Init_Registered).
391 * Gets called in two modes:
392 *
393 * -- from VirtualBox::initMachines() during VirtualBox startup; in that case, the
394 * UUID is specified and we mark the machine as "registered";
395 *
396 * -- from the public VirtualBox::OpenMachine() API, in which case the UUID is NULL
397 * and the machine remains unregistered until RegisterMachine() is called.
398 *
399 * @param aParent Associated parent object
400 * @param aConfigFile Local file system path to the VM settings file (can
401 * be relative to the VirtualBox config directory).
402 * @param aId UUID of the machine or NULL (see above).
403 *
404 * @return Success indicator. if not S_OK, the machine object is invalid
405 */
406HRESULT Machine::initFromSettings(VirtualBox *aParent,
407 const Utf8Str &strConfigFile,
408 const Guid *aId)
409{
410 LogFlowThisFuncEnter();
411 LogFlowThisFunc(("(Init_Registered) aConfigFile='%s\n", strConfigFile.c_str()));
412
413 /* Enclose the state transition NotReady->InInit->Ready */
414 AutoInitSpan autoInitSpan(this);
415 AssertReturn(autoInitSpan.isOk(), E_FAIL);
416
417 HRESULT rc = initImpl(aParent, strConfigFile);
418 if (FAILED(rc)) return rc;
419
420 if (aId)
421 {
422 // loading a registered VM:
423 unconst(mData->mUuid) = *aId;
424 mData->mRegistered = TRUE;
425 // now load the settings from XML:
426 rc = i_registeredInit();
427 // this calls initDataAndChildObjects() and loadSettings()
428 }
429 else
430 {
431 // opening an unregistered VM (VirtualBox::OpenMachine()):
432 rc = initDataAndChildObjects();
433
434 if (SUCCEEDED(rc))
435 {
436 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
437 mData->mAccessible = TRUE;
438
439 try
440 {
441 // load and parse machine XML; this will throw on XML or logic errors
442 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
443
444 // reject VM UUID duplicates, they can happen if someone
445 // tries to register an already known VM config again
446 if (aParent->i_findMachine(mData->pMachineConfigFile->uuid,
447 true /* fPermitInaccessible */,
448 false /* aDoSetError */,
449 NULL) != VBOX_E_OBJECT_NOT_FOUND)
450 {
451 throw setError(E_FAIL,
452 tr("Trying to open a VM config '%s' which has the same UUID as an existing virtual machine"),
453 mData->m_strConfigFile.c_str());
454 }
455
456 // use UUID from machine config
457 unconst(mData->mUuid) = mData->pMachineConfigFile->uuid;
458
459 rc = i_loadMachineDataFromSettings(*mData->pMachineConfigFile,
460 NULL /* puuidRegistry */);
461 if (FAILED(rc)) throw rc;
462
463 /* At this point the changing of the current state modification
464 * flag is allowed. */
465 i_allowStateModification();
466
467 i_commit();
468 }
469 catch (HRESULT err)
470 {
471 /* we assume that error info is set by the thrower */
472 rc = err;
473 }
474 catch (...)
475 {
476 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
477 }
478 }
479 }
480
481 /* Confirm a successful initialization when it's the case */
482 if (SUCCEEDED(rc))
483 {
484 if (mData->mAccessible)
485 autoInitSpan.setSucceeded();
486 else
487 {
488 autoInitSpan.setLimited();
489
490 // uninit media from this machine's media registry, or else
491 // reloading the settings will fail
492 mParent->i_unregisterMachineMedia(i_getId());
493 }
494 }
495
496 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
497 "rc=%08X\n",
498 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
499 mData->mRegistered, mData->mAccessible, rc));
500
501 LogFlowThisFuncLeave();
502
503 return rc;
504}
505
506/**
507 * Initializes a new instance from a machine config that is already in memory
508 * (import OVF case). Since we are importing, the UUID in the machine
509 * config is ignored and we always generate a fresh one.
510 *
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
604 * @return
605 */
606HRESULT Machine::initImpl(VirtualBox *aParent,
607 const Utf8Str &strConfigFile)
608{
609 LogFlowThisFuncEnter();
610
611 AssertReturn(aParent, E_INVALIDARG);
612 AssertReturn(!strConfigFile.isEmpty(), E_INVALIDARG);
613
614 HRESULT rc = S_OK;
615
616 /* share the parent weakly */
617 unconst(mParent) = aParent;
618
619 /* allocate the essential machine data structure (the rest will be
620 * allocated later by initDataAndChildObjects() */
621 mData.allocate();
622
623 /* memorize the config file name (as provided) */
624 mData->m_strConfigFile = strConfigFile;
625
626 /* get the full file name */
627 int vrc1 = mParent->i_calculateFullPath(strConfigFile, mData->m_strConfigFileFull);
628 if (RT_FAILURE(vrc1))
629 return setError(VBOX_E_FILE_ERROR,
630 tr("Invalid machine settings file name '%s' (%Rrc)"),
631 strConfigFile.c_str(),
632 vrc1);
633
634 LogFlowThisFuncLeave();
635
636 return rc;
637}
638
639/**
640 * Tries to create a machine settings file in the path stored in the machine
641 * instance data. Used when a new machine is created to fail gracefully if
642 * the settings file could not be written (e.g. because machine dir is read-only).
643 * @return
644 */
645HRESULT Machine::i_tryCreateMachineConfigFile(bool fForceOverwrite)
646{
647 HRESULT rc = S_OK;
648
649 // when we create a new machine, we must be able to create the settings file
650 RTFILE f = NIL_RTFILE;
651 int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
652 if ( RT_SUCCESS(vrc)
653 || vrc == VERR_SHARING_VIOLATION
654 )
655 {
656 if (RT_SUCCESS(vrc))
657 RTFileClose(f);
658 if (!fForceOverwrite)
659 rc = setError(VBOX_E_FILE_ERROR,
660 tr("Machine settings file '%s' already exists"),
661 mData->m_strConfigFileFull.c_str());
662 else
663 {
664 /* try to delete the config file, as otherwise the creation
665 * of a new settings file will fail. */
666 int vrc2 = RTFileDelete(mData->m_strConfigFileFull.c_str());
667 if (RT_FAILURE(vrc2))
668 rc = setError(VBOX_E_FILE_ERROR,
669 tr("Could not delete the existing settings file '%s' (%Rrc)"),
670 mData->m_strConfigFileFull.c_str(), vrc2);
671 }
672 }
673 else if ( vrc != VERR_FILE_NOT_FOUND
674 && vrc != VERR_PATH_NOT_FOUND
675 )
676 rc = setError(VBOX_E_FILE_ERROR,
677 tr("Invalid machine settings file name '%s' (%Rrc)"),
678 mData->m_strConfigFileFull.c_str(),
679 vrc);
680 return rc;
681}
682
683/**
684 * Initializes the registered machine by loading the settings file.
685 * This method is separated from #init() in order to make it possible to
686 * retry the operation after VirtualBox startup instead of refusing to
687 * startup the whole VirtualBox server in case if the settings file of some
688 * registered VM is invalid or inaccessible.
689 *
690 * @note Must be always called from this object's write lock
691 * (unless called from #init() that doesn't need any locking).
692 * @note Locks the mUSBController method for writing.
693 * @note Subclasses must not call this method.
694 */
695HRESULT Machine::i_registeredInit()
696{
697 AssertReturn(!i_isSessionMachine(), E_FAIL);
698 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
699 AssertReturn(mData->mUuid.isValid(), E_FAIL);
700 AssertReturn(!mData->mAccessible, E_FAIL);
701
702 HRESULT rc = initDataAndChildObjects();
703
704 if (SUCCEEDED(rc))
705 {
706 /* Temporarily reset the registered flag in order to let setters
707 * potentially called from loadSettings() succeed (isMutable() used in
708 * all setters will return FALSE for a Machine instance if mRegistered
709 * is TRUE). */
710 mData->mRegistered = FALSE;
711
712 try
713 {
714 // load and parse machine XML; this will throw on XML or logic errors
715 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
716
717 if (mData->mUuid != mData->pMachineConfigFile->uuid)
718 throw setError(E_FAIL,
719 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
720 mData->pMachineConfigFile->uuid.raw(),
721 mData->m_strConfigFileFull.c_str(),
722 mData->mUuid.toString().c_str(),
723 mParent->i_settingsFilePath().c_str());
724
725 rc = i_loadMachineDataFromSettings(*mData->pMachineConfigFile,
726 NULL /* const Guid *puuidRegistry */);
727 if (FAILED(rc)) throw rc;
728 }
729 catch (HRESULT err)
730 {
731 /* we assume that error info is set by the thrower */
732 rc = err;
733 }
734 catch (...)
735 {
736 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
737 }
738
739 /* Restore the registered flag (even on failure) */
740 mData->mRegistered = TRUE;
741 }
742
743 if (SUCCEEDED(rc))
744 {
745 /* Set mAccessible to TRUE only if we successfully locked and loaded
746 * the settings file */
747 mData->mAccessible = TRUE;
748
749 /* commit all changes made during loading the settings file */
750 i_commit(); // @todo r=dj why do we need a commit during init?!? this is very expensive
751 /// @todo r=klaus for some reason the settings loading logic backs up
752 // the settings, and therefore a commit is needed. Should probably be changed.
753 }
754 else
755 {
756 /* If the machine is registered, then, instead of returning a
757 * failure, we mark it as inaccessible and set the result to
758 * success to give it a try later */
759
760 /* fetch the current error info */
761 mData->mAccessError = com::ErrorInfo();
762 Log1Warning(("Machine {%RTuuid} is inaccessible! [%ls]\n", mData->mUuid.raw(), mData->mAccessError.getText().raw()));
763
764 /* rollback all changes */
765 i_rollback(false /* aNotify */);
766
767 // uninit media from this machine's media registry, or else
768 // reloading the settings will fail
769 mParent->i_unregisterMachineMedia(i_getId());
770
771 /* uninitialize the common part to make sure all data is reset to
772 * default (null) values */
773 uninitDataAndChildObjects();
774
775 rc = S_OK;
776 }
777
778 return rc;
779}
780
781/**
782 * Uninitializes the instance.
783 * Called either from FinalRelease() or by the parent when it gets destroyed.
784 *
785 * @note The caller of this method must make sure that this object
786 * a) doesn't have active callers on the current thread and b) is not locked
787 * by the current thread; otherwise uninit() will hang either a) due to
788 * AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
789 * a dead-lock caused by this thread waiting for all callers on the other
790 * threads are done but preventing them from doing so by holding a lock.
791 */
792void Machine::uninit()
793{
794 LogFlowThisFuncEnter();
795
796 Assert(!isWriteLockOnCurrentThread());
797
798 Assert(!uRegistryNeedsSaving);
799 if (uRegistryNeedsSaving)
800 {
801 AutoCaller autoCaller(this);
802 if (SUCCEEDED(autoCaller.rc()))
803 {
804 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
805 i_saveSettings(NULL, Machine::SaveS_Force);
806 }
807 }
808
809 /* Enclose the state transition Ready->InUninit->NotReady */
810 AutoUninitSpan autoUninitSpan(this);
811 if (autoUninitSpan.uninitDone())
812 return;
813
814 Assert(!i_isSnapshotMachine());
815 Assert(!i_isSessionMachine());
816 Assert(!!mData);
817
818 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
819 LogFlowThisFunc(("mRegistered=%d\n", mData->mRegistered));
820
821 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
822
823 if (!mData->mSession.mMachine.isNull())
824 {
825 /* Theoretically, this can only happen if the VirtualBox server has been
826 * terminated while there were clients running that owned open direct
827 * sessions. Since in this case we are definitely called by
828 * VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
829 * won't happen on the client watcher thread (because it does
830 * VirtualBox::addCaller() for the duration of the
831 * SessionMachine::checkForDeath() call, so that VirtualBox::uninit()
832 * cannot happen until the VirtualBox caller is released). This is
833 * important, because SessionMachine::uninit() cannot correctly operate
834 * after we return from this method (it expects the Machine instance is
835 * still valid). We'll call it ourselves below.
836 */
837 Log1WarningThisFunc(("Session machine is not NULL (%p), the direct session is still open!\n",
838 (SessionMachine*)mData->mSession.mMachine));
839
840 if (Global::IsOnlineOrTransient(mData->mMachineState))
841 {
842 Log1WarningThisFunc(("Setting state to Aborted!\n"));
843 /* set machine state using SessionMachine reimplementation */
844 static_cast<Machine*>(mData->mSession.mMachine)->i_setMachineState(MachineState_Aborted);
845 }
846
847 /*
848 * Uninitialize SessionMachine using public uninit() to indicate
849 * an unexpected uninitialization.
850 */
851 mData->mSession.mMachine->uninit();
852 /* SessionMachine::uninit() must set mSession.mMachine to null */
853 Assert(mData->mSession.mMachine.isNull());
854 }
855
856 // uninit media from this machine's media registry, if they're still there
857 Guid uuidMachine(i_getId());
858
859 /* the lock is no more necessary (SessionMachine is uninitialized) */
860 alock.release();
861
862 /* XXX This will fail with
863 * "cannot be closed because it is still attached to 1 virtual machines"
864 * because at this point we did not call uninitDataAndChildObjects() yet
865 * and therefore also removeBackReference() for all these mediums was not called! */
866
867 if (uuidMachine.isValid() && !uuidMachine.isZero()) // can be empty if we're called from a failure of Machine::init
868 mParent->i_unregisterMachineMedia(uuidMachine);
869
870 // has machine been modified?
871 if (mData->flModifications)
872 {
873 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
874 i_rollback(false /* aNotify */);
875 }
876
877 if (mData->mAccessible)
878 uninitDataAndChildObjects();
879
880 /* free the essential data structure last */
881 mData.free();
882
883 LogFlowThisFuncLeave();
884}
885
886// Wrapped IMachine properties
887/////////////////////////////////////////////////////////////////////////////
888HRESULT Machine::getParent(ComPtr<IVirtualBox> &aParent)
889{
890 /* mParent is constant during life time, no need to lock */
891 ComObjPtr<VirtualBox> pVirtualBox(mParent);
892 aParent = pVirtualBox;
893
894 return S_OK;
895}
896
897
898HRESULT Machine::getAccessible(BOOL *aAccessible)
899{
900 /* In some cases (medium registry related), it is necessary to be able to
901 * go through the list of all machines. Happens when an inaccessible VM
902 * has a sensible medium registry. */
903 AutoReadLock mllock(mParent->i_getMachinesListLockHandle() COMMA_LOCKVAL_SRC_POS);
904 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
905
906 HRESULT rc = S_OK;
907
908 if (!mData->mAccessible)
909 {
910 /* try to initialize the VM once more if not accessible */
911
912 AutoReinitSpan autoReinitSpan(this);
913 AssertReturn(autoReinitSpan.isOk(), E_FAIL);
914
915#ifdef DEBUG
916 LogFlowThisFunc(("Dumping media backreferences\n"));
917 mParent->i_dumpAllBackRefs();
918#endif
919
920 if (mData->pMachineConfigFile)
921 {
922 // reset the XML file to force loadSettings() (called from registeredInit())
923 // to parse it again; the file might have changed
924 delete mData->pMachineConfigFile;
925 mData->pMachineConfigFile = NULL;
926 }
927
928 rc = i_registeredInit();
929
930 if (SUCCEEDED(rc) && mData->mAccessible)
931 {
932 autoReinitSpan.setSucceeded();
933
934 /* make sure interesting parties will notice the accessibility
935 * state change */
936 mParent->i_onMachineStateChange(mData->mUuid, mData->mMachineState);
937 mParent->i_onMachineDataChange(mData->mUuid);
938 }
939 }
940
941 if (SUCCEEDED(rc))
942 *aAccessible = mData->mAccessible;
943
944 LogFlowThisFuncLeave();
945
946 return rc;
947}
948
949HRESULT Machine::getAccessError(ComPtr<IVirtualBoxErrorInfo> &aAccessError)
950{
951 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
952
953 if (mData->mAccessible || !mData->mAccessError.isBasicAvailable())
954 {
955 /* return shortly */
956 aAccessError = NULL;
957 return S_OK;
958 }
959
960 HRESULT rc = S_OK;
961
962 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
963 rc = errorInfo.createObject();
964 if (SUCCEEDED(rc))
965 {
966 errorInfo->init(mData->mAccessError.getResultCode(),
967 mData->mAccessError.getInterfaceID().ref(),
968 Utf8Str(mData->mAccessError.getComponent()).c_str(),
969 Utf8Str(mData->mAccessError.getText()));
970 aAccessError = errorInfo;
971 }
972
973 return rc;
974}
975
976HRESULT Machine::getName(com::Utf8Str &aName)
977{
978 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
979
980 aName = mUserData->s.strName;
981
982 return S_OK;
983}
984
985HRESULT Machine::setName(const com::Utf8Str &aName)
986{
987 // prohibit setting a UUID only as the machine name, or else it can
988 // never be found by findMachine()
989 Guid test(aName);
990
991 if (test.isValid())
992 return setError(E_INVALIDARG, tr("A machine cannot have a UUID as its name"));
993
994 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
995
996 HRESULT rc = i_checkStateDependency(MutableStateDep);
997 if (FAILED(rc)) return rc;
998
999 i_setModified(IsModified_MachineData);
1000 mUserData.backup();
1001 mUserData->s.strName = aName;
1002
1003 return S_OK;
1004}
1005
1006HRESULT Machine::getDescription(com::Utf8Str &aDescription)
1007{
1008 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1009
1010 aDescription = mUserData->s.strDescription;
1011
1012 return S_OK;
1013}
1014
1015HRESULT Machine::setDescription(const com::Utf8Str &aDescription)
1016{
1017 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1018
1019 // this can be done in principle in any state as it doesn't affect the VM
1020 // significantly, but play safe by not messing around while complex
1021 // activities are going on
1022 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
1023 if (FAILED(rc)) return rc;
1024
1025 i_setModified(IsModified_MachineData);
1026 mUserData.backup();
1027 mUserData->s.strDescription = aDescription;
1028
1029 return S_OK;
1030}
1031
1032HRESULT Machine::getId(com::Guid &aId)
1033{
1034 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1035
1036 aId = mData->mUuid;
1037
1038 return S_OK;
1039}
1040
1041HRESULT Machine::getGroups(std::vector<com::Utf8Str> &aGroups)
1042{
1043 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1044 aGroups.resize(mUserData->s.llGroups.size());
1045 size_t i = 0;
1046 for (StringsList::const_iterator it = mUserData->s.llGroups.begin();
1047 it != mUserData->s.llGroups.end(); ++it, ++i)
1048 aGroups[i] = (*it);
1049
1050 return S_OK;
1051}
1052
1053HRESULT Machine::setGroups(const std::vector<com::Utf8Str> &aGroups)
1054{
1055 StringsList llGroups;
1056 HRESULT rc = mParent->i_convertMachineGroups(aGroups, &llGroups);
1057 if (FAILED(rc))
1058 return rc;
1059
1060 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1061
1062 rc = i_checkStateDependency(MutableOrSavedStateDep);
1063 if (FAILED(rc)) return rc;
1064
1065 i_setModified(IsModified_MachineData);
1066 mUserData.backup();
1067 mUserData->s.llGroups = llGroups;
1068
1069 return S_OK;
1070}
1071
1072HRESULT Machine::getOSTypeId(com::Utf8Str &aOSTypeId)
1073{
1074 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1075
1076 aOSTypeId = mUserData->s.strOsType;
1077
1078 return S_OK;
1079}
1080
1081HRESULT Machine::setOSTypeId(const com::Utf8Str &aOSTypeId)
1082{
1083 /* look up the object by Id to check it is valid */
1084 ComPtr<IGuestOSType> guestOSType;
1085 HRESULT rc = mParent->GetGuestOSType(Bstr(aOSTypeId).raw(), guestOSType.asOutParam());
1086 if (FAILED(rc)) return rc;
1087
1088 /* when setting, always use the "etalon" value for consistency -- lookup
1089 * by ID is case-insensitive and the input value may have different case */
1090 Bstr osTypeId;
1091 rc = guestOSType->COMGETTER(Id)(osTypeId.asOutParam());
1092 if (FAILED(rc)) return rc;
1093
1094 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1095
1096 rc = i_checkStateDependency(MutableStateDep);
1097 if (FAILED(rc)) return rc;
1098
1099 i_setModified(IsModified_MachineData);
1100 mUserData.backup();
1101 mUserData->s.strOsType = osTypeId;
1102
1103 return S_OK;
1104}
1105
1106HRESULT Machine::getFirmwareType(FirmwareType_T *aFirmwareType)
1107{
1108 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1109
1110 *aFirmwareType = mHWData->mFirmwareType;
1111
1112 return S_OK;
1113}
1114
1115HRESULT Machine::setFirmwareType(FirmwareType_T aFirmwareType)
1116{
1117 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1118
1119 HRESULT rc = i_checkStateDependency(MutableStateDep);
1120 if (FAILED(rc)) return rc;
1121
1122 i_setModified(IsModified_MachineData);
1123 mHWData.backup();
1124 mHWData->mFirmwareType = aFirmwareType;
1125
1126 return S_OK;
1127}
1128
1129HRESULT Machine::getKeyboardHIDType(KeyboardHIDType_T *aKeyboardHIDType)
1130{
1131 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1132
1133 *aKeyboardHIDType = mHWData->mKeyboardHIDType;
1134
1135 return S_OK;
1136}
1137
1138HRESULT Machine::setKeyboardHIDType(KeyboardHIDType_T aKeyboardHIDType)
1139{
1140 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1141
1142 HRESULT rc = i_checkStateDependency(MutableStateDep);
1143 if (FAILED(rc)) return rc;
1144
1145 i_setModified(IsModified_MachineData);
1146 mHWData.backup();
1147 mHWData->mKeyboardHIDType = aKeyboardHIDType;
1148
1149 return S_OK;
1150}
1151
1152HRESULT Machine::getPointingHIDType(PointingHIDType_T *aPointingHIDType)
1153{
1154 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1155
1156 *aPointingHIDType = mHWData->mPointingHIDType;
1157
1158 return S_OK;
1159}
1160
1161HRESULT Machine::setPointingHIDType(PointingHIDType_T aPointingHIDType)
1162{
1163 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1164
1165 HRESULT rc = i_checkStateDependency(MutableStateDep);
1166 if (FAILED(rc)) return rc;
1167
1168 i_setModified(IsModified_MachineData);
1169 mHWData.backup();
1170 mHWData->mPointingHIDType = aPointingHIDType;
1171
1172 return S_OK;
1173}
1174
1175HRESULT Machine::getChipsetType(ChipsetType_T *aChipsetType)
1176{
1177 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1178
1179 *aChipsetType = mHWData->mChipsetType;
1180
1181 return S_OK;
1182}
1183
1184HRESULT Machine::setChipsetType(ChipsetType_T aChipsetType)
1185{
1186 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1187
1188 HRESULT rc = i_checkStateDependency(MutableStateDep);
1189 if (FAILED(rc)) return rc;
1190
1191 if (aChipsetType != mHWData->mChipsetType)
1192 {
1193 i_setModified(IsModified_MachineData);
1194 mHWData.backup();
1195 mHWData->mChipsetType = aChipsetType;
1196
1197 // Resize network adapter array, to be finalized on commit/rollback.
1198 // We must not throw away entries yet, otherwise settings are lost
1199 // without a way to roll back.
1200 size_t newCount = Global::getMaxNetworkAdapters(aChipsetType);
1201 size_t oldCount = mNetworkAdapters.size();
1202 if (newCount > oldCount)
1203 {
1204 mNetworkAdapters.resize(newCount);
1205 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); slot++)
1206 {
1207 unconst(mNetworkAdapters[slot]).createObject();
1208 mNetworkAdapters[slot]->init(this, (ULONG)slot);
1209 }
1210 }
1211 }
1212
1213 return S_OK;
1214}
1215
1216HRESULT Machine::getParavirtProvider(ParavirtProvider_T *aParavirtProvider)
1217{
1218 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1219
1220 *aParavirtProvider = mHWData->mParavirtProvider;
1221
1222 return S_OK;
1223}
1224
1225HRESULT Machine::setParavirtProvider(ParavirtProvider_T aParavirtProvider)
1226{
1227 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1228
1229 HRESULT rc = i_checkStateDependency(MutableStateDep);
1230 if (FAILED(rc)) return rc;
1231
1232 if (aParavirtProvider != mHWData->mParavirtProvider)
1233 {
1234 i_setModified(IsModified_MachineData);
1235 mHWData.backup();
1236 mHWData->mParavirtProvider = aParavirtProvider;
1237 }
1238
1239 return S_OK;
1240}
1241
1242HRESULT Machine::getEffectiveParavirtProvider(ParavirtProvider_T *aParavirtProvider)
1243{
1244 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1245
1246 *aParavirtProvider = mHWData->mParavirtProvider;
1247 switch (mHWData->mParavirtProvider)
1248 {
1249 case ParavirtProvider_None:
1250 case ParavirtProvider_HyperV:
1251 case ParavirtProvider_KVM:
1252 case ParavirtProvider_Minimal:
1253 break;
1254
1255 /* Resolve dynamic provider types to the effective types. */
1256 default:
1257 {
1258 ComPtr<IGuestOSType> ptrGuestOSType;
1259 HRESULT hrc2 = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(), ptrGuestOSType.asOutParam());
1260 AssertMsgReturn(SUCCEEDED(hrc2), ("Failed to get guest OS type. hrc2=%Rhrc\n", hrc2), hrc2);
1261
1262 Bstr guestTypeFamilyId;
1263 hrc2 = ptrGuestOSType->COMGETTER(FamilyId)(guestTypeFamilyId.asOutParam());
1264 AssertMsgReturn(SUCCEEDED(hrc2), ("Failed to get guest family. hrc2=%Rhrc\n", hrc2), hrc2);
1265 BOOL fOsXGuest = guestTypeFamilyId == Bstr("MacOS");
1266
1267 switch (mHWData->mParavirtProvider)
1268 {
1269 case ParavirtProvider_Legacy:
1270 {
1271 if (fOsXGuest)
1272 *aParavirtProvider = ParavirtProvider_Minimal;
1273 else
1274 *aParavirtProvider = ParavirtProvider_None;
1275 break;
1276 }
1277
1278 case ParavirtProvider_Default:
1279 {
1280 if (fOsXGuest)
1281 *aParavirtProvider = ParavirtProvider_Minimal;
1282 else if ( mUserData->s.strOsType == "Windows10"
1283 || mUserData->s.strOsType == "Windows10_64"
1284 || mUserData->s.strOsType == "Windows81"
1285 || mUserData->s.strOsType == "Windows81_64"
1286 || mUserData->s.strOsType == "Windows8"
1287 || mUserData->s.strOsType == "Windows8_64"
1288 || mUserData->s.strOsType == "Windows7"
1289 || mUserData->s.strOsType == "Windows7_64"
1290 || mUserData->s.strOsType == "WindowsVista"
1291 || mUserData->s.strOsType == "WindowsVista_64"
1292 || mUserData->s.strOsType == "Windows2012"
1293 || mUserData->s.strOsType == "Windows2012_64"
1294 || mUserData->s.strOsType == "Windows2008"
1295 || mUserData->s.strOsType == "Windows2008_64")
1296 {
1297 *aParavirtProvider = ParavirtProvider_HyperV;
1298 }
1299 else if ( mUserData->s.strOsType == "Linux26" // Linux22 and Linux24 omitted as they're too old
1300 || mUserData->s.strOsType == "Linux26_64" // for having any KVM paravirtualization support.
1301 || mUserData->s.strOsType == "Linux"
1302 || mUserData->s.strOsType == "Linux_64"
1303 || mUserData->s.strOsType == "ArchLinux"
1304 || mUserData->s.strOsType == "ArchLinux_64"
1305 || mUserData->s.strOsType == "Debian"
1306 || mUserData->s.strOsType == "Debian_64"
1307 || mUserData->s.strOsType == "Fedora"
1308 || mUserData->s.strOsType == "Fedora_64"
1309 || mUserData->s.strOsType == "Gentoo"
1310 || mUserData->s.strOsType == "Gentoo_64"
1311 || mUserData->s.strOsType == "Mandriva"
1312 || mUserData->s.strOsType == "Mandriva_64"
1313 || mUserData->s.strOsType == "OpenSUSE"
1314 || mUserData->s.strOsType == "OpenSUSE_64"
1315 || mUserData->s.strOsType == "Oracle"
1316 || mUserData->s.strOsType == "Oracle_64"
1317 || mUserData->s.strOsType == "RedHat"
1318 || mUserData->s.strOsType == "RedHat_64"
1319 || mUserData->s.strOsType == "Turbolinux"
1320 || mUserData->s.strOsType == "Turbolinux_64"
1321 || mUserData->s.strOsType == "Ubuntu"
1322 || mUserData->s.strOsType == "Ubuntu_64"
1323 || mUserData->s.strOsType == "Xandros"
1324 || mUserData->s.strOsType == "Xandros_64")
1325 {
1326 *aParavirtProvider = ParavirtProvider_KVM;
1327 }
1328 else
1329 *aParavirtProvider = ParavirtProvider_None;
1330 break;
1331 }
1332 }
1333 break;
1334 }
1335 }
1336
1337 Assert( *aParavirtProvider == ParavirtProvider_None
1338 || *aParavirtProvider == ParavirtProvider_Minimal
1339 || *aParavirtProvider == ParavirtProvider_HyperV
1340 || *aParavirtProvider == ParavirtProvider_KVM);
1341 return S_OK;
1342}
1343
1344HRESULT Machine::getHardwareVersion(com::Utf8Str &aHardwareVersion)
1345{
1346 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1347
1348 aHardwareVersion = mHWData->mHWVersion;
1349
1350 return S_OK;
1351}
1352
1353HRESULT Machine::setHardwareVersion(const com::Utf8Str &aHardwareVersion)
1354{
1355 /* check known version */
1356 Utf8Str hwVersion = aHardwareVersion;
1357 if ( hwVersion.compare("1") != 0
1358 && hwVersion.compare("2") != 0)
1359 return setError(E_INVALIDARG,
1360 tr("Invalid hardware version: %s\n"), aHardwareVersion.c_str());
1361
1362 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1363
1364 HRESULT rc = i_checkStateDependency(MutableStateDep);
1365 if (FAILED(rc)) return rc;
1366
1367 i_setModified(IsModified_MachineData);
1368 mHWData.backup();
1369 mHWData->mHWVersion = aHardwareVersion;
1370
1371 return S_OK;
1372}
1373
1374HRESULT Machine::getHardwareUUID(com::Guid &aHardwareUUID)
1375{
1376 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1377
1378 if (!mHWData->mHardwareUUID.isZero())
1379 aHardwareUUID = mHWData->mHardwareUUID;
1380 else
1381 aHardwareUUID = mData->mUuid;
1382
1383 return S_OK;
1384}
1385
1386HRESULT Machine::setHardwareUUID(const com::Guid &aHardwareUUID)
1387{
1388 if (!aHardwareUUID.isValid())
1389 return E_INVALIDARG;
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 if (aHardwareUUID == mData->mUuid)
1399 mHWData->mHardwareUUID.clear();
1400 else
1401 mHWData->mHardwareUUID = aHardwareUUID;
1402
1403 return S_OK;
1404}
1405
1406HRESULT Machine::getMemorySize(ULONG *aMemorySize)
1407{
1408 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1409
1410 *aMemorySize = mHWData->mMemorySize;
1411
1412 return S_OK;
1413}
1414
1415HRESULT Machine::setMemorySize(ULONG aMemorySize)
1416{
1417 /* check RAM limits */
1418 if ( aMemorySize < MM_RAM_MIN_IN_MB
1419 || aMemorySize > MM_RAM_MAX_IN_MB
1420 )
1421 return setError(E_INVALIDARG,
1422 tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1423 aMemorySize, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
1424
1425 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1426
1427 HRESULT rc = i_checkStateDependency(MutableStateDep);
1428 if (FAILED(rc)) return rc;
1429
1430 i_setModified(IsModified_MachineData);
1431 mHWData.backup();
1432 mHWData->mMemorySize = aMemorySize;
1433
1434 return S_OK;
1435}
1436
1437HRESULT Machine::getCPUCount(ULONG *aCPUCount)
1438{
1439 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1440
1441 *aCPUCount = mHWData->mCPUCount;
1442
1443 return S_OK;
1444}
1445
1446HRESULT Machine::setCPUCount(ULONG aCPUCount)
1447{
1448 /* check CPU limits */
1449 if ( aCPUCount < SchemaDefs::MinCPUCount
1450 || aCPUCount > SchemaDefs::MaxCPUCount
1451 )
1452 return setError(E_INVALIDARG,
1453 tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
1454 aCPUCount, SchemaDefs::MinCPUCount, SchemaDefs::MaxCPUCount);
1455
1456 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1457
1458 /* We cant go below the current number of CPUs attached if hotplug is enabled*/
1459 if (mHWData->mCPUHotPlugEnabled)
1460 {
1461 for (unsigned idx = aCPUCount; idx < SchemaDefs::MaxCPUCount; idx++)
1462 {
1463 if (mHWData->mCPUAttached[idx])
1464 return setError(E_INVALIDARG,
1465 tr("There is still a CPU attached to socket %lu."
1466 "Detach the CPU before removing the socket"),
1467 aCPUCount, idx+1);
1468 }
1469 }
1470
1471 HRESULT rc = i_checkStateDependency(MutableStateDep);
1472 if (FAILED(rc)) return rc;
1473
1474 i_setModified(IsModified_MachineData);
1475 mHWData.backup();
1476 mHWData->mCPUCount = aCPUCount;
1477
1478 return S_OK;
1479}
1480
1481HRESULT Machine::getCPUExecutionCap(ULONG *aCPUExecutionCap)
1482{
1483 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1484
1485 *aCPUExecutionCap = mHWData->mCpuExecutionCap;
1486
1487 return S_OK;
1488}
1489
1490HRESULT Machine::setCPUExecutionCap(ULONG aCPUExecutionCap)
1491{
1492 HRESULT rc = S_OK;
1493
1494 /* check throttle limits */
1495 if ( aCPUExecutionCap < 1
1496 || aCPUExecutionCap > 100
1497 )
1498 return setError(E_INVALIDARG,
1499 tr("Invalid CPU execution cap value: %lu (must be in range [%lu, %lu])"),
1500 aCPUExecutionCap, 1, 100);
1501
1502 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1503
1504 alock.release();
1505 rc = i_onCPUExecutionCapChange(aCPUExecutionCap);
1506 alock.acquire();
1507 if (FAILED(rc)) return rc;
1508
1509 i_setModified(IsModified_MachineData);
1510 mHWData.backup();
1511 mHWData->mCpuExecutionCap = aCPUExecutionCap;
1512
1513 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1514 if (Global::IsOnline(mData->mMachineState))
1515 i_saveSettings(NULL);
1516
1517 return S_OK;
1518}
1519
1520HRESULT Machine::getCPUHotPlugEnabled(BOOL *aCPUHotPlugEnabled)
1521{
1522 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1523
1524 *aCPUHotPlugEnabled = mHWData->mCPUHotPlugEnabled;
1525
1526 return S_OK;
1527}
1528
1529HRESULT Machine::setCPUHotPlugEnabled(BOOL aCPUHotPlugEnabled)
1530{
1531 HRESULT rc = S_OK;
1532
1533 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1534
1535 rc = i_checkStateDependency(MutableStateDep);
1536 if (FAILED(rc)) return rc;
1537
1538 if (mHWData->mCPUHotPlugEnabled != aCPUHotPlugEnabled)
1539 {
1540 if (aCPUHotPlugEnabled)
1541 {
1542 i_setModified(IsModified_MachineData);
1543 mHWData.backup();
1544
1545 /* Add the amount of CPUs currently attached */
1546 for (unsigned i = 0; i < mHWData->mCPUCount; ++i)
1547 mHWData->mCPUAttached[i] = true;
1548 }
1549 else
1550 {
1551 /*
1552 * We can disable hotplug only if the amount of maximum CPUs is equal
1553 * to the amount of attached CPUs
1554 */
1555 unsigned cCpusAttached = 0;
1556 unsigned iHighestId = 0;
1557
1558 for (unsigned i = 0; i < SchemaDefs::MaxCPUCount; ++i)
1559 {
1560 if (mHWData->mCPUAttached[i])
1561 {
1562 cCpusAttached++;
1563 iHighestId = i;
1564 }
1565 }
1566
1567 if ( (cCpusAttached != mHWData->mCPUCount)
1568 || (iHighestId >= mHWData->mCPUCount))
1569 return setError(E_INVALIDARG,
1570 tr("CPU hotplugging can't be disabled because the maximum number of CPUs is not equal to the amount of CPUs attached"));
1571
1572 i_setModified(IsModified_MachineData);
1573 mHWData.backup();
1574 }
1575 }
1576
1577 mHWData->mCPUHotPlugEnabled = aCPUHotPlugEnabled;
1578
1579 return rc;
1580}
1581
1582HRESULT Machine::getCPUIDPortabilityLevel(ULONG *aCPUIDPortabilityLevel)
1583{
1584 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1585
1586 *aCPUIDPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
1587
1588 return S_OK;
1589}
1590
1591HRESULT Machine::setCPUIDPortabilityLevel(ULONG aCPUIDPortabilityLevel)
1592{
1593 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1594
1595 HRESULT hrc = i_checkStateDependency(MutableStateDep);
1596 if (SUCCEEDED(hrc))
1597 {
1598 i_setModified(IsModified_MachineData);
1599 mHWData.backup();
1600 mHWData->mCpuIdPortabilityLevel = aCPUIDPortabilityLevel;
1601 }
1602 return hrc;
1603}
1604
1605HRESULT Machine::getEmulatedUSBCardReaderEnabled(BOOL *aEmulatedUSBCardReaderEnabled)
1606{
1607#ifdef VBOX_WITH_USB_CARDREADER
1608 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1609
1610 *aEmulatedUSBCardReaderEnabled = mHWData->mEmulatedUSBCardReaderEnabled;
1611
1612 return S_OK;
1613#else
1614 NOREF(aEmulatedUSBCardReaderEnabled);
1615 return E_NOTIMPL;
1616#endif
1617}
1618
1619HRESULT Machine::setEmulatedUSBCardReaderEnabled(BOOL aEmulatedUSBCardReaderEnabled)
1620{
1621#ifdef VBOX_WITH_USB_CARDREADER
1622 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1623
1624 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
1625 if (FAILED(rc)) return rc;
1626
1627 i_setModified(IsModified_MachineData);
1628 mHWData.backup();
1629 mHWData->mEmulatedUSBCardReaderEnabled = aEmulatedUSBCardReaderEnabled;
1630
1631 return S_OK;
1632#else
1633 NOREF(aEmulatedUSBCardReaderEnabled);
1634 return E_NOTIMPL;
1635#endif
1636}
1637
1638HRESULT Machine::getHPETEnabled(BOOL *aHPETEnabled)
1639{
1640 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1641
1642 *aHPETEnabled = mHWData->mHPETEnabled;
1643
1644 return S_OK;
1645}
1646
1647HRESULT Machine::setHPETEnabled(BOOL aHPETEnabled)
1648{
1649 HRESULT rc = S_OK;
1650
1651 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1652
1653 rc = i_checkStateDependency(MutableStateDep);
1654 if (FAILED(rc)) return rc;
1655
1656 i_setModified(IsModified_MachineData);
1657 mHWData.backup();
1658
1659 mHWData->mHPETEnabled = aHPETEnabled;
1660
1661 return rc;
1662}
1663
1664HRESULT Machine::getVideoCaptureEnabled(BOOL *aVideoCaptureEnabled)
1665{
1666 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1667
1668 *aVideoCaptureEnabled = mHWData->mVideoCaptureEnabled;
1669 return S_OK;
1670}
1671
1672HRESULT Machine::setVideoCaptureEnabled(BOOL aVideoCaptureEnabled)
1673{
1674 HRESULT rc = S_OK;
1675
1676 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1677
1678 i_setModified(IsModified_MachineData);
1679 mHWData.backup();
1680 mHWData->mVideoCaptureEnabled = aVideoCaptureEnabled;
1681
1682 alock.release();
1683 rc = i_onVideoCaptureChange();
1684 alock.acquire();
1685 if (FAILED(rc))
1686 {
1687 /*
1688 * Normally we would do the actual change _after_ i_onVideoCaptureChange() succeeded.
1689 * We cannot do this because that function uses Machine::GetVideoCaptureEnabled to
1690 * determine if it should start or stop capturing. Therefore we need to manually
1691 * undo change.
1692 */
1693 mHWData->mVideoCaptureEnabled = mHWData.backedUpData()->mVideoCaptureEnabled;
1694 return rc;
1695 }
1696
1697 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1698 if (Global::IsOnline(mData->mMachineState))
1699 i_saveSettings(NULL);
1700
1701 return rc;
1702}
1703
1704HRESULT Machine::getVideoCaptureScreens(std::vector<BOOL> &aVideoCaptureScreens)
1705{
1706 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1707 aVideoCaptureScreens.resize(mHWData->mMonitorCount);
1708 for (unsigned i = 0; i < mHWData->mMonitorCount; ++i)
1709 aVideoCaptureScreens[i] = mHWData->maVideoCaptureScreens[i];
1710 return S_OK;
1711}
1712
1713HRESULT Machine::setVideoCaptureScreens(const std::vector<BOOL> &aVideoCaptureScreens)
1714{
1715 AssertReturn(aVideoCaptureScreens.size() <= RT_ELEMENTS(mHWData->maVideoCaptureScreens), E_INVALIDARG);
1716 bool fChanged = false;
1717
1718 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1719
1720 for (unsigned i = 0; i < aVideoCaptureScreens.size(); ++i)
1721 {
1722 if (mHWData->maVideoCaptureScreens[i] != RT_BOOL(aVideoCaptureScreens[i]))
1723 {
1724 mHWData->maVideoCaptureScreens[i] = RT_BOOL(aVideoCaptureScreens[i]);
1725 fChanged = true;
1726 }
1727 }
1728 if (fChanged)
1729 {
1730 alock.release();
1731 HRESULT rc = i_onVideoCaptureChange();
1732 alock.acquire();
1733 if (FAILED(rc)) return rc;
1734 i_setModified(IsModified_MachineData);
1735
1736 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
1737 if (Global::IsOnline(mData->mMachineState))
1738 i_saveSettings(NULL);
1739 }
1740
1741 return S_OK;
1742}
1743
1744HRESULT Machine::getVideoCaptureFile(com::Utf8Str &aVideoCaptureFile)
1745{
1746 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1747 if (mHWData->mVideoCaptureFile.isEmpty())
1748 i_getDefaultVideoCaptureFile(aVideoCaptureFile);
1749 else
1750 aVideoCaptureFile = mHWData->mVideoCaptureFile;
1751 return S_OK;
1752}
1753
1754HRESULT Machine::setVideoCaptureFile(const com::Utf8Str &aVideoCaptureFile)
1755{
1756 Utf8Str strFile(aVideoCaptureFile);
1757 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1758
1759 if ( Global::IsOnline(mData->mMachineState)
1760 && mHWData->mVideoCaptureEnabled)
1761 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1762
1763 if (!RTPathStartsWithRoot(strFile.c_str()))
1764 return setError(E_INVALIDARG, tr("Video capture file name '%s' is not absolute"), strFile.c_str());
1765
1766 if (!strFile.isEmpty())
1767 {
1768 Utf8Str defaultFile;
1769 i_getDefaultVideoCaptureFile(defaultFile);
1770 if (!RTPathCompare(strFile.c_str(), defaultFile.c_str()))
1771 strFile.setNull();
1772 }
1773
1774 i_setModified(IsModified_MachineData);
1775 mHWData.backup();
1776 mHWData->mVideoCaptureFile = strFile;
1777
1778 return S_OK;
1779}
1780
1781HRESULT Machine::getVideoCaptureWidth(ULONG *aVideoCaptureWidth)
1782{
1783 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1784 *aVideoCaptureWidth = mHWData->mVideoCaptureWidth;
1785 return S_OK;
1786}
1787
1788HRESULT Machine::setVideoCaptureWidth(ULONG aVideoCaptureWidth)
1789{
1790 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1791
1792 if ( Global::IsOnline(mData->mMachineState)
1793 && mHWData->mVideoCaptureEnabled)
1794 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1795
1796 i_setModified(IsModified_MachineData);
1797 mHWData.backup();
1798 mHWData->mVideoCaptureWidth = aVideoCaptureWidth;
1799
1800 return S_OK;
1801}
1802
1803HRESULT Machine::getVideoCaptureHeight(ULONG *aVideoCaptureHeight)
1804{
1805 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1806 *aVideoCaptureHeight = mHWData->mVideoCaptureHeight;
1807 return S_OK;
1808}
1809
1810HRESULT Machine::setVideoCaptureHeight(ULONG aVideoCaptureHeight)
1811{
1812 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1813
1814 if ( Global::IsOnline(mData->mMachineState)
1815 && mHWData->mVideoCaptureEnabled)
1816 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1817
1818 i_setModified(IsModified_MachineData);
1819 mHWData.backup();
1820 mHWData->mVideoCaptureHeight = aVideoCaptureHeight;
1821
1822 return S_OK;
1823}
1824
1825HRESULT Machine::getVideoCaptureRate(ULONG *aVideoCaptureRate)
1826{
1827 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1828 *aVideoCaptureRate = mHWData->mVideoCaptureRate;
1829 return S_OK;
1830}
1831
1832HRESULT Machine::setVideoCaptureRate(ULONG aVideoCaptureRate)
1833{
1834 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1835
1836 if ( Global::IsOnline(mData->mMachineState)
1837 && mHWData->mVideoCaptureEnabled)
1838 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1839
1840 i_setModified(IsModified_MachineData);
1841 mHWData.backup();
1842 mHWData->mVideoCaptureRate = aVideoCaptureRate;
1843
1844 return S_OK;
1845}
1846
1847HRESULT Machine::getVideoCaptureFPS(ULONG *aVideoCaptureFPS)
1848{
1849 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1850 *aVideoCaptureFPS = mHWData->mVideoCaptureFPS;
1851 return S_OK;
1852}
1853
1854HRESULT Machine::setVideoCaptureFPS(ULONG aVideoCaptureFPS)
1855{
1856 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1857
1858 if ( Global::IsOnline(mData->mMachineState)
1859 && mHWData->mVideoCaptureEnabled)
1860 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1861
1862 i_setModified(IsModified_MachineData);
1863 mHWData.backup();
1864 mHWData->mVideoCaptureFPS = aVideoCaptureFPS;
1865
1866 return S_OK;
1867}
1868
1869HRESULT Machine::getVideoCaptureMaxTime(ULONG *aVideoCaptureMaxTime)
1870{
1871 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1872 *aVideoCaptureMaxTime = mHWData->mVideoCaptureMaxTime;
1873 return S_OK;
1874}
1875
1876HRESULT Machine::setVideoCaptureMaxTime(ULONG aVideoCaptureMaxTime)
1877{
1878 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1879
1880 if ( Global::IsOnline(mData->mMachineState)
1881 && mHWData->mVideoCaptureEnabled)
1882 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1883
1884 i_setModified(IsModified_MachineData);
1885 mHWData.backup();
1886 mHWData->mVideoCaptureMaxTime = aVideoCaptureMaxTime;
1887
1888 return S_OK;
1889}
1890
1891HRESULT Machine::getVideoCaptureMaxFileSize(ULONG *aVideoCaptureMaxFileSize)
1892{
1893 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1894 *aVideoCaptureMaxFileSize = mHWData->mVideoCaptureMaxFileSize;
1895 return S_OK;
1896}
1897
1898HRESULT Machine::setVideoCaptureMaxFileSize(ULONG aVideoCaptureMaxFileSize)
1899{
1900 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1901
1902 if ( Global::IsOnline(mData->mMachineState)
1903 && mHWData->mVideoCaptureEnabled)
1904 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1905
1906 i_setModified(IsModified_MachineData);
1907 mHWData.backup();
1908 mHWData->mVideoCaptureMaxFileSize = aVideoCaptureMaxFileSize;
1909
1910 return S_OK;
1911}
1912
1913HRESULT Machine::getVideoCaptureOptions(com::Utf8Str &aVideoCaptureOptions)
1914{
1915 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1916
1917 aVideoCaptureOptions = mHWData->mVideoCaptureOptions;
1918 return S_OK;
1919}
1920
1921HRESULT Machine::setVideoCaptureOptions(const com::Utf8Str &aVideoCaptureOptions)
1922{
1923 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1924
1925 if ( Global::IsOnline(mData->mMachineState)
1926 && mHWData->mVideoCaptureEnabled)
1927 return setError(E_INVALIDARG, tr("Cannot change parameters while capturing is enabled"));
1928
1929 i_setModified(IsModified_MachineData);
1930 mHWData.backup();
1931 mHWData->mVideoCaptureOptions = aVideoCaptureOptions;
1932
1933 return S_OK;
1934}
1935
1936HRESULT Machine::getGraphicsControllerType(GraphicsControllerType_T *aGraphicsControllerType)
1937{
1938 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1939
1940 *aGraphicsControllerType = mHWData->mGraphicsControllerType;
1941
1942 return S_OK;
1943}
1944
1945HRESULT Machine::setGraphicsControllerType(GraphicsControllerType_T aGraphicsControllerType)
1946{
1947 switch (aGraphicsControllerType)
1948 {
1949 case GraphicsControllerType_Null:
1950 case GraphicsControllerType_VBoxVGA:
1951#ifdef VBOX_WITH_VMSVGA
1952 case GraphicsControllerType_VMSVGA:
1953#endif
1954 break;
1955 default:
1956 return setError(E_INVALIDARG, tr("The graphics controller type (%d) is invalid"), aGraphicsControllerType);
1957 }
1958
1959 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1960
1961 HRESULT rc = i_checkStateDependency(MutableStateDep);
1962 if (FAILED(rc)) return rc;
1963
1964 i_setModified(IsModified_MachineData);
1965 mHWData.backup();
1966 mHWData->mGraphicsControllerType = aGraphicsControllerType;
1967
1968 return S_OK;
1969}
1970
1971HRESULT Machine::getVRAMSize(ULONG *aVRAMSize)
1972{
1973 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1974
1975 *aVRAMSize = mHWData->mVRAMSize;
1976
1977 return S_OK;
1978}
1979
1980HRESULT Machine::setVRAMSize(ULONG aVRAMSize)
1981{
1982 /* check VRAM limits */
1983 if (aVRAMSize < SchemaDefs::MinGuestVRAM ||
1984 aVRAMSize > SchemaDefs::MaxGuestVRAM)
1985 return setError(E_INVALIDARG,
1986 tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1987 aVRAMSize, SchemaDefs::MinGuestVRAM, SchemaDefs::MaxGuestVRAM);
1988
1989 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1990
1991 HRESULT rc = i_checkStateDependency(MutableStateDep);
1992 if (FAILED(rc)) return rc;
1993
1994 i_setModified(IsModified_MachineData);
1995 mHWData.backup();
1996 mHWData->mVRAMSize = aVRAMSize;
1997
1998 return S_OK;
1999}
2000
2001/** @todo this method should not be public */
2002HRESULT Machine::getMemoryBalloonSize(ULONG *aMemoryBalloonSize)
2003{
2004 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2005
2006 *aMemoryBalloonSize = mHWData->mMemoryBalloonSize;
2007
2008 return S_OK;
2009}
2010
2011/**
2012 * Set the memory balloon size.
2013 *
2014 * This method is also called from IGuest::COMSETTER(MemoryBalloonSize) so
2015 * we have to make sure that we never call IGuest from here.
2016 */
2017HRESULT Machine::setMemoryBalloonSize(ULONG aMemoryBalloonSize)
2018{
2019 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
2020#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
2021 /* check limits */
2022 if (aMemoryBalloonSize >= VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize))
2023 return setError(E_INVALIDARG,
2024 tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
2025 aMemoryBalloonSize, 0, VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize));
2026
2027 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2028
2029 i_setModified(IsModified_MachineData);
2030 mHWData.backup();
2031 mHWData->mMemoryBalloonSize = aMemoryBalloonSize;
2032
2033 return S_OK;
2034#else
2035 NOREF(aMemoryBalloonSize);
2036 return setError(E_NOTIMPL, tr("Memory ballooning is only supported on 64-bit hosts"));
2037#endif
2038}
2039
2040HRESULT Machine::getPageFusionEnabled(BOOL *aPageFusionEnabled)
2041{
2042 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2043
2044 *aPageFusionEnabled = mHWData->mPageFusionEnabled;
2045 return S_OK;
2046}
2047
2048HRESULT Machine::setPageFusionEnabled(BOOL aPageFusionEnabled)
2049{
2050#ifdef VBOX_WITH_PAGE_SHARING
2051 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2052
2053 /** @todo must support changes for running vms and keep this in sync with IGuest. */
2054 i_setModified(IsModified_MachineData);
2055 mHWData.backup();
2056 mHWData->mPageFusionEnabled = aPageFusionEnabled;
2057 return S_OK;
2058#else
2059 NOREF(aPageFusionEnabled);
2060 return setError(E_NOTIMPL, tr("Page fusion is only supported on 64-bit hosts"));
2061#endif
2062}
2063
2064HRESULT Machine::getAccelerate3DEnabled(BOOL *aAccelerate3DEnabled)
2065{
2066 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2067
2068 *aAccelerate3DEnabled = mHWData->mAccelerate3DEnabled;
2069
2070 return S_OK;
2071}
2072
2073HRESULT Machine::setAccelerate3DEnabled(BOOL aAccelerate3DEnabled)
2074{
2075 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2076
2077 HRESULT rc = i_checkStateDependency(MutableStateDep);
2078 if (FAILED(rc)) return rc;
2079
2080 /** @todo check validity! */
2081
2082 i_setModified(IsModified_MachineData);
2083 mHWData.backup();
2084 mHWData->mAccelerate3DEnabled = aAccelerate3DEnabled;
2085
2086 return S_OK;
2087}
2088
2089
2090HRESULT Machine::getAccelerate2DVideoEnabled(BOOL *aAccelerate2DVideoEnabled)
2091{
2092 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2093
2094 *aAccelerate2DVideoEnabled = mHWData->mAccelerate2DVideoEnabled;
2095
2096 return S_OK;
2097}
2098
2099HRESULT Machine::setAccelerate2DVideoEnabled(BOOL aAccelerate2DVideoEnabled)
2100{
2101 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2102
2103 HRESULT rc = i_checkStateDependency(MutableStateDep);
2104 if (FAILED(rc)) return rc;
2105
2106 /** @todo check validity! */
2107 i_setModified(IsModified_MachineData);
2108 mHWData.backup();
2109 mHWData->mAccelerate2DVideoEnabled = aAccelerate2DVideoEnabled;
2110
2111 return S_OK;
2112}
2113
2114HRESULT Machine::getMonitorCount(ULONG *aMonitorCount)
2115{
2116 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2117
2118 *aMonitorCount = mHWData->mMonitorCount;
2119
2120 return S_OK;
2121}
2122
2123HRESULT Machine::setMonitorCount(ULONG aMonitorCount)
2124{
2125 /* make sure monitor count is a sensible number */
2126 if (aMonitorCount < 1 || aMonitorCount > SchemaDefs::MaxGuestMonitors)
2127 return setError(E_INVALIDARG,
2128 tr("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
2129 aMonitorCount, 1, SchemaDefs::MaxGuestMonitors);
2130
2131 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2132
2133 HRESULT rc = i_checkStateDependency(MutableStateDep);
2134 if (FAILED(rc)) return rc;
2135
2136 i_setModified(IsModified_MachineData);
2137 mHWData.backup();
2138 mHWData->mMonitorCount = aMonitorCount;
2139
2140 return S_OK;
2141}
2142
2143HRESULT Machine::getBIOSSettings(ComPtr<IBIOSSettings> &aBIOSSettings)
2144{
2145 /* mBIOSSettings is constant during life time, no need to lock */
2146 aBIOSSettings = mBIOSSettings;
2147
2148 return S_OK;
2149}
2150
2151HRESULT Machine::getCPUProperty(CPUPropertyType_T aProperty, BOOL *aValue)
2152{
2153 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2154
2155 switch (aProperty)
2156 {
2157 case CPUPropertyType_PAE:
2158 *aValue = mHWData->mPAEEnabled;
2159 break;
2160
2161 case CPUPropertyType_LongMode:
2162 if (mHWData->mLongMode == settings::Hardware::LongMode_Enabled)
2163 *aValue = TRUE;
2164 else if (mHWData->mLongMode == settings::Hardware::LongMode_Disabled)
2165 *aValue = FALSE;
2166#if HC_ARCH_BITS == 64
2167 else
2168 *aValue = TRUE;
2169#else
2170 else
2171 {
2172 *aValue = FALSE;
2173
2174 ComPtr<IGuestOSType> ptrGuestOSType;
2175 HRESULT hrc2 = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(), ptrGuestOSType.asOutParam());
2176 if (SUCCEEDED(hrc2))
2177 {
2178 BOOL fIs64Bit = FALSE;
2179 hrc2 = ptrGuestOSType->COMGETTER(Is64Bit)(&fIs64Bit); AssertComRC(hrc2);
2180 if (SUCCEEDED(hrc2) && fIs64Bit)
2181 {
2182 ComObjPtr<Host> ptrHost = mParent->i_host();
2183 alock.release();
2184
2185 hrc2 = ptrHost->GetProcessorFeature(ProcessorFeature_LongMode, aValue); AssertComRC(hrc2);
2186 if (FAILED(hrc2))
2187 *aValue = FALSE;
2188 }
2189 }
2190 }
2191#endif
2192 break;
2193
2194 case CPUPropertyType_TripleFaultReset:
2195 *aValue = mHWData->mTripleFaultReset;
2196 break;
2197
2198 default:
2199 return E_INVALIDARG;
2200 }
2201 return S_OK;
2202}
2203
2204HRESULT Machine::setCPUProperty(CPUPropertyType_T aProperty, BOOL aValue)
2205{
2206 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2207
2208 HRESULT rc = i_checkStateDependency(MutableStateDep);
2209 if (FAILED(rc)) return rc;
2210
2211 switch (aProperty)
2212 {
2213 case CPUPropertyType_PAE:
2214 i_setModified(IsModified_MachineData);
2215 mHWData.backup();
2216 mHWData->mPAEEnabled = !!aValue;
2217 break;
2218
2219 case CPUPropertyType_LongMode:
2220 i_setModified(IsModified_MachineData);
2221 mHWData.backup();
2222 mHWData->mLongMode = !aValue ? settings::Hardware::LongMode_Disabled : settings::Hardware::LongMode_Enabled;
2223 break;
2224
2225 case CPUPropertyType_TripleFaultReset:
2226 i_setModified(IsModified_MachineData);
2227 mHWData.backup();
2228 mHWData->mTripleFaultReset = !!aValue;
2229 break;
2230
2231 default:
2232 return E_INVALIDARG;
2233 }
2234 return S_OK;
2235}
2236
2237HRESULT Machine::getCPUIDLeaf(ULONG aId, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx)
2238{
2239 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2240
2241 switch(aId)
2242 {
2243 case 0x0:
2244 case 0x1:
2245 case 0x2:
2246 case 0x3:
2247 case 0x4:
2248 case 0x5:
2249 case 0x6:
2250 case 0x7:
2251 case 0x8:
2252 case 0x9:
2253 case 0xA:
2254 if (mHWData->mCpuIdStdLeafs[aId].ulId != aId)
2255 return E_INVALIDARG;
2256
2257 *aValEax = mHWData->mCpuIdStdLeafs[aId].ulEax;
2258 *aValEbx = mHWData->mCpuIdStdLeafs[aId].ulEbx;
2259 *aValEcx = mHWData->mCpuIdStdLeafs[aId].ulEcx;
2260 *aValEdx = mHWData->mCpuIdStdLeafs[aId].ulEdx;
2261 break;
2262
2263 case 0x80000000:
2264 case 0x80000001:
2265 case 0x80000002:
2266 case 0x80000003:
2267 case 0x80000004:
2268 case 0x80000005:
2269 case 0x80000006:
2270 case 0x80000007:
2271 case 0x80000008:
2272 case 0x80000009:
2273 case 0x8000000A:
2274 if (mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId != aId)
2275 return E_INVALIDARG;
2276
2277 *aValEax = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax;
2278 *aValEbx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx;
2279 *aValEcx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx;
2280 *aValEdx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx;
2281 break;
2282
2283 default:
2284 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2285 }
2286 return S_OK;
2287}
2288
2289
2290HRESULT Machine::setCPUIDLeaf(ULONG aId, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx)
2291{
2292 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2293
2294 HRESULT rc = i_checkStateDependency(MutableStateDep);
2295 if (FAILED(rc)) return rc;
2296
2297 switch(aId)
2298 {
2299 case 0x0:
2300 case 0x1:
2301 case 0x2:
2302 case 0x3:
2303 case 0x4:
2304 case 0x5:
2305 case 0x6:
2306 case 0x7:
2307 case 0x8:
2308 case 0x9:
2309 case 0xA:
2310 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2311 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2312 i_setModified(IsModified_MachineData);
2313 mHWData.backup();
2314 mHWData->mCpuIdStdLeafs[aId].ulId = aId;
2315 mHWData->mCpuIdStdLeafs[aId].ulEax = aValEax;
2316 mHWData->mCpuIdStdLeafs[aId].ulEbx = aValEbx;
2317 mHWData->mCpuIdStdLeafs[aId].ulEcx = aValEcx;
2318 mHWData->mCpuIdStdLeafs[aId].ulEdx = aValEdx;
2319 break;
2320
2321 case 0x80000000:
2322 case 0x80000001:
2323 case 0x80000002:
2324 case 0x80000003:
2325 case 0x80000004:
2326 case 0x80000005:
2327 case 0x80000006:
2328 case 0x80000007:
2329 case 0x80000008:
2330 case 0x80000009:
2331 case 0x8000000A:
2332 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2333 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2334 i_setModified(IsModified_MachineData);
2335 mHWData.backup();
2336 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = aId;
2337 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax = aValEax;
2338 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx = aValEbx;
2339 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx = aValEcx;
2340 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx = aValEdx;
2341 break;
2342
2343 default:
2344 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2345 }
2346 return S_OK;
2347}
2348
2349HRESULT Machine::removeCPUIDLeaf(ULONG aId)
2350{
2351 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2352
2353 HRESULT rc = i_checkStateDependency(MutableStateDep);
2354 if (FAILED(rc)) return rc;
2355
2356 switch(aId)
2357 {
2358 case 0x0:
2359 case 0x1:
2360 case 0x2:
2361 case 0x3:
2362 case 0x4:
2363 case 0x5:
2364 case 0x6:
2365 case 0x7:
2366 case 0x8:
2367 case 0x9:
2368 case 0xA:
2369 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2370 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2371 i_setModified(IsModified_MachineData);
2372 mHWData.backup();
2373 /* Invalidate leaf. */
2374 mHWData->mCpuIdStdLeafs[aId].ulId = UINT32_MAX;
2375 break;
2376
2377 case 0x80000000:
2378 case 0x80000001:
2379 case 0x80000002:
2380 case 0x80000003:
2381 case 0x80000004:
2382 case 0x80000005:
2383 case 0x80000006:
2384 case 0x80000007:
2385 case 0x80000008:
2386 case 0x80000009:
2387 case 0x8000000A:
2388 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2389 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2390 i_setModified(IsModified_MachineData);
2391 mHWData.backup();
2392 /* Invalidate leaf. */
2393 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = UINT32_MAX;
2394 break;
2395
2396 default:
2397 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2398 }
2399 return S_OK;
2400}
2401
2402HRESULT Machine::removeAllCPUIDLeaves()
2403{
2404 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2405
2406 HRESULT rc = i_checkStateDependency(MutableStateDep);
2407 if (FAILED(rc)) return rc;
2408
2409 i_setModified(IsModified_MachineData);
2410 mHWData.backup();
2411
2412 /* Invalidate all standard leafs. */
2413 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++i)
2414 mHWData->mCpuIdStdLeafs[i].ulId = UINT32_MAX;
2415
2416 /* Invalidate all extended leafs. */
2417 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++i)
2418 mHWData->mCpuIdExtLeafs[i].ulId = UINT32_MAX;
2419
2420 return S_OK;
2421}
2422HRESULT Machine::getHWVirtExProperty(HWVirtExPropertyType_T aProperty, BOOL *aValue)
2423{
2424 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2425
2426 switch(aProperty)
2427 {
2428 case HWVirtExPropertyType_Enabled:
2429 *aValue = mHWData->mHWVirtExEnabled;
2430 break;
2431
2432 case HWVirtExPropertyType_VPID:
2433 *aValue = mHWData->mHWVirtExVPIDEnabled;
2434 break;
2435
2436 case HWVirtExPropertyType_NestedPaging:
2437 *aValue = mHWData->mHWVirtExNestedPagingEnabled;
2438 break;
2439
2440 case HWVirtExPropertyType_UnrestrictedExecution:
2441 *aValue = mHWData->mHWVirtExUXEnabled;
2442 break;
2443
2444 case HWVirtExPropertyType_LargePages:
2445 *aValue = mHWData->mHWVirtExLargePagesEnabled;
2446#if defined(DEBUG_bird) && defined(RT_OS_LINUX) /* This feature is deadly here */
2447 *aValue = FALSE;
2448#endif
2449 break;
2450
2451 case HWVirtExPropertyType_Force:
2452 *aValue = mHWData->mHWVirtExForceEnabled;
2453 break;
2454
2455 default:
2456 return E_INVALIDARG;
2457 }
2458 return S_OK;
2459}
2460
2461HRESULT Machine::setHWVirtExProperty(HWVirtExPropertyType_T aProperty, BOOL aValue)
2462{
2463 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2464
2465 HRESULT rc = i_checkStateDependency(MutableStateDep);
2466 if (FAILED(rc)) return rc;
2467
2468 switch(aProperty)
2469 {
2470 case HWVirtExPropertyType_Enabled:
2471 i_setModified(IsModified_MachineData);
2472 mHWData.backup();
2473 mHWData->mHWVirtExEnabled = !!aValue;
2474 break;
2475
2476 case HWVirtExPropertyType_VPID:
2477 i_setModified(IsModified_MachineData);
2478 mHWData.backup();
2479 mHWData->mHWVirtExVPIDEnabled = !!aValue;
2480 break;
2481
2482 case HWVirtExPropertyType_NestedPaging:
2483 i_setModified(IsModified_MachineData);
2484 mHWData.backup();
2485 mHWData->mHWVirtExNestedPagingEnabled = !!aValue;
2486 break;
2487
2488 case HWVirtExPropertyType_UnrestrictedExecution:
2489 i_setModified(IsModified_MachineData);
2490 mHWData.backup();
2491 mHWData->mHWVirtExUXEnabled = !!aValue;
2492 break;
2493
2494 case HWVirtExPropertyType_LargePages:
2495 i_setModified(IsModified_MachineData);
2496 mHWData.backup();
2497 mHWData->mHWVirtExLargePagesEnabled = !!aValue;
2498 break;
2499
2500 case HWVirtExPropertyType_Force:
2501 i_setModified(IsModified_MachineData);
2502 mHWData.backup();
2503 mHWData->mHWVirtExForceEnabled = !!aValue;
2504 break;
2505
2506 default:
2507 return E_INVALIDARG;
2508 }
2509
2510 return S_OK;
2511}
2512
2513HRESULT Machine::getSnapshotFolder(com::Utf8Str &aSnapshotFolder)
2514{
2515 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2516
2517 i_calculateFullPath(mUserData->s.strSnapshotFolder, aSnapshotFolder);
2518
2519 return S_OK;
2520}
2521
2522HRESULT Machine::setSnapshotFolder(const com::Utf8Str &aSnapshotFolder)
2523{
2524 /* @todo (r=dmik):
2525 * 1. Allow to change the name of the snapshot folder containing snapshots
2526 * 2. Rename the folder on disk instead of just changing the property
2527 * value (to be smart and not to leave garbage). Note that it cannot be
2528 * done here because the change may be rolled back. Thus, the right
2529 * place is #saveSettings().
2530 */
2531
2532 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2533
2534 HRESULT rc = i_checkStateDependency(MutableStateDep);
2535 if (FAILED(rc)) return rc;
2536
2537 if (!mData->mCurrentSnapshot.isNull())
2538 return setError(E_FAIL,
2539 tr("The snapshot folder of a machine with snapshots cannot be changed (please delete all snapshots first)"));
2540
2541 Utf8Str strSnapshotFolder(aSnapshotFolder); // keep original
2542
2543 if (strSnapshotFolder.isEmpty())
2544 strSnapshotFolder = "Snapshots";
2545 int vrc = i_calculateFullPath(strSnapshotFolder,
2546 strSnapshotFolder);
2547 if (RT_FAILURE(vrc))
2548 return setError(E_FAIL,
2549 tr("Invalid snapshot folder '%s' (%Rrc)"),
2550 strSnapshotFolder.c_str(), vrc);
2551
2552 i_setModified(IsModified_MachineData);
2553 mUserData.backup();
2554
2555 i_copyPathRelativeToMachine(strSnapshotFolder, mUserData->s.strSnapshotFolder);
2556
2557 return S_OK;
2558}
2559
2560HRESULT Machine::getMediumAttachments(std::vector<ComPtr<IMediumAttachment> > &aMediumAttachments)
2561{
2562 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2563
2564 aMediumAttachments.resize(mMediaData->mAttachments.size());
2565 size_t i = 0;
2566 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
2567 it != mMediaData->mAttachments.end(); ++it, ++i)
2568 aMediumAttachments[i] = *it;
2569
2570 return S_OK;
2571}
2572
2573HRESULT Machine::getVRDEServer(ComPtr<IVRDEServer> &aVRDEServer)
2574{
2575 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2576
2577 Assert(!!mVRDEServer);
2578
2579 aVRDEServer = mVRDEServer;
2580
2581 return S_OK;
2582}
2583
2584HRESULT Machine::getAudioAdapter(ComPtr<IAudioAdapter> &aAudioAdapter)
2585{
2586 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2587
2588 aAudioAdapter = mAudioAdapter;
2589
2590 return S_OK;
2591}
2592
2593HRESULT Machine::getUSBControllers(std::vector<ComPtr<IUSBController> > &aUSBControllers)
2594{
2595#ifdef VBOX_WITH_VUSB
2596 clearError();
2597 MultiResult rc(S_OK);
2598
2599# ifdef VBOX_WITH_USB
2600 rc = mParent->i_host()->i_checkUSBProxyService();
2601 if (FAILED(rc)) return rc;
2602# endif
2603
2604 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2605
2606 USBControllerList data = *mUSBControllers.data();
2607 aUSBControllers.resize(data.size());
2608 size_t i = 0;
2609 for (USBControllerList::iterator it = data.begin(); it != data.end(); ++i, ++it)
2610 aUSBControllers[i] = *it;
2611
2612 return S_OK;
2613#else
2614 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2615 * extended error info to indicate that USB is simply not available
2616 * (w/o treating it as a failure), for example, as in OSE */
2617 NOREF(aUSBControllers);
2618 ReturnComNotImplemented();
2619#endif /* VBOX_WITH_VUSB */
2620}
2621
2622HRESULT Machine::getUSBDeviceFilters(ComPtr<IUSBDeviceFilters> &aUSBDeviceFilters)
2623{
2624#ifdef VBOX_WITH_VUSB
2625 clearError();
2626 MultiResult rc(S_OK);
2627
2628# ifdef VBOX_WITH_USB
2629 rc = mParent->i_host()->i_checkUSBProxyService();
2630 if (FAILED(rc)) return rc;
2631# endif
2632
2633 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2634
2635 aUSBDeviceFilters = mUSBDeviceFilters;
2636 return rc;
2637#else
2638 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2639 * extended error info to indicate that USB is simply not available
2640 * (w/o treating it as a failure), for example, as in OSE */
2641 NOREF(aUSBDeviceFilters);
2642 ReturnComNotImplemented();
2643#endif /* VBOX_WITH_VUSB */
2644}
2645
2646HRESULT Machine::getSettingsFilePath(com::Utf8Str &aSettingsFilePath)
2647{
2648 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2649
2650 aSettingsFilePath = mData->m_strConfigFileFull;
2651
2652 return S_OK;
2653}
2654
2655HRESULT Machine::getSettingsModified(BOOL *aSettingsModified)
2656{
2657 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2658
2659 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2660 if (FAILED(rc)) return rc;
2661
2662 if (!mData->pMachineConfigFile->fileExists())
2663 // this is a new machine, and no config file exists yet:
2664 *aSettingsModified = TRUE;
2665 else
2666 *aSettingsModified = (mData->flModifications != 0);
2667
2668 return S_OK;
2669}
2670
2671HRESULT Machine::getSessionState(SessionState_T *aSessionState)
2672{
2673 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2674
2675 *aSessionState = mData->mSession.mState;
2676
2677 return S_OK;
2678}
2679
2680HRESULT Machine::getSessionName(com::Utf8Str &aSessionName)
2681{
2682 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2683
2684 aSessionName = mData->mSession.mName;
2685
2686 return S_OK;
2687}
2688
2689HRESULT Machine::getSessionPID(ULONG *aSessionPID)
2690{
2691 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2692
2693 *aSessionPID = mData->mSession.mPID;
2694
2695 return S_OK;
2696}
2697
2698HRESULT Machine::getState(MachineState_T *aState)
2699{
2700 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2701
2702 *aState = mData->mMachineState;
2703 Assert(mData->mMachineState != MachineState_Null);
2704
2705 return S_OK;
2706}
2707
2708HRESULT Machine::getLastStateChange(LONG64 *aLastStateChange)
2709{
2710 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2711
2712 *aLastStateChange = RTTimeSpecGetMilli(&mData->mLastStateChange);
2713
2714 return S_OK;
2715}
2716
2717HRESULT Machine::getStateFilePath(com::Utf8Str &aStateFilePath)
2718{
2719 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2720
2721 aStateFilePath = mSSData->strStateFilePath;
2722
2723 return S_OK;
2724}
2725
2726HRESULT Machine::getLogFolder(com::Utf8Str &aLogFolder)
2727{
2728 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2729
2730 i_getLogFolder(aLogFolder);
2731
2732 return S_OK;
2733}
2734
2735HRESULT Machine::getCurrentSnapshot(ComPtr<ISnapshot> &aCurrentSnapshot)
2736{
2737 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2738
2739 aCurrentSnapshot = mData->mCurrentSnapshot;
2740
2741 return S_OK;
2742}
2743
2744HRESULT Machine::getSnapshotCount(ULONG *aSnapshotCount)
2745{
2746 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2747
2748 *aSnapshotCount = mData->mFirstSnapshot.isNull()
2749 ? 0
2750 : mData->mFirstSnapshot->i_getAllChildrenCount() + 1;
2751
2752 return S_OK;
2753}
2754
2755HRESULT Machine::getCurrentStateModified(BOOL *aCurrentStateModified)
2756{
2757 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2758
2759 /* Note: for machines with no snapshots, we always return FALSE
2760 * (mData->mCurrentStateModified will be TRUE in this case, for historical
2761 * reasons :) */
2762
2763 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
2764 ? FALSE
2765 : mData->mCurrentStateModified;
2766
2767 return S_OK;
2768}
2769
2770HRESULT Machine::getSharedFolders(std::vector<ComPtr<ISharedFolder> > &aSharedFolders)
2771{
2772 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2773
2774 aSharedFolders.resize(mHWData->mSharedFolders.size());
2775 size_t i = 0;
2776 for (std::list<ComObjPtr<SharedFolder> >::iterator it = mHWData->mSharedFolders.begin();
2777 it != mHWData->mSharedFolders.end(); ++i, ++it)
2778 aSharedFolders[i] = *it;
2779
2780 return S_OK;
2781}
2782
2783HRESULT Machine::getClipboardMode(ClipboardMode_T *aClipboardMode)
2784{
2785 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2786
2787 *aClipboardMode = mHWData->mClipboardMode;
2788
2789 return S_OK;
2790}
2791
2792HRESULT Machine::setClipboardMode(ClipboardMode_T aClipboardMode)
2793{
2794 HRESULT rc = S_OK;
2795
2796 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2797
2798 alock.release();
2799 rc = i_onClipboardModeChange(aClipboardMode);
2800 alock.acquire();
2801 if (FAILED(rc)) return rc;
2802
2803 i_setModified(IsModified_MachineData);
2804 mHWData.backup();
2805 mHWData->mClipboardMode = aClipboardMode;
2806
2807 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
2808 if (Global::IsOnline(mData->mMachineState))
2809 i_saveSettings(NULL);
2810
2811 return S_OK;
2812}
2813
2814HRESULT Machine::getDnDMode(DnDMode_T *aDnDMode)
2815{
2816 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2817
2818 *aDnDMode = mHWData->mDnDMode;
2819
2820 return S_OK;
2821}
2822
2823HRESULT Machine::setDnDMode(DnDMode_T aDnDMode)
2824{
2825 HRESULT rc = S_OK;
2826
2827 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2828
2829 alock.release();
2830 rc = i_onDnDModeChange(aDnDMode);
2831
2832 alock.acquire();
2833 if (FAILED(rc)) return rc;
2834
2835 i_setModified(IsModified_MachineData);
2836 mHWData.backup();
2837 mHWData->mDnDMode = aDnDMode;
2838
2839 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
2840 if (Global::IsOnline(mData->mMachineState))
2841 i_saveSettings(NULL);
2842
2843 return S_OK;
2844}
2845
2846HRESULT Machine::getStorageControllers(std::vector<ComPtr<IStorageController> > &aStorageControllers)
2847{
2848 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2849 StorageControllerList data = *mStorageControllers.data();
2850 size_t i = 0;
2851 aStorageControllers.resize(data.size());
2852 for (StorageControllerList::iterator it = data.begin(); it != data.end(); ++it, ++i)
2853 aStorageControllers[i] = *it;
2854 return S_OK;
2855}
2856
2857HRESULT Machine::getTeleporterEnabled(BOOL *aEnabled)
2858{
2859 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2860
2861 *aEnabled = mUserData->s.fTeleporterEnabled;
2862
2863 return S_OK;
2864}
2865
2866HRESULT Machine::setTeleporterEnabled(BOOL aTeleporterEnabled)
2867{
2868 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2869
2870 /* Only allow it to be set to true when PoweredOff or Aborted.
2871 (Clearing it is always permitted.) */
2872 if ( aTeleporterEnabled
2873 && mData->mRegistered
2874 && ( !i_isSessionMachine()
2875 || ( mData->mMachineState != MachineState_PoweredOff
2876 && mData->mMachineState != MachineState_Teleported
2877 && mData->mMachineState != MachineState_Aborted
2878 )
2879 )
2880 )
2881 return setError(VBOX_E_INVALID_VM_STATE,
2882 tr("The machine is not powered off (state is %s)"),
2883 Global::stringifyMachineState(mData->mMachineState));
2884
2885 i_setModified(IsModified_MachineData);
2886 mUserData.backup();
2887 mUserData->s.fTeleporterEnabled = !! aTeleporterEnabled;
2888
2889 return S_OK;
2890}
2891
2892HRESULT Machine::getTeleporterPort(ULONG *aTeleporterPort)
2893{
2894 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2895
2896 *aTeleporterPort = (ULONG)mUserData->s.uTeleporterPort;
2897
2898 return S_OK;
2899}
2900
2901HRESULT Machine::setTeleporterPort(ULONG aTeleporterPort)
2902{
2903 if (aTeleporterPort >= _64K)
2904 return setError(E_INVALIDARG, tr("Invalid port number %d"), aTeleporterPort);
2905
2906 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2907
2908 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
2909 if (FAILED(rc)) return rc;
2910
2911 i_setModified(IsModified_MachineData);
2912 mUserData.backup();
2913 mUserData->s.uTeleporterPort = (uint32_t)aTeleporterPort;
2914
2915 return S_OK;
2916}
2917
2918HRESULT Machine::getTeleporterAddress(com::Utf8Str &aTeleporterAddress)
2919{
2920 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2921
2922 aTeleporterAddress = mUserData->s.strTeleporterAddress;
2923
2924 return S_OK;
2925}
2926
2927HRESULT Machine::setTeleporterAddress(const com::Utf8Str &aTeleporterAddress)
2928{
2929 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2930
2931 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
2932 if (FAILED(rc)) return rc;
2933
2934 i_setModified(IsModified_MachineData);
2935 mUserData.backup();
2936 mUserData->s.strTeleporterAddress = aTeleporterAddress;
2937
2938 return S_OK;
2939}
2940
2941HRESULT Machine::getTeleporterPassword(com::Utf8Str &aTeleporterPassword)
2942{
2943 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2944 aTeleporterPassword = mUserData->s.strTeleporterPassword;
2945
2946 return S_OK;
2947}
2948
2949HRESULT Machine::setTeleporterPassword(const com::Utf8Str &aTeleporterPassword)
2950{
2951 /*
2952 * Hash the password first.
2953 */
2954 com::Utf8Str aT = aTeleporterPassword;
2955
2956 if (!aT.isEmpty())
2957 {
2958 if (VBoxIsPasswordHashed(&aT))
2959 return setError(E_INVALIDARG, tr("Cannot set an already hashed password, only plain text password please"));
2960 VBoxHashPassword(&aT);
2961 }
2962
2963 /*
2964 * Do the update.
2965 */
2966 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2967 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
2968 if (SUCCEEDED(hrc))
2969 {
2970 i_setModified(IsModified_MachineData);
2971 mUserData.backup();
2972 mUserData->s.strTeleporterPassword = aT;
2973 }
2974
2975 return hrc;
2976}
2977
2978HRESULT Machine::getFaultToleranceState(FaultToleranceState_T *aFaultToleranceState)
2979{
2980 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2981
2982 *aFaultToleranceState = mUserData->s.enmFaultToleranceState;
2983 return S_OK;
2984}
2985
2986HRESULT Machine::setFaultToleranceState(FaultToleranceState_T aFaultToleranceState)
2987{
2988 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2989
2990 /* @todo deal with running state change. */
2991 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2992 if (FAILED(rc)) return rc;
2993
2994 i_setModified(IsModified_MachineData);
2995 mUserData.backup();
2996 mUserData->s.enmFaultToleranceState = aFaultToleranceState;
2997 return S_OK;
2998}
2999
3000HRESULT Machine::getFaultToleranceAddress(com::Utf8Str &aFaultToleranceAddress)
3001{
3002 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3003
3004 aFaultToleranceAddress = mUserData->s.strFaultToleranceAddress;
3005 return S_OK;
3006}
3007
3008HRESULT Machine::setFaultToleranceAddress(const com::Utf8Str &aFaultToleranceAddress)
3009{
3010 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3011
3012 /* @todo deal with running state change. */
3013 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3014 if (FAILED(rc)) return rc;
3015
3016 i_setModified(IsModified_MachineData);
3017 mUserData.backup();
3018 mUserData->s.strFaultToleranceAddress = aFaultToleranceAddress;
3019 return S_OK;
3020}
3021
3022HRESULT Machine::getFaultTolerancePort(ULONG *aFaultTolerancePort)
3023{
3024 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3025
3026 *aFaultTolerancePort = mUserData->s.uFaultTolerancePort;
3027 return S_OK;
3028}
3029
3030HRESULT Machine::setFaultTolerancePort(ULONG aFaultTolerancePort)
3031{
3032 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3033
3034 /* @todo deal with running state change. */
3035 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3036 if (FAILED(rc)) return rc;
3037
3038 i_setModified(IsModified_MachineData);
3039 mUserData.backup();
3040 mUserData->s.uFaultTolerancePort = aFaultTolerancePort;
3041 return S_OK;
3042}
3043
3044HRESULT Machine::getFaultTolerancePassword(com::Utf8Str &aFaultTolerancePassword)
3045{
3046 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3047
3048 aFaultTolerancePassword = mUserData->s.strFaultTolerancePassword;
3049
3050 return S_OK;
3051}
3052
3053HRESULT Machine::setFaultTolerancePassword(const com::Utf8Str &aFaultTolerancePassword)
3054{
3055 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3056
3057 /* @todo deal with running state change. */
3058 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3059 if (FAILED(rc)) return rc;
3060
3061 i_setModified(IsModified_MachineData);
3062 mUserData.backup();
3063 mUserData->s.strFaultTolerancePassword = aFaultTolerancePassword;
3064
3065 return S_OK;
3066}
3067
3068HRESULT Machine::getFaultToleranceSyncInterval(ULONG *aFaultToleranceSyncInterval)
3069{
3070 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3071
3072 *aFaultToleranceSyncInterval = mUserData->s.uFaultToleranceInterval;
3073 return S_OK;
3074}
3075
3076HRESULT Machine::setFaultToleranceSyncInterval(ULONG aFaultToleranceSyncInterval)
3077{
3078 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3079
3080 /* @todo deal with running state change. */
3081 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
3082 if (FAILED(rc)) return rc;
3083
3084 i_setModified(IsModified_MachineData);
3085 mUserData.backup();
3086 mUserData->s.uFaultToleranceInterval = aFaultToleranceSyncInterval;
3087 return S_OK;
3088}
3089
3090HRESULT Machine::getRTCUseUTC(BOOL *aRTCUseUTC)
3091{
3092 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3093
3094 *aRTCUseUTC = mUserData->s.fRTCUseUTC;
3095
3096 return S_OK;
3097}
3098
3099HRESULT Machine::setRTCUseUTC(BOOL aRTCUseUTC)
3100{
3101 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3102
3103 /* Only allow it to be set to true when PoweredOff or Aborted.
3104 (Clearing it is always permitted.) */
3105 if ( aRTCUseUTC
3106 && mData->mRegistered
3107 && ( !i_isSessionMachine()
3108 || ( mData->mMachineState != MachineState_PoweredOff
3109 && mData->mMachineState != MachineState_Teleported
3110 && mData->mMachineState != MachineState_Aborted
3111 )
3112 )
3113 )
3114 return setError(VBOX_E_INVALID_VM_STATE,
3115 tr("The machine is not powered off (state is %s)"),
3116 Global::stringifyMachineState(mData->mMachineState));
3117
3118 i_setModified(IsModified_MachineData);
3119 mUserData.backup();
3120 mUserData->s.fRTCUseUTC = !!aRTCUseUTC;
3121
3122 return S_OK;
3123}
3124
3125HRESULT Machine::getIOCacheEnabled(BOOL *aIOCacheEnabled)
3126{
3127 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3128
3129 *aIOCacheEnabled = mHWData->mIOCacheEnabled;
3130
3131 return S_OK;
3132}
3133
3134HRESULT Machine::setIOCacheEnabled(BOOL aIOCacheEnabled)
3135{
3136 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3137
3138 HRESULT rc = i_checkStateDependency(MutableStateDep);
3139 if (FAILED(rc)) return rc;
3140
3141 i_setModified(IsModified_MachineData);
3142 mHWData.backup();
3143 mHWData->mIOCacheEnabled = aIOCacheEnabled;
3144
3145 return S_OK;
3146}
3147
3148HRESULT Machine::getIOCacheSize(ULONG *aIOCacheSize)
3149{
3150 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3151
3152 *aIOCacheSize = mHWData->mIOCacheSize;
3153
3154 return S_OK;
3155}
3156
3157HRESULT Machine::setIOCacheSize(ULONG aIOCacheSize)
3158{
3159 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3160
3161 HRESULT rc = i_checkStateDependency(MutableStateDep);
3162 if (FAILED(rc)) return rc;
3163
3164 i_setModified(IsModified_MachineData);
3165 mHWData.backup();
3166 mHWData->mIOCacheSize = aIOCacheSize;
3167
3168 return S_OK;
3169}
3170
3171
3172/**
3173 * @note Locks objects!
3174 */
3175HRESULT Machine::lockMachine(const ComPtr<ISession> &aSession,
3176 LockType_T aLockType)
3177{
3178 /* check the session state */
3179 SessionState_T state;
3180 HRESULT rc = aSession->COMGETTER(State)(&state);
3181 if (FAILED(rc)) return rc;
3182
3183 if (state != SessionState_Unlocked)
3184 return setError(VBOX_E_INVALID_OBJECT_STATE,
3185 tr("The given session is busy"));
3186
3187 // get the client's IInternalSessionControl interface
3188 ComPtr<IInternalSessionControl> pSessionControl = aSession;
3189 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
3190 E_INVALIDARG);
3191
3192 // session name (only used in some code paths)
3193 Utf8Str strSessionName;
3194
3195 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3196
3197 if (!mData->mRegistered)
3198 return setError(E_UNEXPECTED,
3199 tr("The machine '%s' is not registered"),
3200 mUserData->s.strName.c_str());
3201
3202 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3203
3204 SessionState_T oldState = mData->mSession.mState;
3205 /* Hack: in case the session is closing and there is a progress object
3206 * which allows waiting for the session to be closed, take the opportunity
3207 * and do a limited wait (max. 1 second). This helps a lot when the system
3208 * is busy and thus session closing can take a little while. */
3209 if ( mData->mSession.mState == SessionState_Unlocking
3210 && mData->mSession.mProgress)
3211 {
3212 alock.release();
3213 mData->mSession.mProgress->WaitForCompletion(1000);
3214 alock.acquire();
3215 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3216 }
3217
3218 // try again now
3219 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already
3220 // (i.e. session machine exists)
3221 && (aLockType == LockType_Shared) // caller wants a shared link to the
3222 // existing session that holds the write lock:
3223 )
3224 {
3225 // OK, share the session... we are now dealing with three processes:
3226 // 1) VBoxSVC (where this code runs);
3227 // 2) process C: the caller's client process (who wants a shared session);
3228 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
3229
3230 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
3231 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
3232 ComAssertRet(!pSessionW.isNull(), E_FAIL);
3233 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
3234 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
3235
3236 /*
3237 * Release the lock before calling the client process. It's safe here
3238 * since the only thing to do after we get the lock again is to add
3239 * the remote control to the list (which doesn't directly influence
3240 * anything).
3241 */
3242 alock.release();
3243
3244 // get the console of the session holding the write lock (this is a remote call)
3245 ComPtr<IConsole> pConsoleW;
3246 if (mData->mSession.mLockType == LockType_VM)
3247 {
3248 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
3249 rc = pSessionW->COMGETTER(RemoteConsole)(pConsoleW.asOutParam());
3250 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
3251 if (FAILED(rc))
3252 // the failure may occur w/o any error info (from RPC), so provide one
3253 return setError(VBOX_E_VM_ERROR,
3254 tr("Failed to get a console object from the direct session (%Rhrc)"), rc);
3255 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
3256 }
3257
3258 // share the session machine and W's console with the caller's session
3259 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3260 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
3261 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3262
3263 if (FAILED(rc))
3264 // the failure may occur w/o any error info (from RPC), so provide one
3265 return setError(VBOX_E_VM_ERROR,
3266 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
3267 alock.acquire();
3268
3269 // need to revalidate the state after acquiring the lock again
3270 if (mData->mSession.mState != SessionState_Locked)
3271 {
3272 pSessionControl->Uninitialize();
3273 return setError(VBOX_E_INVALID_SESSION_STATE,
3274 tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
3275 mUserData->s.strName.c_str());
3276 }
3277
3278 // add the caller's session to the list
3279 mData->mSession.mRemoteControls.push_back(pSessionControl);
3280 }
3281 else if ( mData->mSession.mState == SessionState_Locked
3282 || mData->mSession.mState == SessionState_Unlocking
3283 )
3284 {
3285 // sharing not permitted, or machine still unlocking:
3286 return setError(VBOX_E_INVALID_OBJECT_STATE,
3287 tr("The machine '%s' is already locked for a session (or being unlocked)"),
3288 mUserData->s.strName.c_str());
3289 }
3290 else
3291 {
3292 // machine is not locked: then write-lock the machine (create the session machine)
3293
3294 // must not be busy
3295 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
3296
3297 // get the caller's session PID
3298 RTPROCESS pid = NIL_RTPROCESS;
3299 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
3300 pSessionControl->COMGETTER(PID)((ULONG*)&pid);
3301 Assert(pid != NIL_RTPROCESS);
3302
3303 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
3304
3305 if (fLaunchingVMProcess)
3306 {
3307 if (mData->mSession.mPID == NIL_RTPROCESS)
3308 {
3309 // two or more clients racing for a lock, the one which set the
3310 // session state to Spawning will win, the others will get an
3311 // error as we can't decide here if waiting a little would help
3312 // (only for shared locks this would avoid an error)
3313 return setError(VBOX_E_INVALID_OBJECT_STATE,
3314 tr("The machine '%s' already has a lock request pending"),
3315 mUserData->s.strName.c_str());
3316 }
3317
3318 // this machine is awaiting for a spawning session to be opened:
3319 // then the calling process must be the one that got started by
3320 // LaunchVMProcess()
3321
3322 LogFlowThisFunc(("mSession.mPID=%d(0x%x)\n", mData->mSession.mPID, mData->mSession.mPID));
3323 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3324
3325#if defined(VBOX_WITH_HARDENING) && defined(RT_OS_WINDOWS)
3326 /* Hardened windows builds spawns three processes when a VM is
3327 launched, the 3rd one is the one that will end up here. */
3328 RTPROCESS ppid;
3329 int rc = RTProcQueryParent(pid, &ppid);
3330 if (RT_SUCCESS(rc))
3331 rc = RTProcQueryParent(ppid, &ppid);
3332 if ( (RT_SUCCESS(rc) && mData->mSession.mPID == ppid)
3333 || rc == VERR_ACCESS_DENIED)
3334 {
3335 LogFlowThisFunc(("mSession.mPID => %d(%#x) - windows hardening stub\n", mData->mSession.mPID, pid));
3336 mData->mSession.mPID = pid;
3337 }
3338#endif
3339
3340 if (mData->mSession.mPID != pid)
3341 return setError(E_ACCESSDENIED,
3342 tr("An unexpected process (PID=0x%08X) has tried to lock the "
3343 "machine '%s', while only the process started by LaunchVMProcess (PID=0x%08X) is allowed"),
3344 pid, mUserData->s.strName.c_str(), mData->mSession.mPID);
3345 }
3346
3347 // create the mutable SessionMachine from the current machine
3348 ComObjPtr<SessionMachine> sessionMachine;
3349 sessionMachine.createObject();
3350 rc = sessionMachine->init(this);
3351 AssertComRC(rc);
3352
3353 /* NOTE: doing return from this function after this point but
3354 * before the end is forbidden since it may call SessionMachine::uninit()
3355 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3356 * lock while still holding the Machine lock in alock so that a deadlock
3357 * is possible due to the wrong lock order. */
3358
3359 if (SUCCEEDED(rc))
3360 {
3361 /*
3362 * Set the session state to Spawning to protect against subsequent
3363 * attempts to open a session and to unregister the machine after
3364 * we release the lock.
3365 */
3366 SessionState_T origState = mData->mSession.mState;
3367 mData->mSession.mState = SessionState_Spawning;
3368
3369#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
3370 /* Get the client token ID to be passed to the client process */
3371 Utf8Str strTokenId;
3372 sessionMachine->i_getTokenId(strTokenId);
3373 Assert(!strTokenId.isEmpty());
3374#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3375 /* Get the client token to be passed to the client process */
3376 ComPtr<IToken> pToken(sessionMachine->i_getToken());
3377 /* The token is now "owned" by pToken, fix refcount */
3378 if (!pToken.isNull())
3379 pToken->Release();
3380#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3381
3382 /*
3383 * Release the lock before calling the client process -- it will call
3384 * Machine/SessionMachine methods. Releasing the lock here is quite safe
3385 * because the state is Spawning, so that LaunchVMProcess() and
3386 * LockMachine() calls will fail. This method, called before we
3387 * acquire the lock again, will fail because of the wrong PID.
3388 *
3389 * Note that mData->mSession.mRemoteControls accessed outside
3390 * the lock may not be modified when state is Spawning, so it's safe.
3391 */
3392 alock.release();
3393
3394 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3395#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
3396 rc = pSessionControl->AssignMachine(sessionMachine, aLockType, Bstr(strTokenId).raw());
3397#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3398 rc = pSessionControl->AssignMachine(sessionMachine, aLockType, pToken);
3399 /* Now the token is owned by the client process. */
3400 pToken.setNull();
3401#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
3402 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3403
3404 /* The failure may occur w/o any error info (from RPC), so provide one */
3405 if (FAILED(rc))
3406 setError(VBOX_E_VM_ERROR,
3407 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
3408
3409 // get session name, either to remember or to compare against
3410 // the already known session name.
3411 {
3412 Bstr bstrSessionName;
3413 HRESULT rc2 = aSession->COMGETTER(Name)(bstrSessionName.asOutParam());
3414 if (SUCCEEDED(rc2))
3415 strSessionName = bstrSessionName;
3416 }
3417
3418 if ( SUCCEEDED(rc)
3419 && fLaunchingVMProcess
3420 )
3421 {
3422 /* complete the remote session initialization */
3423
3424 /* get the console from the direct session */
3425 ComPtr<IConsole> console;
3426 rc = pSessionControl->COMGETTER(RemoteConsole)(console.asOutParam());
3427 ComAssertComRC(rc);
3428
3429 if (SUCCEEDED(rc) && !console)
3430 {
3431 ComAssert(!!console);
3432 rc = E_FAIL;
3433 }
3434
3435 /* assign machine & console to the remote session */
3436 if (SUCCEEDED(rc))
3437 {
3438 /*
3439 * after LaunchVMProcess(), the first and the only
3440 * entry in remoteControls is that remote session
3441 */
3442 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3443 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
3444 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3445
3446 /* The failure may occur w/o any error info (from RPC), so provide one */
3447 if (FAILED(rc))
3448 setError(VBOX_E_VM_ERROR,
3449 tr("Failed to assign the machine to the remote session (%Rhrc)"), rc);
3450 }
3451
3452 if (FAILED(rc))
3453 pSessionControl->Uninitialize();
3454 }
3455
3456 /* acquire the lock again */
3457 alock.acquire();
3458
3459 /* Restore the session state */
3460 mData->mSession.mState = origState;
3461 }
3462
3463 // finalize spawning anyway (this is why we don't return on errors above)
3464 if (fLaunchingVMProcess)
3465 {
3466 Assert(mData->mSession.mName == strSessionName);
3467 /* Note that the progress object is finalized later */
3468 /** @todo Consider checking mData->mSession.mProgress for cancellation
3469 * around here. */
3470
3471 /* We don't reset mSession.mPID here because it is necessary for
3472 * SessionMachine::uninit() to reap the child process later. */
3473
3474 if (FAILED(rc))
3475 {
3476 /* Close the remote session, remove the remote control from the list
3477 * and reset session state to Closed (@note keep the code in sync
3478 * with the relevant part in checkForSpawnFailure()). */
3479
3480 Assert(mData->mSession.mRemoteControls.size() == 1);
3481 if (mData->mSession.mRemoteControls.size() == 1)
3482 {
3483 ErrorInfoKeeper eik;
3484 mData->mSession.mRemoteControls.front()->Uninitialize();
3485 }
3486
3487 mData->mSession.mRemoteControls.clear();
3488 mData->mSession.mState = SessionState_Unlocked;
3489 }
3490 }
3491 else
3492 {
3493 /* memorize PID of the directly opened session */
3494 if (SUCCEEDED(rc))
3495 mData->mSession.mPID = pid;
3496 }
3497
3498 if (SUCCEEDED(rc))
3499 {
3500 mData->mSession.mLockType = aLockType;
3501 /* memorize the direct session control and cache IUnknown for it */
3502 mData->mSession.mDirectControl = pSessionControl;
3503 mData->mSession.mState = SessionState_Locked;
3504 if (!fLaunchingVMProcess)
3505 mData->mSession.mName = strSessionName;
3506 /* associate the SessionMachine with this Machine */
3507 mData->mSession.mMachine = sessionMachine;
3508
3509 /* request an IUnknown pointer early from the remote party for later
3510 * identity checks (it will be internally cached within mDirectControl
3511 * at least on XPCOM) */
3512 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3513 NOREF(unk);
3514 }
3515
3516 /* Release the lock since SessionMachine::uninit() locks VirtualBox which
3517 * would break the lock order */
3518 alock.release();
3519
3520 /* uninitialize the created session machine on failure */
3521 if (FAILED(rc))
3522 sessionMachine->uninit();
3523 }
3524
3525 if (SUCCEEDED(rc))
3526 {
3527 /*
3528 * tell the client watcher thread to update the set of
3529 * machines that have open sessions
3530 */
3531 mParent->i_updateClientWatcher();
3532
3533 if (oldState != SessionState_Locked)
3534 /* fire an event */
3535 mParent->i_onSessionStateChange(i_getId(), SessionState_Locked);
3536 }
3537
3538 return rc;
3539}
3540
3541/**
3542 * @note Locks objects!
3543 */
3544HRESULT Machine::launchVMProcess(const ComPtr<ISession> &aSession,
3545 const com::Utf8Str &aName,
3546 const com::Utf8Str &aEnvironment,
3547 ComPtr<IProgress> &aProgress)
3548{
3549 Utf8Str strFrontend(aName);
3550 /* "emergencystop" doesn't need the session, so skip the checks/interface
3551 * retrieval. This code doesn't quite fit in here, but introducing a
3552 * special API method would be even more effort, and would require explicit
3553 * support by every API client. It's better to hide the feature a bit. */
3554 if (strFrontend != "emergencystop")
3555 CheckComArgNotNull(aSession);
3556
3557 HRESULT rc = S_OK;
3558 if (strFrontend.isEmpty())
3559 {
3560 Bstr bstrFrontend;
3561 rc = COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3562 if (FAILED(rc))
3563 return rc;
3564 strFrontend = bstrFrontend;
3565 if (strFrontend.isEmpty())
3566 {
3567 ComPtr<ISystemProperties> systemProperties;
3568 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
3569 if (FAILED(rc))
3570 return rc;
3571 rc = systemProperties->COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3572 if (FAILED(rc))
3573 return rc;
3574 strFrontend = bstrFrontend;
3575 }
3576 /* paranoia - emergencystop is not a valid default */
3577 if (strFrontend == "emergencystop")
3578 strFrontend = Utf8Str::Empty;
3579 }
3580 /* default frontend: Qt GUI */
3581 if (strFrontend.isEmpty())
3582 strFrontend = "GUI/Qt";
3583
3584 if (strFrontend != "emergencystop")
3585 {
3586 /* check the session state */
3587 SessionState_T state;
3588 rc = aSession->COMGETTER(State)(&state);
3589 if (FAILED(rc))
3590 return rc;
3591
3592 if (state != SessionState_Unlocked)
3593 return setError(VBOX_E_INVALID_OBJECT_STATE,
3594 tr("The given session is busy"));
3595
3596 /* get the IInternalSessionControl interface */
3597 ComPtr<IInternalSessionControl> control(aSession);
3598 ComAssertMsgRet(!control.isNull(),
3599 ("No IInternalSessionControl interface"),
3600 E_INVALIDARG);
3601
3602 /* get the teleporter enable state for the progress object init. */
3603 BOOL fTeleporterEnabled;
3604 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3605 if (FAILED(rc))
3606 return rc;
3607
3608 /* create a progress object */
3609 ComObjPtr<ProgressProxy> progress;
3610 progress.createObject();
3611 rc = progress->init(mParent,
3612 static_cast<IMachine*>(this),
3613 Bstr(tr("Starting VM")).raw(),
3614 TRUE /* aCancelable */,
3615 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3616 BstrFmt(tr("Creating process for virtual machine \"%s\" (%s)"),
3617 mUserData->s.strName.c_str(), strFrontend.c_str()).raw(),
3618 2 /* uFirstOperationWeight */,
3619 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3620
3621 if (SUCCEEDED(rc))
3622 {
3623 rc = i_launchVMProcess(control, strFrontend, aEnvironment, progress);
3624 if (SUCCEEDED(rc))
3625 {
3626 aProgress = progress;
3627
3628 /* signal the client watcher thread */
3629 mParent->i_updateClientWatcher();
3630
3631 /* fire an event */
3632 mParent->i_onSessionStateChange(i_getId(), SessionState_Spawning);
3633 }
3634 }
3635 }
3636 else
3637 {
3638 /* no progress object - either instant success or failure */
3639 aProgress = NULL;
3640
3641 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3642
3643 if (mData->mSession.mState != SessionState_Locked)
3644 return setError(VBOX_E_INVALID_OBJECT_STATE,
3645 tr("The machine '%s' is not locked by a session"),
3646 mUserData->s.strName.c_str());
3647
3648 /* must have a VM process associated - do not kill normal API clients
3649 * with an open session */
3650 if (!Global::IsOnline(mData->mMachineState))
3651 return setError(VBOX_E_INVALID_OBJECT_STATE,
3652 tr("The machine '%s' does not have a VM process"),
3653 mUserData->s.strName.c_str());
3654
3655 /* forcibly terminate the VM process */
3656 if (mData->mSession.mPID != NIL_RTPROCESS)
3657 RTProcTerminate(mData->mSession.mPID);
3658
3659 /* signal the client watcher thread, as most likely the client has
3660 * been terminated */
3661 mParent->i_updateClientWatcher();
3662 }
3663
3664 return rc;
3665}
3666
3667HRESULT Machine::setBootOrder(ULONG aPosition, DeviceType_T aDevice)
3668{
3669 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3670 return setError(E_INVALIDARG,
3671 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3672 aPosition, SchemaDefs::MaxBootPosition);
3673
3674 if (aDevice == DeviceType_USB)
3675 return setError(E_NOTIMPL,
3676 tr("Booting from USB device is currently not supported"));
3677
3678 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3679
3680 HRESULT rc = i_checkStateDependency(MutableStateDep);
3681 if (FAILED(rc)) return rc;
3682
3683 i_setModified(IsModified_MachineData);
3684 mHWData.backup();
3685 mHWData->mBootOrder[aPosition - 1] = aDevice;
3686
3687 return S_OK;
3688}
3689
3690HRESULT Machine::getBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3691{
3692 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3693 return setError(E_INVALIDARG,
3694 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3695 aPosition, SchemaDefs::MaxBootPosition);
3696
3697 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3698
3699 *aDevice = mHWData->mBootOrder[aPosition - 1];
3700
3701 return S_OK;
3702}
3703
3704HRESULT Machine::attachDevice(const com::Utf8Str &aName,
3705 LONG aControllerPort,
3706 LONG aDevice,
3707 DeviceType_T aType,
3708 const ComPtr<IMedium> &aMedium)
3709{
3710 IMedium *aM = aMedium;
3711 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
3712 aName.c_str(), aControllerPort, aDevice, aType, aM));
3713
3714 // request the host lock first, since might be calling Host methods for getting host drives;
3715 // next, protect the media tree all the while we're in here, as well as our member variables
3716 AutoMultiWriteLock2 alock(mParent->i_host(), this COMMA_LOCKVAL_SRC_POS);
3717 AutoWriteLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3718
3719 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
3720 if (FAILED(rc)) return rc;
3721
3722 /// @todo NEWMEDIA implicit machine registration
3723 if (!mData->mRegistered)
3724 return setError(VBOX_E_INVALID_OBJECT_STATE,
3725 tr("Cannot attach storage devices to an unregistered machine"));
3726
3727 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3728
3729 /* Check for an existing controller. */
3730 ComObjPtr<StorageController> ctl;
3731 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
3732 if (FAILED(rc)) return rc;
3733
3734 StorageControllerType_T ctrlType;
3735 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
3736 if (FAILED(rc))
3737 return setError(E_FAIL,
3738 tr("Could not get type of controller '%s'"),
3739 aName.c_str());
3740
3741 bool fSilent = false;
3742 Utf8Str strReconfig;
3743
3744 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
3745 strReconfig = i_getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
3746 if ( mData->mMachineState == MachineState_Paused
3747 && strReconfig == "1")
3748 fSilent = true;
3749
3750 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
3751 bool fHotplug = false;
3752 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
3753 fHotplug = true;
3754
3755 if (fHotplug && !i_isControllerHotplugCapable(ctrlType))
3756 return setError(VBOX_E_INVALID_VM_STATE,
3757 tr("Controller '%s' does not support hotplugging"),
3758 aName.c_str());
3759
3760 // check that the port and device are not out of range
3761 rc = ctl->i_checkPortAndDeviceValid(aControllerPort, aDevice);
3762 if (FAILED(rc)) return rc;
3763
3764 /* check if the device slot is already busy */
3765 MediumAttachment *pAttachTemp;
3766 if ((pAttachTemp = i_findAttachment(mMediaData->mAttachments,
3767 Bstr(aName).raw(),
3768 aControllerPort,
3769 aDevice)))
3770 {
3771 Medium *pMedium = pAttachTemp->i_getMedium();
3772 if (pMedium)
3773 {
3774 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3775 return setError(VBOX_E_OBJECT_IN_USE,
3776 tr("Medium '%s' is already attached to port %d, device %d of controller '%s' of this virtual machine"),
3777 pMedium->i_getLocationFull().c_str(),
3778 aControllerPort,
3779 aDevice,
3780 aName.c_str());
3781 }
3782 else
3783 return setError(VBOX_E_OBJECT_IN_USE,
3784 tr("Device is already attached to port %d, device %d of controller '%s' of this virtual machine"),
3785 aControllerPort, aDevice, aName.c_str());
3786 }
3787
3788 ComObjPtr<Medium> medium = static_cast<Medium*>(aM);
3789 if (aMedium && medium.isNull())
3790 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3791
3792 AutoCaller mediumCaller(medium);
3793 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3794
3795 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3796
3797 if ( (pAttachTemp = i_findAttachment(mMediaData->mAttachments, medium))
3798 && !medium.isNull()
3799 )
3800 return setError(VBOX_E_OBJECT_IN_USE,
3801 tr("Medium '%s' is already attached to this virtual machine"),
3802 medium->i_getLocationFull().c_str());
3803
3804 if (!medium.isNull())
3805 {
3806 MediumType_T mtype = medium->i_getType();
3807 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3808 // For DVDs it's not written to the config file, so needs no global config
3809 // version bump. For floppies it's a new attribute "type", which is ignored
3810 // by older VirtualBox version, so needs no global config version bump either.
3811 // For hard disks this type is not accepted.
3812 if (mtype == MediumType_MultiAttach)
3813 {
3814 // This type is new with VirtualBox 4.0 and therefore requires settings
3815 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3816 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3817 // two reasons: The medium type is a property of the media registry tree, which
3818 // can reside in the global config file (for pre-4.0 media); we would therefore
3819 // possibly need to bump the global config version. We don't want to do that though
3820 // because that might make downgrading to pre-4.0 impossible.
3821 // As a result, we can only use these two new types if the medium is NOT in the
3822 // global registry:
3823 const Guid &uuidGlobalRegistry = mParent->i_getGlobalRegistryId();
3824 if ( medium->i_isInRegistry(uuidGlobalRegistry)
3825 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3826 )
3827 return setError(VBOX_E_INVALID_OBJECT_STATE,
3828 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3829 "to machines that were created with VirtualBox 4.0 or later"),
3830 medium->i_getLocationFull().c_str());
3831 }
3832 }
3833
3834 bool fIndirect = false;
3835 if (!medium.isNull())
3836 fIndirect = medium->i_isReadOnly();
3837 bool associate = true;
3838
3839 do
3840 {
3841 if ( aType == DeviceType_HardDisk
3842 && mMediaData.isBackedUp())
3843 {
3844 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3845
3846 /* check if the medium was attached to the VM before we started
3847 * changing attachments in which case the attachment just needs to
3848 * be restored */
3849 if ((pAttachTemp = i_findAttachment(oldAtts, medium)))
3850 {
3851 AssertReturn(!fIndirect, E_FAIL);
3852
3853 /* see if it's the same bus/channel/device */
3854 if (pAttachTemp->i_matches(Bstr(aName).raw(), aControllerPort, aDevice))
3855 {
3856 /* the simplest case: restore the whole attachment
3857 * and return, nothing else to do */
3858 mMediaData->mAttachments.push_back(pAttachTemp);
3859
3860 /* Reattach the medium to the VM. */
3861 if (fHotplug || fSilent)
3862 {
3863 mediumLock.release();
3864 treeLock.release();
3865 alock.release();
3866
3867 MediumLockList *pMediumLockList(new MediumLockList());
3868
3869 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
3870 true /* fMediumLockWrite */,
3871 false /* fMediumLockWriteAll */,
3872 NULL,
3873 *pMediumLockList);
3874 alock.acquire();
3875 if (FAILED(rc))
3876 delete pMediumLockList;
3877 else
3878 {
3879 mData->mSession.mLockedMedia.Unlock();
3880 alock.release();
3881 rc = mData->mSession.mLockedMedia.Insert(pAttachTemp, pMediumLockList);
3882 mData->mSession.mLockedMedia.Lock();
3883 alock.acquire();
3884 }
3885 alock.release();
3886
3887 if (SUCCEEDED(rc))
3888 {
3889 rc = i_onStorageDeviceChange(pAttachTemp, FALSE /* aRemove */, fSilent);
3890 /* Remove lock list in case of error. */
3891 if (FAILED(rc))
3892 {
3893 mData->mSession.mLockedMedia.Unlock();
3894 mData->mSession.mLockedMedia.Remove(pAttachTemp);
3895 mData->mSession.mLockedMedia.Lock();
3896 }
3897 }
3898 }
3899
3900 return S_OK;
3901 }
3902
3903 /* bus/channel/device differ; we need a new attachment object,
3904 * but don't try to associate it again */
3905 associate = false;
3906 break;
3907 }
3908 }
3909
3910 /* go further only if the attachment is to be indirect */
3911 if (!fIndirect)
3912 break;
3913
3914 /* perform the so called smart attachment logic for indirect
3915 * attachments. Note that smart attachment is only applicable to base
3916 * hard disks. */
3917
3918 if (medium->i_getParent().isNull())
3919 {
3920 /* first, investigate the backup copy of the current hard disk
3921 * attachments to make it possible to re-attach existing diffs to
3922 * another device slot w/o losing their contents */
3923 if (mMediaData.isBackedUp())
3924 {
3925 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3926
3927 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
3928 uint32_t foundLevel = 0;
3929
3930 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin(); it != oldAtts.end(); ++it)
3931 {
3932 uint32_t level = 0;
3933 MediumAttachment *pAttach = *it;
3934 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
3935 Assert(!pMedium.isNull() || pAttach->i_getType() != DeviceType_HardDisk);
3936 if (pMedium.isNull())
3937 continue;
3938
3939 if (pMedium->i_getBase(&level) == medium)
3940 {
3941 /* skip the hard disk if its currently attached (we
3942 * cannot attach the same hard disk twice) */
3943 if (i_findAttachment(mMediaData->mAttachments,
3944 pMedium))
3945 continue;
3946
3947 /* matched device, channel and bus (i.e. attached to the
3948 * same place) will win and immediately stop the search;
3949 * otherwise the attachment that has the youngest
3950 * descendant of medium will be used
3951 */
3952 if (pAttach->i_matches(Bstr(aName).raw(), aControllerPort, aDevice))
3953 {
3954 /* the simplest case: restore the whole attachment
3955 * and return, nothing else to do */
3956 mMediaData->mAttachments.push_back(*it);
3957
3958 /* Reattach the medium to the VM. */
3959 if (fHotplug || fSilent)
3960 {
3961 mediumLock.release();
3962 treeLock.release();
3963 alock.release();
3964
3965 MediumLockList *pMediumLockList(new MediumLockList());
3966
3967 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
3968 true /* fMediumLockWrite */,
3969 false /* fMediumLockWriteAll */,
3970 NULL,
3971 *pMediumLockList);
3972 alock.acquire();
3973 if (FAILED(rc))
3974 delete pMediumLockList;
3975 else
3976 {
3977 mData->mSession.mLockedMedia.Unlock();
3978 alock.release();
3979 rc = mData->mSession.mLockedMedia.Insert(pAttachTemp, pMediumLockList);
3980 mData->mSession.mLockedMedia.Lock();
3981 alock.acquire();
3982 }
3983 alock.release();
3984
3985 if (SUCCEEDED(rc))
3986 {
3987 rc = i_onStorageDeviceChange(pAttachTemp, FALSE /* aRemove */, fSilent);
3988 /* Remove lock list in case of error. */
3989 if (FAILED(rc))
3990 {
3991 mData->mSession.mLockedMedia.Unlock();
3992 mData->mSession.mLockedMedia.Remove(pAttachTemp);
3993 mData->mSession.mLockedMedia.Lock();
3994 }
3995 }
3996 }
3997
3998 return S_OK;
3999 }
4000 else if ( foundIt == oldAtts.end()
4001 || level > foundLevel /* prefer younger */
4002 )
4003 {
4004 foundIt = it;
4005 foundLevel = level;
4006 }
4007 }
4008 }
4009
4010 if (foundIt != oldAtts.end())
4011 {
4012 /* use the previously attached hard disk */
4013 medium = (*foundIt)->i_getMedium();
4014 mediumCaller.attach(medium);
4015 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4016 mediumLock.attach(medium);
4017 /* not implicit, doesn't require association with this VM */
4018 fIndirect = false;
4019 associate = false;
4020 /* go right to the MediumAttachment creation */
4021 break;
4022 }
4023 }
4024
4025 /* must give up the medium lock and medium tree lock as below we
4026 * go over snapshots, which needs a lock with higher lock order. */
4027 mediumLock.release();
4028 treeLock.release();
4029
4030 /* then, search through snapshots for the best diff in the given
4031 * hard disk's chain to base the new diff on */
4032
4033 ComObjPtr<Medium> base;
4034 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
4035 while (snap)
4036 {
4037 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
4038
4039 const MediaData::AttachmentList &snapAtts = snap->i_getSnapshotMachine()->mMediaData->mAttachments;
4040
4041 MediumAttachment *pAttachFound = NULL;
4042 uint32_t foundLevel = 0;
4043
4044 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin(); it != snapAtts.end(); ++it)
4045 {
4046 MediumAttachment *pAttach = *it;
4047 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
4048 Assert(!pMedium.isNull() || pAttach->i_getType() != DeviceType_HardDisk);
4049 if (pMedium.isNull())
4050 continue;
4051
4052 uint32_t level = 0;
4053 if (pMedium->i_getBase(&level) == medium)
4054 {
4055 /* matched device, channel and bus (i.e. attached to the
4056 * same place) will win and immediately stop the search;
4057 * otherwise the attachment that has the youngest
4058 * descendant of medium will be used
4059 */
4060 if ( pAttach->i_getDevice() == aDevice
4061 && pAttach->i_getPort() == aControllerPort
4062 && pAttach->i_getControllerName() == aName
4063 )
4064 {
4065 pAttachFound = pAttach;
4066 break;
4067 }
4068 else if ( !pAttachFound
4069 || level > foundLevel /* prefer younger */
4070 )
4071 {
4072 pAttachFound = pAttach;
4073 foundLevel = level;
4074 }
4075 }
4076 }
4077
4078 if (pAttachFound)
4079 {
4080 base = pAttachFound->i_getMedium();
4081 break;
4082 }
4083
4084 snap = snap->i_getParent();
4085 }
4086
4087 /* re-lock medium tree and the medium, as we need it below */
4088 treeLock.acquire();
4089 mediumLock.acquire();
4090
4091 /* found a suitable diff, use it as a base */
4092 if (!base.isNull())
4093 {
4094 medium = base;
4095 mediumCaller.attach(medium);
4096 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4097 mediumLock.attach(medium);
4098 }
4099 }
4100
4101 Utf8Str strFullSnapshotFolder;
4102 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4103
4104 ComObjPtr<Medium> diff;
4105 diff.createObject();
4106 // store this diff in the same registry as the parent
4107 Guid uuidRegistryParent;
4108 if (!medium->i_getFirstRegistryMachineId(uuidRegistryParent))
4109 {
4110 // parent image has no registry: this can happen if we're attaching a new immutable
4111 // image that has not yet been attached (medium then points to the base and we're
4112 // creating the diff image for the immutable, and the parent is not yet registered);
4113 // put the parent in the machine registry then
4114 mediumLock.release();
4115 treeLock.release();
4116 alock.release();
4117 i_addMediumToRegistry(medium);
4118 alock.acquire();
4119 treeLock.acquire();
4120 mediumLock.acquire();
4121 medium->i_getFirstRegistryMachineId(uuidRegistryParent);
4122 }
4123 rc = diff->init(mParent,
4124 medium->i_getPreferredDiffFormat(),
4125 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
4126 uuidRegistryParent,
4127 DeviceType_HardDisk);
4128 if (FAILED(rc)) return rc;
4129
4130 /* Apply the normal locking logic to the entire chain. */
4131 MediumLockList *pMediumLockList(new MediumLockList());
4132 mediumLock.release();
4133 treeLock.release();
4134 rc = diff->i_createMediumLockList(true /* fFailIfInaccessible */,
4135 true /* fMediumLockWrite */,
4136 false /* fMediumLockWriteAll */,
4137 medium,
4138 *pMediumLockList);
4139 treeLock.acquire();
4140 mediumLock.acquire();
4141 if (SUCCEEDED(rc))
4142 {
4143 mediumLock.release();
4144 treeLock.release();
4145 rc = pMediumLockList->Lock();
4146 treeLock.acquire();
4147 mediumLock.acquire();
4148 if (FAILED(rc))
4149 setError(rc,
4150 tr("Could not lock medium when creating diff '%s'"),
4151 diff->i_getLocationFull().c_str());
4152 else
4153 {
4154 /* will release the lock before the potentially lengthy
4155 * operation, so protect with the special state */
4156 MachineState_T oldState = mData->mMachineState;
4157 i_setMachineState(MachineState_SettingUp);
4158
4159 mediumLock.release();
4160 treeLock.release();
4161 alock.release();
4162
4163 rc = medium->i_createDiffStorage(diff,
4164 MediumVariant_Standard,
4165 pMediumLockList,
4166 NULL /* aProgress */,
4167 true /* aWait */);
4168
4169 alock.acquire();
4170 treeLock.acquire();
4171 mediumLock.acquire();
4172
4173 i_setMachineState(oldState);
4174 }
4175 }
4176
4177 /* Unlock the media and free the associated memory. */
4178 delete pMediumLockList;
4179
4180 if (FAILED(rc)) return rc;
4181
4182 /* use the created diff for the actual attachment */
4183 medium = diff;
4184 mediumCaller.attach(medium);
4185 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4186 mediumLock.attach(medium);
4187 }
4188 while (0);
4189
4190 ComObjPtr<MediumAttachment> attachment;
4191 attachment.createObject();
4192 rc = attachment->init(this,
4193 medium,
4194 aName,
4195 aControllerPort,
4196 aDevice,
4197 aType,
4198 fIndirect,
4199 false /* fPassthrough */,
4200 false /* fTempEject */,
4201 false /* fNonRotational */,
4202 false /* fDiscard */,
4203 fHotplug /* fHotPluggable */,
4204 Utf8Str::Empty);
4205 if (FAILED(rc)) return rc;
4206
4207 if (associate && !medium.isNull())
4208 {
4209 // as the last step, associate the medium to the VM
4210 rc = medium->i_addBackReference(mData->mUuid);
4211 // here we can fail because of Deleting, or being in process of creating a Diff
4212 if (FAILED(rc)) return rc;
4213
4214 mediumLock.release();
4215 treeLock.release();
4216 alock.release();
4217 i_addMediumToRegistry(medium);
4218 alock.acquire();
4219 treeLock.acquire();
4220 mediumLock.acquire();
4221 }
4222
4223 /* success: finally remember the attachment */
4224 i_setModified(IsModified_Storage);
4225 mMediaData.backup();
4226 mMediaData->mAttachments.push_back(attachment);
4227
4228 mediumLock.release();
4229 treeLock.release();
4230 alock.release();
4231
4232 if (fHotplug || fSilent)
4233 {
4234 if (!medium.isNull())
4235 {
4236 MediumLockList *pMediumLockList(new MediumLockList());
4237
4238 rc = medium->i_createMediumLockList(true /* fFailIfInaccessible */,
4239 true /* fMediumLockWrite */,
4240 false /* fMediumLockWriteAll */,
4241 NULL,
4242 *pMediumLockList);
4243 alock.acquire();
4244 if (FAILED(rc))
4245 delete pMediumLockList;
4246 else
4247 {
4248 mData->mSession.mLockedMedia.Unlock();
4249 alock.release();
4250 rc = mData->mSession.mLockedMedia.Insert(attachment, pMediumLockList);
4251 mData->mSession.mLockedMedia.Lock();
4252 alock.acquire();
4253 }
4254 alock.release();
4255 }
4256
4257 if (SUCCEEDED(rc))
4258 {
4259 rc = i_onStorageDeviceChange(attachment, FALSE /* aRemove */, fSilent);
4260 /* Remove lock list in case of error. */
4261 if (FAILED(rc))
4262 {
4263 mData->mSession.mLockedMedia.Unlock();
4264 mData->mSession.mLockedMedia.Remove(attachment);
4265 mData->mSession.mLockedMedia.Lock();
4266 }
4267 }
4268 }
4269
4270 /* Save modified registries, but skip this machine as it's the caller's
4271 * job to save its settings like all other settings changes. */
4272 mParent->i_unmarkRegistryModified(i_getId());
4273 mParent->i_saveModifiedRegistries();
4274
4275 return rc;
4276}
4277
4278HRESULT Machine::detachDevice(const com::Utf8Str &aName, LONG aControllerPort,
4279 LONG aDevice)
4280{
4281 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
4282 aName.c_str(), aControllerPort, aDevice));
4283
4284 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4285
4286 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
4287 if (FAILED(rc)) return rc;
4288
4289 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4290
4291 /* Check for an existing controller. */
4292 ComObjPtr<StorageController> ctl;
4293 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
4294 if (FAILED(rc)) return rc;
4295
4296 StorageControllerType_T ctrlType;
4297 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4298 if (FAILED(rc))
4299 return setError(E_FAIL,
4300 tr("Could not get type of controller '%s'"),
4301 aName.c_str());
4302
4303 bool fSilent = false;
4304 Utf8Str strReconfig;
4305
4306 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
4307 strReconfig = i_getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
4308 if ( mData->mMachineState == MachineState_Paused
4309 && strReconfig == "1")
4310 fSilent = true;
4311
4312 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
4313 bool fHotplug = false;
4314 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
4315 fHotplug = true;
4316
4317 if (fHotplug && !i_isControllerHotplugCapable(ctrlType))
4318 return setError(VBOX_E_INVALID_VM_STATE,
4319 tr("Controller '%s' does not support hotplugging"),
4320 aName.c_str());
4321
4322 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4323 Bstr(aName).raw(),
4324 aControllerPort,
4325 aDevice);
4326 if (!pAttach)
4327 return setError(VBOX_E_OBJECT_NOT_FOUND,
4328 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4329 aDevice, aControllerPort, aName.c_str());
4330
4331 if (fHotplug && !pAttach->i_getHotPluggable())
4332 return setError(VBOX_E_NOT_SUPPORTED,
4333 tr("The device slot %d on port %d of controller '%s' does not support hotplugging"),
4334 aDevice, aControllerPort, aName.c_str());
4335
4336 /*
4337 * The VM has to detach the device before we delete any implicit diffs.
4338 * If this fails we can roll back without loosing data.
4339 */
4340 if (fHotplug || fSilent)
4341 {
4342 alock.release();
4343 rc = i_onStorageDeviceChange(pAttach, TRUE /* aRemove */, fSilent);
4344 alock.acquire();
4345 }
4346 if (FAILED(rc)) return rc;
4347
4348 /* If we are here everything went well and we can delete the implicit now. */
4349 rc = i_detachDevice(pAttach, alock, NULL /* pSnapshot */);
4350
4351 alock.release();
4352
4353 /* Save modified registries, but skip this machine as it's the caller's
4354 * job to save its settings like all other settings changes. */
4355 mParent->i_unmarkRegistryModified(i_getId());
4356 mParent->i_saveModifiedRegistries();
4357
4358 return rc;
4359}
4360
4361HRESULT Machine::passthroughDevice(const com::Utf8Str &aName, LONG aControllerPort,
4362 LONG aDevice, BOOL aPassthrough)
4363{
4364 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aPassthrough=%d\n",
4365 aName.c_str(), aControllerPort, aDevice, aPassthrough));
4366
4367 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4368
4369 HRESULT rc = i_checkStateDependency(MutableStateDep);
4370 if (FAILED(rc)) return rc;
4371
4372 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4373
4374 if (Global::IsOnlineOrTransient(mData->mMachineState))
4375 return setError(VBOX_E_INVALID_VM_STATE,
4376 tr("Invalid machine state: %s"),
4377 Global::stringifyMachineState(mData->mMachineState));
4378
4379 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4380 Bstr(aName).raw(),
4381 aControllerPort,
4382 aDevice);
4383 if (!pAttach)
4384 return setError(VBOX_E_OBJECT_NOT_FOUND,
4385 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4386 aDevice, aControllerPort, aName.c_str());
4387
4388
4389 i_setModified(IsModified_Storage);
4390 mMediaData.backup();
4391
4392 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4393
4394 if (pAttach->i_getType() != DeviceType_DVD)
4395 return setError(E_INVALIDARG,
4396 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
4397 aDevice, aControllerPort, aName.c_str());
4398 pAttach->i_updatePassthrough(!!aPassthrough);
4399
4400 return S_OK;
4401}
4402
4403HRESULT Machine::temporaryEjectDevice(const com::Utf8Str &aName, LONG aControllerPort,
4404 LONG aDevice, BOOL aTemporaryEject)
4405{
4406
4407 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aTemporaryEject=%d\n",
4408 aName.c_str(), aControllerPort, aDevice, aTemporaryEject));
4409
4410 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4411
4412 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
4413 if (FAILED(rc)) return rc;
4414
4415 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4416 Bstr(aName).raw(),
4417 aControllerPort,
4418 aDevice);
4419 if (!pAttach)
4420 return setError(VBOX_E_OBJECT_NOT_FOUND,
4421 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4422 aDevice, aControllerPort, aName.c_str());
4423
4424
4425 i_setModified(IsModified_Storage);
4426 mMediaData.backup();
4427
4428 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4429
4430 if (pAttach->i_getType() != DeviceType_DVD)
4431 return setError(E_INVALIDARG,
4432 tr("Setting temporary eject flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
4433 aDevice, aControllerPort, aName.c_str());
4434 pAttach->i_updateTempEject(!!aTemporaryEject);
4435
4436 return S_OK;
4437}
4438
4439HRESULT Machine::nonRotationalDevice(const com::Utf8Str &aName, LONG aControllerPort,
4440 LONG aDevice, BOOL aNonRotational)
4441{
4442
4443 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aNonRotational=%d\n",
4444 aName.c_str(), aControllerPort, aDevice, aNonRotational));
4445
4446 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4447
4448 HRESULT rc = i_checkStateDependency(MutableStateDep);
4449 if (FAILED(rc)) return rc;
4450
4451 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4452
4453 if (Global::IsOnlineOrTransient(mData->mMachineState))
4454 return setError(VBOX_E_INVALID_VM_STATE,
4455 tr("Invalid machine state: %s"),
4456 Global::stringifyMachineState(mData->mMachineState));
4457
4458 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4459 Bstr(aName).raw(),
4460 aControllerPort,
4461 aDevice);
4462 if (!pAttach)
4463 return setError(VBOX_E_OBJECT_NOT_FOUND,
4464 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4465 aDevice, aControllerPort, aName.c_str());
4466
4467
4468 i_setModified(IsModified_Storage);
4469 mMediaData.backup();
4470
4471 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4472
4473 if (pAttach->i_getType() != DeviceType_HardDisk)
4474 return setError(E_INVALIDARG,
4475 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"),
4476 aDevice, aControllerPort, aName.c_str());
4477 pAttach->i_updateNonRotational(!!aNonRotational);
4478
4479 return S_OK;
4480}
4481
4482HRESULT Machine::setAutoDiscardForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4483 LONG aDevice, BOOL aDiscard)
4484{
4485
4486 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aDiscard=%d\n",
4487 aName.c_str(), aControllerPort, aDevice, aDiscard));
4488
4489 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4490
4491 HRESULT rc = i_checkStateDependency(MutableStateDep);
4492 if (FAILED(rc)) return rc;
4493
4494 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4495
4496 if (Global::IsOnlineOrTransient(mData->mMachineState))
4497 return setError(VBOX_E_INVALID_VM_STATE,
4498 tr("Invalid machine state: %s"),
4499 Global::stringifyMachineState(mData->mMachineState));
4500
4501 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4502 Bstr(aName).raw(),
4503 aControllerPort,
4504 aDevice);
4505 if (!pAttach)
4506 return setError(VBOX_E_OBJECT_NOT_FOUND,
4507 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4508 aDevice, aControllerPort, aName.c_str());
4509
4510
4511 i_setModified(IsModified_Storage);
4512 mMediaData.backup();
4513
4514 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4515
4516 if (pAttach->i_getType() != DeviceType_HardDisk)
4517 return setError(E_INVALIDARG,
4518 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"),
4519 aDevice, aControllerPort, aName.c_str());
4520 pAttach->i_updateDiscard(!!aDiscard);
4521
4522 return S_OK;
4523}
4524
4525HRESULT Machine::setHotPluggableForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4526 LONG aDevice, BOOL aHotPluggable)
4527{
4528 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aHotPluggable=%d\n",
4529 aName.c_str(), aControllerPort, aDevice, aHotPluggable));
4530
4531 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4532
4533 HRESULT rc = i_checkStateDependency(MutableStateDep);
4534 if (FAILED(rc)) return rc;
4535
4536 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4537
4538 if (Global::IsOnlineOrTransient(mData->mMachineState))
4539 return setError(VBOX_E_INVALID_VM_STATE,
4540 tr("Invalid machine state: %s"),
4541 Global::stringifyMachineState(mData->mMachineState));
4542
4543 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4544 Bstr(aName).raw(),
4545 aControllerPort,
4546 aDevice);
4547 if (!pAttach)
4548 return setError(VBOX_E_OBJECT_NOT_FOUND,
4549 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4550 aDevice, aControllerPort, aName.c_str());
4551
4552 /* Check for an existing controller. */
4553 ComObjPtr<StorageController> ctl;
4554 rc = i_getStorageControllerByName(aName, ctl, true /* aSetError */);
4555 if (FAILED(rc)) return rc;
4556
4557 StorageControllerType_T ctrlType;
4558 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4559 if (FAILED(rc))
4560 return setError(E_FAIL,
4561 tr("Could not get type of controller '%s'"),
4562 aName.c_str());
4563
4564 if (!i_isControllerHotplugCapable(ctrlType))
4565 return setError(VBOX_E_NOT_SUPPORTED,
4566 tr("Controller '%s' does not support changing the hot-pluggable device flag"),
4567 aName.c_str());
4568
4569 i_setModified(IsModified_Storage);
4570 mMediaData.backup();
4571
4572 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4573
4574 if (pAttach->i_getType() == DeviceType_Floppy)
4575 return setError(E_INVALIDARG,
4576 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"),
4577 aDevice, aControllerPort, aName.c_str());
4578 pAttach->i_updateHotPluggable(!!aHotPluggable);
4579
4580 return S_OK;
4581}
4582
4583HRESULT Machine::setNoBandwidthGroupForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4584 LONG aDevice)
4585{
4586 int rc = S_OK;
4587 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4588 aName.c_str(), aControllerPort, aDevice));
4589
4590 rc = setBandwidthGroupForDevice(aName, aControllerPort, aDevice, NULL);
4591
4592 return rc;
4593}
4594
4595HRESULT Machine::setBandwidthGroupForDevice(const com::Utf8Str &aName, LONG aControllerPort,
4596 LONG aDevice, const ComPtr<IBandwidthGroup> &aBandwidthGroup)
4597{
4598 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4599 aName.c_str(), aControllerPort, aDevice));
4600
4601 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4602
4603 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
4604 if (FAILED(rc)) return rc;
4605
4606 if (Global::IsOnlineOrTransient(mData->mMachineState))
4607 return setError(VBOX_E_INVALID_VM_STATE,
4608 tr("Invalid machine state: %s"),
4609 Global::stringifyMachineState(mData->mMachineState));
4610
4611 MediumAttachment *pAttach = i_findAttachment(mMediaData->mAttachments,
4612 Bstr(aName).raw(),
4613 aControllerPort,
4614 aDevice);
4615 if (!pAttach)
4616 return setError(VBOX_E_OBJECT_NOT_FOUND,
4617 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4618 aDevice, aControllerPort, aName.c_str());
4619
4620
4621 i_setModified(IsModified_Storage);
4622 mMediaData.backup();
4623
4624 IBandwidthGroup *iB = aBandwidthGroup;
4625 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(iB);
4626 if (aBandwidthGroup && group.isNull())
4627 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
4628
4629 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4630
4631 const Utf8Str strBandwidthGroupOld = pAttach->i_getBandwidthGroup();
4632 if (strBandwidthGroupOld.isNotEmpty())
4633 {
4634 /* Get the bandwidth group object and release it - this must not fail. */
4635 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
4636 rc = i_getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
4637 Assert(SUCCEEDED(rc));
4638
4639 pBandwidthGroupOld->i_release();
4640 pAttach->i_updateBandwidthGroup(Utf8Str::Empty);
4641 }
4642
4643 if (!group.isNull())
4644 {
4645 group->i_reference();
4646 pAttach->i_updateBandwidthGroup(group->i_getName());
4647 }
4648
4649 return S_OK;
4650}
4651
4652HRESULT Machine::attachDeviceWithoutMedium(const com::Utf8Str &aName,
4653 LONG aControllerPort,
4654 LONG aDevice,
4655 DeviceType_T aType)
4656{
4657 HRESULT rc = S_OK;
4658
4659 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aType=%d\n",
4660 aName.c_str(), aControllerPort, aDevice, aType));
4661
4662 rc = AttachDevice(Bstr(aName).raw(), aControllerPort, aDevice, aType, NULL);
4663
4664 return rc;
4665}
4666
4667
4668HRESULT Machine::unmountMedium(const com::Utf8Str &aName,
4669 LONG aControllerPort,
4670 LONG aDevice,
4671 BOOL aForce)
4672{
4673 int rc = S_OK;
4674 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d",
4675 aName.c_str(), aControllerPort, aForce));
4676
4677 rc = mountMedium(aName, aControllerPort, aDevice, NULL, aForce);
4678
4679 return rc;
4680}
4681
4682HRESULT Machine::mountMedium(const com::Utf8Str &aName,
4683 LONG aControllerPort,
4684 LONG aDevice,
4685 const ComPtr<IMedium> &aMedium,
4686 BOOL aForce)
4687{
4688 int rc = S_OK;
4689 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aForce=%d\n",
4690 aName.c_str(), aControllerPort, aDevice, aForce));
4691
4692 // request the host lock first, since might be calling Host methods for getting host drives;
4693 // next, protect the media tree all the while we're in here, as well as our member variables
4694 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
4695 this->lockHandle(),
4696 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4697
4698 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(mMediaData->mAttachments,
4699 Bstr(aName).raw(),
4700 aControllerPort,
4701 aDevice);
4702 if (pAttach.isNull())
4703 return setError(VBOX_E_OBJECT_NOT_FOUND,
4704 tr("No drive attached to device slot %d on port %d of controller '%s'"),
4705 aDevice, aControllerPort, aName.c_str());
4706
4707 /* Remember previously mounted medium. The medium before taking the
4708 * backup is not necessarily the same thing. */
4709 ComObjPtr<Medium> oldmedium;
4710 oldmedium = pAttach->i_getMedium();
4711
4712 IMedium *iM = aMedium;
4713 ComObjPtr<Medium> pMedium = static_cast<Medium*>(iM);
4714 if (aMedium && pMedium.isNull())
4715 return setError(E_INVALIDARG, "The given medium pointer is invalid");
4716
4717 AutoCaller mediumCaller(pMedium);
4718 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4719
4720 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4721 if (pMedium)
4722 {
4723 DeviceType_T mediumType = pAttach->i_getType();
4724 switch (mediumType)
4725 {
4726 case DeviceType_DVD:
4727 case DeviceType_Floppy:
4728 break;
4729
4730 default:
4731 return setError(VBOX_E_INVALID_OBJECT_STATE,
4732 tr("The device at port %d, device %d of controller '%s' of this virtual machine is not removeable"),
4733 aControllerPort,
4734 aDevice,
4735 aName.c_str());
4736 }
4737 }
4738
4739 i_setModified(IsModified_Storage);
4740 mMediaData.backup();
4741
4742 {
4743 // The backup operation makes the pAttach reference point to the
4744 // old settings. Re-get the correct reference.
4745 pAttach = i_findAttachment(mMediaData->mAttachments,
4746 Bstr(aName).raw(),
4747 aControllerPort,
4748 aDevice);
4749 if (!oldmedium.isNull())
4750 oldmedium->i_removeBackReference(mData->mUuid);
4751 if (!pMedium.isNull())
4752 {
4753 pMedium->i_addBackReference(mData->mUuid);
4754
4755 mediumLock.release();
4756 multiLock.release();
4757 i_addMediumToRegistry(pMedium);
4758 multiLock.acquire();
4759 mediumLock.acquire();
4760 }
4761
4762 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4763 pAttach->i_updateMedium(pMedium);
4764 }
4765
4766 i_setModified(IsModified_Storage);
4767
4768 mediumLock.release();
4769 multiLock.release();
4770 rc = i_onMediumChange(pAttach, aForce);
4771 multiLock.acquire();
4772 mediumLock.acquire();
4773
4774 /* On error roll back this change only. */
4775 if (FAILED(rc))
4776 {
4777 if (!pMedium.isNull())
4778 pMedium->i_removeBackReference(mData->mUuid);
4779 pAttach = i_findAttachment(mMediaData->mAttachments,
4780 Bstr(aName).raw(),
4781 aControllerPort,
4782 aDevice);
4783 /* If the attachment is gone in the meantime, bail out. */
4784 if (pAttach.isNull())
4785 return rc;
4786 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4787 if (!oldmedium.isNull())
4788 oldmedium->i_addBackReference(mData->mUuid);
4789 pAttach->i_updateMedium(oldmedium);
4790 }
4791
4792 mediumLock.release();
4793 multiLock.release();
4794
4795 /* Save modified registries, but skip this machine as it's the caller's
4796 * job to save its settings like all other settings changes. */
4797 mParent->i_unmarkRegistryModified(i_getId());
4798 mParent->i_saveModifiedRegistries();
4799
4800 return rc;
4801}
4802HRESULT Machine::getMedium(const com::Utf8Str &aName,
4803 LONG aControllerPort,
4804 LONG aDevice,
4805 ComPtr<IMedium> &aMedium)
4806{
4807 LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
4808 aName.c_str(), aControllerPort, aDevice));
4809
4810 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4811
4812 aMedium = NULL;
4813
4814 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(mMediaData->mAttachments,
4815 Bstr(aName).raw(),
4816 aControllerPort,
4817 aDevice);
4818 if (pAttach.isNull())
4819 return setError(VBOX_E_OBJECT_NOT_FOUND,
4820 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
4821 aDevice, aControllerPort, aName.c_str());
4822
4823 aMedium = pAttach->i_getMedium();
4824
4825 return S_OK;
4826}
4827
4828HRESULT Machine::getSerialPort(ULONG aSlot, ComPtr<ISerialPort> &aPort)
4829{
4830
4831 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4832
4833 mSerialPorts[aSlot].queryInterfaceTo(aPort.asOutParam());
4834
4835 return S_OK;
4836}
4837
4838HRESULT Machine::getParallelPort(ULONG aSlot, ComPtr<IParallelPort> &aPort)
4839{
4840 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4841
4842 mParallelPorts[aSlot].queryInterfaceTo(aPort.asOutParam());
4843
4844 return S_OK;
4845}
4846
4847HRESULT Machine::getNetworkAdapter(ULONG aSlot, ComPtr<INetworkAdapter> &aAdapter)
4848{
4849 /* Do not assert if slot is out of range, just return the advertised
4850 status. testdriver/vbox.py triggers this in logVmInfo. */
4851 if (aSlot >= mNetworkAdapters.size())
4852 return setError(E_INVALIDARG,
4853 tr("No network adapter in slot %RU32 (total %RU32 adapters)"),
4854 aSlot, mNetworkAdapters.size());
4855
4856 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4857
4858 mNetworkAdapters[aSlot].queryInterfaceTo(aAdapter.asOutParam());
4859
4860 return S_OK;
4861}
4862
4863HRESULT Machine::getExtraDataKeys(std::vector<com::Utf8Str> &aKeys)
4864{
4865 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4866
4867 aKeys.resize(mData->pMachineConfigFile->mapExtraDataItems.size());
4868 size_t i = 0;
4869 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4870 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4871 ++it, ++i)
4872 aKeys[i] = it->first;
4873
4874 return S_OK;
4875}
4876
4877 /**
4878 * @note Locks this object for reading.
4879 */
4880HRESULT Machine::getExtraData(const com::Utf8Str &aKey,
4881 com::Utf8Str &aValue)
4882{
4883 /* start with nothing found */
4884 aValue = "";
4885
4886 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4887
4888 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(aKey);
4889 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4890 // found:
4891 aValue = it->second; // source is a Utf8Str
4892
4893 /* return the result to caller (may be empty) */
4894 return S_OK;
4895}
4896
4897 /**
4898 * @note Locks mParent for writing + this object for writing.
4899 */
4900HRESULT Machine::setExtraData(const com::Utf8Str &aKey, const com::Utf8Str &aValue)
4901{
4902 Utf8Str strOldValue; // empty
4903
4904 // locking note: we only hold the read lock briefly to look up the old value,
4905 // then release it and call the onExtraCanChange callbacks. There is a small
4906 // chance of a race insofar as the callback might be called twice if two callers
4907 // change the same key at the same time, but that's a much better solution
4908 // than the deadlock we had here before. The actual changing of the extradata
4909 // is then performed under the write lock and race-free.
4910
4911 // look up the old value first; if nothing has changed then we need not do anything
4912 {
4913 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
4914
4915 // For snapshots don't even think about allowing changes, extradata
4916 // is global for a machine, so there is nothing snapshot specific.
4917 if (i_isSnapshotMachine())
4918 return setError(VBOX_E_INVALID_VM_STATE,
4919 tr("Cannot set extradata for a snapshot"));
4920
4921 // check if the right IMachine instance is used
4922 if (mData->mRegistered && !i_isSessionMachine())
4923 return setError(VBOX_E_INVALID_VM_STATE,
4924 tr("Cannot set extradata for an immutable machine"));
4925
4926 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(aKey);
4927 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4928 strOldValue = it->second;
4929 }
4930
4931 bool fChanged;
4932 if ((fChanged = (strOldValue != aValue)))
4933 {
4934 // ask for permission from all listeners outside the locks;
4935 // i_onExtraDataCanChange() only briefly requests the VirtualBox
4936 // lock to copy the list of callbacks to invoke
4937 Bstr error;
4938 Bstr bstrValue(aValue);
4939
4940 if (!mParent->i_onExtraDataCanChange(mData->mUuid, Bstr(aKey).raw(), bstrValue.raw(), error))
4941 {
4942 const char *sep = error.isEmpty() ? "" : ": ";
4943 CBSTR err = error.raw();
4944 Log1WarningFunc(("Someone vetoed! Change refused%s%ls\n", sep, err));
4945 return setError(E_ACCESSDENIED,
4946 tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
4947 aKey.c_str(),
4948 aValue.c_str(),
4949 sep,
4950 err);
4951 }
4952
4953 // data is changing and change not vetoed: then write it out under the lock
4954 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4955
4956 if (aValue.isEmpty())
4957 mData->pMachineConfigFile->mapExtraDataItems.erase(aKey);
4958 else
4959 mData->pMachineConfigFile->mapExtraDataItems[aKey] = aValue;
4960 // creates a new key if needed
4961
4962 bool fNeedsGlobalSaveSettings = false;
4963 // This saving of settings is tricky: there is no "old state" for the
4964 // extradata items at all (unlike all other settings), so the old/new
4965 // settings comparison would give a wrong result!
4966 i_saveSettings(&fNeedsGlobalSaveSettings, SaveS_Force);
4967
4968 if (fNeedsGlobalSaveSettings)
4969 {
4970 // save the global settings; for that we should hold only the VirtualBox lock
4971 alock.release();
4972 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
4973 mParent->i_saveSettings();
4974 }
4975 }
4976
4977 // fire notification outside the lock
4978 if (fChanged)
4979 mParent->i_onExtraDataChange(mData->mUuid, Bstr(aKey).raw(), Bstr(aValue).raw());
4980
4981 return S_OK;
4982}
4983
4984HRESULT Machine::setSettingsFilePath(const com::Utf8Str &aSettingsFilePath, ComPtr<IProgress> &aProgress)
4985{
4986 aProgress = NULL;
4987 NOREF(aSettingsFilePath);
4988 ReturnComNotImplemented();
4989}
4990
4991HRESULT Machine::saveSettings()
4992{
4993 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
4994
4995 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
4996 if (FAILED(rc)) return rc;
4997
4998 /* the settings file path may never be null */
4999 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
5000
5001 /* save all VM data excluding snapshots */
5002 bool fNeedsGlobalSaveSettings = false;
5003 rc = i_saveSettings(&fNeedsGlobalSaveSettings);
5004 mlock.release();
5005
5006 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
5007 {
5008 // save the global settings; for that we should hold only the VirtualBox lock
5009 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
5010 rc = mParent->i_saveSettings();
5011 }
5012
5013 return rc;
5014}
5015
5016
5017HRESULT Machine::discardSettings()
5018{
5019 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5020
5021 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
5022 if (FAILED(rc)) return rc;
5023
5024 /*
5025 * during this rollback, the session will be notified if data has
5026 * been actually changed
5027 */
5028 i_rollback(true /* aNotify */);
5029
5030 return S_OK;
5031}
5032
5033/** @note Locks objects! */
5034HRESULT Machine::unregister(AutoCaller &autoCaller,
5035 CleanupMode_T aCleanupMode,
5036 std::vector<ComPtr<IMedium> > &aMedia)
5037{
5038 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5039
5040 Guid id(i_getId());
5041
5042 if (mData->mSession.mState != SessionState_Unlocked)
5043 return setError(VBOX_E_INVALID_OBJECT_STATE,
5044 tr("Cannot unregister the machine '%s' while it is locked"),
5045 mUserData->s.strName.c_str());
5046
5047 // wait for state dependents to drop to zero
5048 i_ensureNoStateDependencies();
5049
5050 if (!mData->mAccessible)
5051 {
5052 // inaccessible maschines can only be unregistered; uninitialize ourselves
5053 // here because currently there may be no unregistered that are inaccessible
5054 // (this state combination is not supported). Note releasing the caller and
5055 // leaving the lock before calling uninit()
5056 alock.release();
5057 autoCaller.release();
5058
5059 uninit();
5060
5061 mParent->i_unregisterMachine(this, id);
5062 // calls VirtualBox::i_saveSettings()
5063
5064 return S_OK;
5065 }
5066
5067 HRESULT rc = S_OK;
5068
5069 /// @todo r=klaus this is stupid... why is the saved state always deleted?
5070 // discard saved state
5071 if (mData->mMachineState == MachineState_Saved)
5072 {
5073 // add the saved state file to the list of files the caller should delete
5074 Assert(!mSSData->strStateFilePath.isEmpty());
5075 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
5076
5077 mSSData->strStateFilePath.setNull();
5078
5079 // unconditionally set the machine state to powered off, we now
5080 // know no session has locked the machine
5081 mData->mMachineState = MachineState_PoweredOff;
5082 }
5083
5084 size_t cSnapshots = 0;
5085 if (mData->mFirstSnapshot)
5086 cSnapshots = mData->mFirstSnapshot->i_getAllChildrenCount() + 1;
5087 if (cSnapshots && aCleanupMode == CleanupMode_UnregisterOnly)
5088 // fail now before we start detaching media
5089 return setError(VBOX_E_INVALID_OBJECT_STATE,
5090 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
5091 mUserData->s.strName.c_str(), cSnapshots);
5092
5093 // This list collects the medium objects from all medium attachments
5094 // which we will detach from the machine and its snapshots, in a specific
5095 // order which allows for closing all media without getting "media in use"
5096 // errors, simply by going through the list from the front to the back:
5097 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
5098 // and must be closed before the parent media from the snapshots, or closing the parents
5099 // will fail because they still have children);
5100 // 2) media from the youngest snapshots followed by those from the parent snapshots until
5101 // the root ("first") snapshot of the machine.
5102 MediaList llMedia;
5103
5104 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
5105 && mMediaData->mAttachments.size()
5106 )
5107 {
5108 // we have media attachments: detach them all and add the Medium objects to our list
5109 if (aCleanupMode != CleanupMode_UnregisterOnly)
5110 i_detachAllMedia(alock, NULL /* pSnapshot */, aCleanupMode, llMedia);
5111 else
5112 return setError(VBOX_E_INVALID_OBJECT_STATE,
5113 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
5114 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
5115 }
5116
5117 if (cSnapshots)
5118 {
5119 // add the media from the medium attachments of the snapshots to llMedia
5120 // as well, after the "main" machine media; Snapshot::uninitRecursively()
5121 // calls Machine::detachAllMedia() for the snapshot machine, recursing
5122 // into the children first
5123
5124 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
5125 MachineState_T oldState = mData->mMachineState;
5126 mData->mMachineState = MachineState_DeletingSnapshot;
5127
5128 // make a copy of the first snapshot so the refcount does not drop to 0
5129 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
5130 // because of the AutoCaller voodoo)
5131 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
5132
5133 // GO!
5134 pFirstSnapshot->i_uninitRecursively(alock, aCleanupMode, llMedia, mData->llFilesToDelete);
5135
5136 mData->mMachineState = oldState;
5137 }
5138
5139 if (FAILED(rc))
5140 {
5141 i_rollbackMedia();
5142 return rc;
5143 }
5144
5145 // commit all the media changes made above
5146 i_commitMedia();
5147
5148 mData->mRegistered = false;
5149
5150 // machine lock no longer needed
5151 alock.release();
5152
5153 // return media to caller
5154 size_t i = 0;
5155 aMedia.resize(llMedia.size());
5156 for (MediaList::iterator it = llMedia.begin(); it != llMedia.end(); ++it, ++i)
5157 (*it).queryInterfaceTo(aMedia[i].asOutParam());
5158
5159 mParent->i_unregisterMachine(this, id);
5160 // calls VirtualBox::i_saveSettings() and VirtualBox::saveModifiedRegistries()
5161
5162 return S_OK;
5163}
5164
5165/**
5166 * Task record for deleting a machine config.
5167 */
5168struct Machine::DeleteConfigTask
5169 : public Machine::Task
5170{
5171 DeleteConfigTask(Machine *m,
5172 Progress *p,
5173 const Utf8Str &t,
5174 const RTCList<ComPtr<IMedium> > &llMediums,
5175 const StringsList &llFilesToDelete)
5176 : Task(m, p, t),
5177 m_llMediums(llMediums),
5178 m_llFilesToDelete(llFilesToDelete)
5179 {}
5180
5181 void handler()
5182 {
5183 m_pMachine->i_deleteConfigHandler(*this);
5184 }
5185
5186 RTCList<ComPtr<IMedium> > m_llMediums;
5187 StringsList m_llFilesToDelete;
5188};
5189
5190/**
5191 * Task thread implementation for SessionMachine::DeleteConfig(), called from
5192 * SessionMachine::taskHandler().
5193 *
5194 * @note Locks this object for writing.
5195 *
5196 * @param task
5197 * @return
5198 */
5199void Machine::i_deleteConfigHandler(DeleteConfigTask &task)
5200{
5201 LogFlowThisFuncEnter();
5202
5203 AutoCaller autoCaller(this);
5204 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
5205 if (FAILED(autoCaller.rc()))
5206 {
5207 /* we might have been uninitialized because the session was accidentally
5208 * closed by the client, so don't assert */
5209 HRESULT rc = setError(E_FAIL,
5210 tr("The session has been accidentally closed"));
5211 task.m_pProgress->i_notifyComplete(rc);
5212 LogFlowThisFuncLeave();
5213 return;
5214 }
5215
5216 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5217
5218 HRESULT rc = S_OK;
5219
5220 try
5221 {
5222 ULONG uLogHistoryCount = 3;
5223 ComPtr<ISystemProperties> systemProperties;
5224 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
5225 if (FAILED(rc)) throw rc;
5226
5227 if (!systemProperties.isNull())
5228 {
5229 rc = systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
5230 if (FAILED(rc)) throw rc;
5231 }
5232
5233 MachineState_T oldState = mData->mMachineState;
5234 i_setMachineState(MachineState_SettingUp);
5235 alock.release();
5236 for (size_t i = 0; i < task.m_llMediums.size(); ++i)
5237 {
5238 ComObjPtr<Medium> pMedium = (Medium*)(IMedium*)(task.m_llMediums.at(i));
5239 {
5240 AutoCaller mac(pMedium);
5241 if (FAILED(mac.rc())) throw mac.rc();
5242 Utf8Str strLocation = pMedium->i_getLocationFull();
5243 rc = task.m_pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), strLocation.c_str()).raw(), 1);
5244 if (FAILED(rc)) throw rc;
5245 LogFunc(("Deleting file %s\n", strLocation.c_str()));
5246 }
5247 if (pMedium->i_isMediumFormatFile())
5248 {
5249 ComPtr<IProgress> pProgress2;
5250 rc = pMedium->DeleteStorage(pProgress2.asOutParam());
5251 if (FAILED(rc)) throw rc;
5252 rc = task.m_pProgress->WaitForAsyncProgressCompletion(pProgress2);
5253 if (FAILED(rc)) throw rc;
5254 /* Check the result of the asynchronous process. */
5255 LONG iRc;
5256 rc = pProgress2->COMGETTER(ResultCode)(&iRc);
5257 if (FAILED(rc)) throw rc;
5258 /* If the thread of the progress object has an error, then
5259 * retrieve the error info from there, or it'll be lost. */
5260 if (FAILED(iRc))
5261 throw setError(ProgressErrorInfo(pProgress2));
5262 }
5263
5264 /* Close the medium, deliberately without checking the return
5265 * code, and without leaving any trace in the error info, as
5266 * a failure here is a very minor issue, which shouldn't happen
5267 * as above we even managed to delete the medium. */
5268 {
5269 ErrorInfoKeeper eik;
5270 pMedium->Close();
5271 }
5272 }
5273 i_setMachineState(oldState);
5274 alock.acquire();
5275
5276 // delete the files pushed on the task list by Machine::Delete()
5277 // (this includes saved states of the machine and snapshots and
5278 // medium storage files from the IMedium list passed in, and the
5279 // machine XML file)
5280 StringsList::const_iterator it = task.m_llFilesToDelete.begin();
5281 while (it != task.m_llFilesToDelete.end())
5282 {
5283 const Utf8Str &strFile = *it;
5284 LogFunc(("Deleting file %s\n", strFile.c_str()));
5285 int vrc = RTFileDelete(strFile.c_str());
5286 if (RT_FAILURE(vrc))
5287 throw setError(VBOX_E_IPRT_ERROR,
5288 tr("Could not delete file '%s' (%Rrc)"), strFile.c_str(), vrc);
5289
5290 ++it;
5291 if (it == task.m_llFilesToDelete.end())
5292 {
5293 rc = task.m_pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
5294 if (FAILED(rc)) throw rc;
5295 break;
5296 }
5297
5298 rc = task.m_pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
5299 if (FAILED(rc)) throw rc;
5300 }
5301
5302 /* delete the settings only when the file actually exists */
5303 if (mData->pMachineConfigFile->fileExists())
5304 {
5305 /* Delete any backup or uncommitted XML files. Ignore failures.
5306 See the fSafe parameter of xml::XmlFileWriter::write for details. */
5307 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
5308 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
5309 RTFileDelete(otherXml.c_str());
5310 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
5311 RTFileDelete(otherXml.c_str());
5312
5313 /* delete the Logs folder, nothing important should be left
5314 * there (we don't check for errors because the user might have
5315 * some private files there that we don't want to delete) */
5316 Utf8Str logFolder;
5317 getLogFolder(logFolder);
5318 Assert(logFolder.length());
5319 if (RTDirExists(logFolder.c_str()))
5320 {
5321 /* Delete all VBox.log[.N] files from the Logs folder
5322 * (this must be in sync with the rotation logic in
5323 * Console::powerUpThread()). Also, delete the VBox.png[.N]
5324 * files that may have been created by the GUI. */
5325 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
5326 logFolder.c_str(), RTPATH_DELIMITER);
5327 RTFileDelete(log.c_str());
5328 log = Utf8StrFmt("%s%cVBox.png",
5329 logFolder.c_str(), RTPATH_DELIMITER);
5330 RTFileDelete(log.c_str());
5331 for (int i = uLogHistoryCount; i > 0; i--)
5332 {
5333 log = Utf8StrFmt("%s%cVBox.log.%d",
5334 logFolder.c_str(), RTPATH_DELIMITER, i);
5335 RTFileDelete(log.c_str());
5336 log = Utf8StrFmt("%s%cVBox.png.%d",
5337 logFolder.c_str(), RTPATH_DELIMITER, i);
5338 RTFileDelete(log.c_str());
5339 }
5340#if defined(RT_OS_WINDOWS)
5341 log = Utf8StrFmt("%s%cVBoxStartup.log", logFolder.c_str(), RTPATH_DELIMITER);
5342 RTFileDelete(log.c_str());
5343 log = Utf8StrFmt("%s%cVBoxHardening.log", logFolder.c_str(), RTPATH_DELIMITER);
5344 RTFileDelete(log.c_str());
5345#endif
5346
5347 RTDirRemove(logFolder.c_str());
5348 }
5349
5350 /* delete the Snapshots folder, nothing important should be left
5351 * there (we don't check for errors because the user might have
5352 * some private files there that we don't want to delete) */
5353 Utf8Str strFullSnapshotFolder;
5354 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
5355 Assert(!strFullSnapshotFolder.isEmpty());
5356 if (RTDirExists(strFullSnapshotFolder.c_str()))
5357 RTDirRemove(strFullSnapshotFolder.c_str());
5358
5359 // delete the directory that contains the settings file, but only
5360 // if it matches the VM name
5361 Utf8Str settingsDir;
5362 if (i_isInOwnDir(&settingsDir))
5363 RTDirRemove(settingsDir.c_str());
5364 }
5365
5366 alock.release();
5367
5368 mParent->i_saveModifiedRegistries();
5369 }
5370 catch (HRESULT aRC) { rc = aRC; }
5371
5372 task.m_pProgress->i_notifyComplete(rc);
5373
5374 LogFlowThisFuncLeave();
5375}
5376
5377HRESULT Machine::deleteConfig(const std::vector<ComPtr<IMedium> > &aMedia, ComPtr<IProgress> &aProgress)
5378{
5379 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5380
5381 HRESULT rc = i_checkStateDependency(MutableStateDep);
5382 if (FAILED(rc)) return rc;
5383
5384 if (mData->mRegistered)
5385 return setError(VBOX_E_INVALID_VM_STATE,
5386 tr("Cannot delete settings of a registered machine"));
5387
5388 // collect files to delete
5389 StringsList llFilesToDelete(mData->llFilesToDelete); // saved states pushed here by Unregister()
5390 if (mData->pMachineConfigFile->fileExists())
5391 llFilesToDelete.push_back(mData->m_strConfigFileFull);
5392
5393 RTCList<ComPtr<IMedium> > llMediums;
5394 for (size_t i = 0; i < aMedia.size(); ++i)
5395 {
5396 IMedium *pIMedium(aMedia[i]);
5397 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
5398 if (pMedium.isNull())
5399 return setError(E_INVALIDARG, "The given medium pointer with index %d is invalid", i);
5400 SafeArray<BSTR> ids;
5401 rc = pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(ids));
5402 if (FAILED(rc)) return rc;
5403 /* At this point the medium should not have any back references
5404 * anymore. If it has it is attached to another VM and *must* not
5405 * deleted. */
5406 if (ids.size() < 1)
5407 llMediums.append(pMedium);
5408 }
5409
5410 ComObjPtr<Progress> pProgress;
5411 pProgress.createObject();
5412 rc = pProgress->init(i_getVirtualBox(),
5413 static_cast<IMachine*>(this) /* aInitiator */,
5414 Bstr(tr("Deleting files")).raw(),
5415 true /* fCancellable */,
5416 (ULONG)(llFilesToDelete.size() + llMediums.size() + 1), // cOperations
5417 BstrFmt(tr("Deleting '%s'"), llFilesToDelete.front().c_str()).raw());
5418 if (FAILED(rc))
5419 return rc;
5420
5421 /* create and start the task on a separate thread (note that it will not
5422 * start working until we release alock) */
5423 DeleteConfigTask *pTask = new DeleteConfigTask(this, pProgress, "DeleteVM", llMediums, llFilesToDelete);
5424 rc = pTask->createThread();
5425 if (FAILED(rc))
5426 return rc;
5427
5428 pProgress.queryInterfaceTo(aProgress.asOutParam());
5429
5430 LogFlowFuncLeave();
5431
5432 return S_OK;
5433}
5434
5435HRESULT Machine::findSnapshot(const com::Utf8Str &aNameOrId, ComPtr<ISnapshot> &aSnapshot)
5436{
5437 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5438
5439 ComObjPtr<Snapshot> pSnapshot;
5440 HRESULT rc;
5441
5442 if (aNameOrId.isEmpty())
5443 // null case (caller wants root snapshot): i_findSnapshotById() handles this
5444 rc = i_findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
5445 else
5446 {
5447 Guid uuid(aNameOrId);
5448 if (uuid.isValid())
5449 rc = i_findSnapshotById(uuid, pSnapshot, true /* aSetError */);
5450 else
5451 rc = i_findSnapshotByName(aNameOrId, pSnapshot, true /* aSetError */);
5452 }
5453 pSnapshot.queryInterfaceTo(aSnapshot.asOutParam());
5454
5455 return rc;
5456}
5457
5458HRESULT Machine::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable, BOOL aAutomount)
5459{
5460 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5461
5462 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
5463 if (FAILED(rc)) return rc;
5464
5465 ComObjPtr<SharedFolder> sharedFolder;
5466 rc = i_findSharedFolder(aName, sharedFolder, false /* aSetError */);
5467 if (SUCCEEDED(rc))
5468 return setError(VBOX_E_OBJECT_IN_USE,
5469 tr("Shared folder named '%s' already exists"),
5470 aName.c_str());
5471
5472 sharedFolder.createObject();
5473 rc = sharedFolder->init(i_getMachine(),
5474 aName,
5475 aHostPath,
5476 !!aWritable,
5477 !!aAutomount,
5478 true /* fFailOnError */);
5479 if (FAILED(rc)) return rc;
5480
5481 i_setModified(IsModified_SharedFolders);
5482 mHWData.backup();
5483 mHWData->mSharedFolders.push_back(sharedFolder);
5484
5485 /* inform the direct session if any */
5486 alock.release();
5487 i_onSharedFolderChange();
5488
5489 return S_OK;
5490}
5491
5492HRESULT Machine::removeSharedFolder(const com::Utf8Str &aName)
5493{
5494 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5495
5496 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
5497 if (FAILED(rc)) return rc;
5498
5499 ComObjPtr<SharedFolder> sharedFolder;
5500 rc = i_findSharedFolder(aName, sharedFolder, true /* aSetError */);
5501 if (FAILED(rc)) return rc;
5502
5503 i_setModified(IsModified_SharedFolders);
5504 mHWData.backup();
5505 mHWData->mSharedFolders.remove(sharedFolder);
5506
5507 /* inform the direct session if any */
5508 alock.release();
5509 i_onSharedFolderChange();
5510
5511 return S_OK;
5512}
5513
5514HRESULT Machine::canShowConsoleWindow(BOOL *aCanShow)
5515{
5516 /* start with No */
5517 *aCanShow = FALSE;
5518
5519 ComPtr<IInternalSessionControl> directControl;
5520 {
5521 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5522
5523 if (mData->mSession.mState != SessionState_Locked)
5524 return setError(VBOX_E_INVALID_VM_STATE,
5525 tr("Machine is not locked for session (session state: %s)"),
5526 Global::stringifySessionState(mData->mSession.mState));
5527
5528 if (mData->mSession.mLockType == LockType_VM)
5529 directControl = mData->mSession.mDirectControl;
5530 }
5531
5532 /* ignore calls made after #OnSessionEnd() is called */
5533 if (!directControl)
5534 return S_OK;
5535
5536 LONG64 dummy;
5537 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
5538}
5539
5540HRESULT Machine::showConsoleWindow(LONG64 *aWinId)
5541{
5542 ComPtr<IInternalSessionControl> directControl;
5543 {
5544 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5545
5546 if (mData->mSession.mState != SessionState_Locked)
5547 return setError(E_FAIL,
5548 tr("Machine is not locked for session (session state: %s)"),
5549 Global::stringifySessionState(mData->mSession.mState));
5550
5551 if (mData->mSession.mLockType == LockType_VM)
5552 directControl = mData->mSession.mDirectControl;
5553 }
5554
5555 /* ignore calls made after #OnSessionEnd() is called */
5556 if (!directControl)
5557 return S_OK;
5558
5559 BOOL dummy;
5560 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
5561}
5562
5563#ifdef VBOX_WITH_GUEST_PROPS
5564/**
5565 * Look up a guest property in VBoxSVC's internal structures.
5566 */
5567HRESULT Machine::i_getGuestPropertyFromService(const com::Utf8Str &aName,
5568 com::Utf8Str &aValue,
5569 LONG64 *aTimestamp,
5570 com::Utf8Str &aFlags) const
5571{
5572 using namespace guestProp;
5573
5574 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5575 HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.find(aName);
5576
5577 if (it != mHWData->mGuestProperties.end())
5578 {
5579 char szFlags[MAX_FLAGS_LEN + 1];
5580 aValue = it->second.strValue;
5581 *aTimestamp = it->second.mTimestamp;
5582 writeFlags(it->second.mFlags, szFlags);
5583 aFlags = Utf8Str(szFlags);
5584 }
5585
5586 return S_OK;
5587}
5588
5589/**
5590 * Query the VM that a guest property belongs to for the property.
5591 * @returns E_ACCESSDENIED if the VM process is not available or not
5592 * currently handling queries and the lookup should then be done in
5593 * VBoxSVC.
5594 */
5595HRESULT Machine::i_getGuestPropertyFromVM(const com::Utf8Str &aName,
5596 com::Utf8Str &aValue,
5597 LONG64 *aTimestamp,
5598 com::Utf8Str &aFlags) const
5599{
5600 HRESULT rc = S_OK;
5601 BSTR bValue = NULL;
5602 BSTR bFlags = NULL;
5603
5604 ComPtr<IInternalSessionControl> directControl;
5605 {
5606 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5607 if (mData->mSession.mLockType == LockType_VM)
5608 directControl = mData->mSession.mDirectControl;
5609 }
5610
5611 /* ignore calls made after #OnSessionEnd() is called */
5612 if (!directControl)
5613 rc = E_ACCESSDENIED;
5614 else
5615 rc = directControl->AccessGuestProperty(Bstr(aName).raw(), Bstr("").raw(), Bstr("").raw(),
5616 0 /* accessMode */,
5617 &bValue, aTimestamp, &bFlags);
5618
5619 aValue = bValue;
5620 aFlags = bFlags;
5621
5622 return rc;
5623}
5624#endif // VBOX_WITH_GUEST_PROPS
5625
5626HRESULT Machine::getGuestProperty(const com::Utf8Str &aName,
5627 com::Utf8Str &aValue,
5628 LONG64 *aTimestamp,
5629 com::Utf8Str &aFlags)
5630{
5631#ifndef VBOX_WITH_GUEST_PROPS
5632 ReturnComNotImplemented();
5633#else // VBOX_WITH_GUEST_PROPS
5634
5635 HRESULT rc = i_getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
5636
5637 if (rc == E_ACCESSDENIED)
5638 /* The VM is not running or the service is not (yet) accessible */
5639 rc = i_getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
5640 return rc;
5641#endif // VBOX_WITH_GUEST_PROPS
5642}
5643
5644HRESULT Machine::getGuestPropertyValue(const com::Utf8Str &aProperty, com::Utf8Str &aValue)
5645{
5646 LONG64 dummyTimestamp;
5647 com::Utf8Str dummyFlags;
5648 HRESULT rc = getGuestProperty(aProperty, aValue, &dummyTimestamp, dummyFlags);
5649 return rc;
5650
5651}
5652HRESULT Machine::getGuestPropertyTimestamp(const com::Utf8Str &aProperty, LONG64 *aValue)
5653{
5654 com::Utf8Str dummyFlags;
5655 com::Utf8Str dummyValue;
5656 HRESULT rc = getGuestProperty(aProperty, dummyValue, aValue, dummyFlags);
5657 return rc;
5658}
5659
5660#ifdef VBOX_WITH_GUEST_PROPS
5661/**
5662 * Set a guest property in VBoxSVC's internal structures.
5663 */
5664HRESULT Machine::i_setGuestPropertyToService(const com::Utf8Str &aName, const com::Utf8Str &aValue,
5665 const com::Utf8Str &aFlags, bool fDelete)
5666{
5667 using namespace guestProp;
5668
5669 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5670 HRESULT rc = S_OK;
5671
5672 rc = i_checkStateDependency(MutableOrSavedStateDep);
5673 if (FAILED(rc)) return rc;
5674
5675 try
5676 {
5677 uint32_t fFlags = NILFLAG;
5678 if (aFlags.length() && RT_FAILURE(validateFlags(aFlags.c_str(), &fFlags)))
5679 return setError(E_INVALIDARG, tr("Invalid guest property flag values: '%s'"), aFlags.c_str());
5680
5681 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
5682 if (it == mHWData->mGuestProperties.end())
5683 {
5684 if (!fDelete)
5685 {
5686 i_setModified(IsModified_MachineData);
5687 mHWData.backupEx();
5688
5689 RTTIMESPEC time;
5690 HWData::GuestProperty prop;
5691 prop.strValue = Bstr(aValue).raw();
5692 prop.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5693 prop.mFlags = fFlags;
5694 mHWData->mGuestProperties[aName] = prop;
5695 }
5696 }
5697 else
5698 {
5699 if (it->second.mFlags & (RDONLYHOST))
5700 {
5701 rc = setError(E_ACCESSDENIED, tr("The property '%s' cannot be changed by the host"), aName.c_str());
5702 }
5703 else
5704 {
5705 i_setModified(IsModified_MachineData);
5706 mHWData.backupEx();
5707
5708 /* The backupEx() operation invalidates our iterator,
5709 * so get a new one. */
5710 it = mHWData->mGuestProperties.find(aName);
5711 Assert(it != mHWData->mGuestProperties.end());
5712
5713 if (!fDelete)
5714 {
5715 RTTIMESPEC time;
5716 it->second.strValue = aValue;
5717 it->second.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5718 it->second.mFlags = fFlags;
5719 }
5720 else
5721 mHWData->mGuestProperties.erase(it);
5722 }
5723 }
5724
5725 if (SUCCEEDED(rc))
5726 {
5727 alock.release();
5728
5729 mParent->i_onGuestPropertyChange(mData->mUuid,
5730 Bstr(aName).raw(),
5731 Bstr(aValue).raw(),
5732 Bstr(aFlags).raw());
5733 }
5734 }
5735 catch (std::bad_alloc &)
5736 {
5737 rc = E_OUTOFMEMORY;
5738 }
5739
5740 return rc;
5741}
5742
5743/**
5744 * Set a property on the VM that that property belongs to.
5745 * @returns E_ACCESSDENIED if the VM process is not available or not
5746 * currently handling queries and the setting should then be done in
5747 * VBoxSVC.
5748 */
5749HRESULT Machine::i_setGuestPropertyToVM(const com::Utf8Str &aName, const com::Utf8Str &aValue,
5750 const com::Utf8Str &aFlags, bool fDelete)
5751{
5752 HRESULT rc;
5753
5754 try
5755 {
5756 ComPtr<IInternalSessionControl> directControl;
5757 {
5758 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5759 if (mData->mSession.mLockType == LockType_VM)
5760 directControl = mData->mSession.mDirectControl;
5761 }
5762
5763 BSTR dummy = NULL; /* will not be changed (setter) */
5764 LONG64 dummy64;
5765 if (!directControl)
5766 rc = E_ACCESSDENIED;
5767 else
5768 /** @todo Fix when adding DeleteGuestProperty(), see defect. */
5769 rc = directControl->AccessGuestProperty(Bstr(aName).raw(), Bstr(aValue).raw(), Bstr(aFlags).raw(),
5770 fDelete? 2: 1 /* accessMode */,
5771 &dummy, &dummy64, &dummy);
5772 }
5773 catch (std::bad_alloc &)
5774 {
5775 rc = E_OUTOFMEMORY;
5776 }
5777
5778 return rc;
5779}
5780#endif // VBOX_WITH_GUEST_PROPS
5781
5782HRESULT Machine::setGuestProperty(const com::Utf8Str &aProperty, const com::Utf8Str &aValue,
5783 const com::Utf8Str &aFlags)
5784{
5785#ifndef VBOX_WITH_GUEST_PROPS
5786 ReturnComNotImplemented();
5787#else // VBOX_WITH_GUEST_PROPS
5788 HRESULT rc = i_setGuestPropertyToVM(aProperty, aValue, aFlags, /* fDelete = */ false);
5789 if (rc == E_ACCESSDENIED)
5790 /* The VM is not running or the service is not (yet) accessible */
5791 rc = i_setGuestPropertyToService(aProperty, aValue, aFlags, /* fDelete = */ false);
5792 return rc;
5793#endif // VBOX_WITH_GUEST_PROPS
5794}
5795
5796HRESULT Machine::setGuestPropertyValue(const com::Utf8Str &aProperty, const com::Utf8Str &aValue)
5797{
5798 return setGuestProperty(aProperty, aValue, "");
5799}
5800
5801HRESULT Machine::deleteGuestProperty(const com::Utf8Str &aName)
5802{
5803#ifndef VBOX_WITH_GUEST_PROPS
5804 ReturnComNotImplemented();
5805#else // VBOX_WITH_GUEST_PROPS
5806 HRESULT rc = i_setGuestPropertyToVM(aName, "", "", /* fDelete = */ true);
5807 if (rc == E_ACCESSDENIED)
5808 /* The VM is not running or the service is not (yet) accessible */
5809 rc = i_setGuestPropertyToService(aName, "", "", /* fDelete = */ true);
5810 return rc;
5811#endif // VBOX_WITH_GUEST_PROPS
5812}
5813
5814#ifdef VBOX_WITH_GUEST_PROPS
5815/**
5816 * Enumerate the guest properties in VBoxSVC's internal structures.
5817 */
5818HRESULT Machine::i_enumerateGuestPropertiesInService(const com::Utf8Str &aPatterns,
5819 std::vector<com::Utf8Str> &aNames,
5820 std::vector<com::Utf8Str> &aValues,
5821 std::vector<LONG64> &aTimestamps,
5822 std::vector<com::Utf8Str> &aFlags)
5823{
5824 using namespace guestProp;
5825
5826 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5827 Utf8Str strPatterns(aPatterns);
5828
5829 HWData::GuestPropertyMap propMap;
5830
5831 /*
5832 * Look for matching patterns and build up a list.
5833 */
5834 HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.begin();
5835 while (it != mHWData->mGuestProperties.end())
5836 {
5837 if ( strPatterns.isEmpty()
5838 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5839 RTSTR_MAX,
5840 it->first.c_str(),
5841 RTSTR_MAX,
5842 NULL)
5843 )
5844 propMap.insert(*it);
5845 ++it;
5846 }
5847
5848 alock.release();
5849
5850 /*
5851 * And build up the arrays for returning the property information.
5852 */
5853 size_t cEntries = propMap.size();
5854
5855 aNames.resize(cEntries);
5856 aValues.resize(cEntries);
5857 aTimestamps.resize(cEntries);
5858 aFlags.resize(cEntries);
5859
5860 char szFlags[MAX_FLAGS_LEN + 1];
5861 size_t i= 0;
5862 for (it = propMap.begin(); it != propMap.end(); ++i, ++it)
5863 {
5864 aNames[i] = it->first;
5865 aValues[i] = it->second.strValue;
5866 aTimestamps[i] = it->second.mTimestamp;
5867 writeFlags(it->second.mFlags, szFlags);
5868 aFlags[i] = Utf8Str(szFlags);
5869 }
5870
5871 return S_OK;
5872}
5873
5874/**
5875 * Enumerate the properties managed by a VM.
5876 * @returns E_ACCESSDENIED if the VM process is not available or not
5877 * currently handling queries and the setting should then be done in
5878 * VBoxSVC.
5879 */
5880HRESULT Machine::i_enumerateGuestPropertiesOnVM(const com::Utf8Str &aPatterns,
5881 std::vector<com::Utf8Str> &aNames,
5882 std::vector<com::Utf8Str> &aValues,
5883 std::vector<LONG64> &aTimestamps,
5884 std::vector<com::Utf8Str> &aFlags)
5885{
5886 HRESULT rc;
5887 ComPtr<IInternalSessionControl> directControl;
5888 {
5889 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5890 if (mData->mSession.mLockType == LockType_VM)
5891 directControl = mData->mSession.mDirectControl;
5892 }
5893
5894 com::SafeArray<BSTR> bNames;
5895 com::SafeArray<BSTR> bValues;
5896 com::SafeArray<LONG64> bTimestamps;
5897 com::SafeArray<BSTR> bFlags;
5898
5899 if (!directControl)
5900 rc = E_ACCESSDENIED;
5901 else
5902 rc = directControl->EnumerateGuestProperties(Bstr(aPatterns).raw(),
5903 ComSafeArrayAsOutParam(bNames),
5904 ComSafeArrayAsOutParam(bValues),
5905 ComSafeArrayAsOutParam(bTimestamps),
5906 ComSafeArrayAsOutParam(bFlags));
5907 size_t i;
5908 aNames.resize(bNames.size());
5909 for (i = 0; i < bNames.size(); ++i)
5910 aNames[i] = Utf8Str(bNames[i]);
5911 aValues.resize(bValues.size());
5912 for (i = 0; i < bValues.size(); ++i)
5913 aValues[i] = Utf8Str(bValues[i]);
5914 aTimestamps.resize(bTimestamps.size());
5915 for (i = 0; i < bTimestamps.size(); ++i)
5916 aTimestamps[i] = bTimestamps[i];
5917 aFlags.resize(bFlags.size());
5918 for (i = 0; i < bFlags.size(); ++i)
5919 aFlags[i] = Utf8Str(bFlags[i]);
5920
5921 return rc;
5922}
5923#endif // VBOX_WITH_GUEST_PROPS
5924HRESULT Machine::enumerateGuestProperties(const com::Utf8Str &aPatterns,
5925 std::vector<com::Utf8Str> &aNames,
5926 std::vector<com::Utf8Str> &aValues,
5927 std::vector<LONG64> &aTimestamps,
5928 std::vector<com::Utf8Str> &aFlags)
5929{
5930#ifndef VBOX_WITH_GUEST_PROPS
5931 ReturnComNotImplemented();
5932#else // VBOX_WITH_GUEST_PROPS
5933
5934 HRESULT rc = i_enumerateGuestPropertiesOnVM(aPatterns, aNames, aValues, aTimestamps, aFlags);
5935
5936 if (rc == E_ACCESSDENIED)
5937 /* The VM is not running or the service is not (yet) accessible */
5938 rc = i_enumerateGuestPropertiesInService(aPatterns, aNames, aValues, aTimestamps, aFlags);
5939 return rc;
5940#endif // VBOX_WITH_GUEST_PROPS
5941}
5942
5943HRESULT Machine::getMediumAttachmentsOfController(const com::Utf8Str &aName,
5944 std::vector<ComPtr<IMediumAttachment> > &aMediumAttachments)
5945{
5946 MediaData::AttachmentList atts;
5947
5948 HRESULT rc = i_getMediumAttachmentsOfController(aName, atts);
5949 if (FAILED(rc)) return rc;
5950
5951 size_t i = 0;
5952 aMediumAttachments.resize(atts.size());
5953 for (MediaData::AttachmentList::iterator it = atts.begin(); it != atts.end(); ++it, ++i)
5954 (*it).queryInterfaceTo(aMediumAttachments[i].asOutParam());
5955
5956 return S_OK;
5957}
5958
5959HRESULT Machine::getMediumAttachment(const com::Utf8Str &aName,
5960 LONG aControllerPort,
5961 LONG aDevice,
5962 ComPtr<IMediumAttachment> &aAttachment)
5963{
5964 LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
5965 aName.c_str(), aControllerPort, aDevice));
5966
5967 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5968
5969 aAttachment = NULL;
5970
5971 ComObjPtr<MediumAttachment> pAttach = i_findAttachment(mMediaData->mAttachments,
5972 Bstr(aName).raw(),
5973 aControllerPort,
5974 aDevice);
5975 if (pAttach.isNull())
5976 return setError(VBOX_E_OBJECT_NOT_FOUND,
5977 tr("No storage device attached to device slot %d on port %d of controller '%s'"),
5978 aDevice, aControllerPort, aName.c_str());
5979
5980 pAttach.queryInterfaceTo(aAttachment.asOutParam());
5981
5982 return S_OK;
5983}
5984
5985
5986HRESULT Machine::addStorageController(const com::Utf8Str &aName,
5987 StorageBus_T aConnectionType,
5988 ComPtr<IStorageController> &aController)
5989{
5990 if ( (aConnectionType <= StorageBus_Null)
5991 || (aConnectionType > StorageBus_USB))
5992 return setError(E_INVALIDARG,
5993 tr("Invalid connection type: %d"),
5994 aConnectionType);
5995
5996 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5997
5998 HRESULT rc = i_checkStateDependency(MutableStateDep);
5999 if (FAILED(rc)) return rc;
6000
6001 /* try to find one with the name first. */
6002 ComObjPtr<StorageController> ctrl;
6003
6004 rc = i_getStorageControllerByName(aName, ctrl, false /* aSetError */);
6005 if (SUCCEEDED(rc))
6006 return setError(VBOX_E_OBJECT_IN_USE,
6007 tr("Storage controller named '%s' already exists"),
6008 aName.c_str());
6009
6010 ctrl.createObject();
6011
6012 /* get a new instance number for the storage controller */
6013 ULONG ulInstance = 0;
6014 bool fBootable = true;
6015 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6016 it != mStorageControllers->end();
6017 ++it)
6018 {
6019 if ((*it)->i_getStorageBus() == aConnectionType)
6020 {
6021 ULONG ulCurInst = (*it)->i_getInstance();
6022
6023 if (ulCurInst >= ulInstance)
6024 ulInstance = ulCurInst + 1;
6025
6026 /* Only one controller of each type can be marked as bootable. */
6027 if ((*it)->i_getBootable())
6028 fBootable = false;
6029 }
6030 }
6031
6032 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
6033 if (FAILED(rc)) return rc;
6034
6035 i_setModified(IsModified_Storage);
6036 mStorageControllers.backup();
6037 mStorageControllers->push_back(ctrl);
6038
6039 ctrl.queryInterfaceTo(aController.asOutParam());
6040
6041 /* inform the direct session if any */
6042 alock.release();
6043 i_onStorageControllerChange();
6044
6045 return S_OK;
6046}
6047
6048HRESULT Machine::getStorageControllerByName(const com::Utf8Str &aName,
6049 ComPtr<IStorageController> &aStorageController)
6050{
6051 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6052
6053 ComObjPtr<StorageController> ctrl;
6054
6055 HRESULT rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6056 if (SUCCEEDED(rc))
6057 ctrl.queryInterfaceTo(aStorageController.asOutParam());
6058
6059 return rc;
6060}
6061
6062HRESULT Machine::getStorageControllerByInstance(StorageBus_T aConnectionType,
6063 ULONG aInstance,
6064 ComPtr<IStorageController> &aStorageController)
6065{
6066 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6067
6068 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6069 it != mStorageControllers->end();
6070 ++it)
6071 {
6072 if ( (*it)->i_getStorageBus() == aConnectionType
6073 && (*it)->i_getInstance() == aInstance)
6074 {
6075 (*it).queryInterfaceTo(aStorageController.asOutParam());
6076 return S_OK;
6077 }
6078 }
6079
6080 return setError(VBOX_E_OBJECT_NOT_FOUND,
6081 tr("Could not find a storage controller with instance number '%lu'"),
6082 aInstance);
6083}
6084
6085HRESULT Machine::setStorageControllerBootable(const com::Utf8Str &aName, BOOL aBootable)
6086{
6087 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6088
6089 HRESULT rc = i_checkStateDependency(MutableStateDep);
6090 if (FAILED(rc)) return rc;
6091
6092 ComObjPtr<StorageController> ctrl;
6093
6094 rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6095 if (SUCCEEDED(rc))
6096 {
6097 /* Ensure that only one controller of each type is marked as bootable. */
6098 if (aBootable == TRUE)
6099 {
6100 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6101 it != mStorageControllers->end();
6102 ++it)
6103 {
6104 ComObjPtr<StorageController> aCtrl = (*it);
6105
6106 if ( (aCtrl->i_getName() != aName)
6107 && aCtrl->i_getBootable() == TRUE
6108 && aCtrl->i_getStorageBus() == ctrl->i_getStorageBus()
6109 && aCtrl->i_getControllerType() == ctrl->i_getControllerType())
6110 {
6111 aCtrl->i_setBootable(FALSE);
6112 break;
6113 }
6114 }
6115 }
6116
6117 if (SUCCEEDED(rc))
6118 {
6119 ctrl->i_setBootable(aBootable);
6120 i_setModified(IsModified_Storage);
6121 }
6122 }
6123
6124 if (SUCCEEDED(rc))
6125 {
6126 /* inform the direct session if any */
6127 alock.release();
6128 i_onStorageControllerChange();
6129 }
6130
6131 return rc;
6132}
6133
6134HRESULT Machine::removeStorageController(const com::Utf8Str &aName)
6135{
6136 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6137
6138 HRESULT rc = i_checkStateDependency(MutableStateDep);
6139 if (FAILED(rc)) return rc;
6140
6141 ComObjPtr<StorageController> ctrl;
6142 rc = i_getStorageControllerByName(aName, ctrl, true /* aSetError */);
6143 if (FAILED(rc)) return rc;
6144
6145 {
6146 /* find all attached devices to the appropriate storage controller and detach them all */
6147 // make a temporary list because detachDevice invalidates iterators into
6148 // mMediaData->mAttachments
6149 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
6150
6151 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
6152 it != llAttachments2.end();
6153 ++it)
6154 {
6155 MediumAttachment *pAttachTemp = *it;
6156
6157 AutoCaller localAutoCaller(pAttachTemp);
6158 if (FAILED(localAutoCaller.rc())) return localAutoCaller.rc();
6159
6160 AutoReadLock local_alock(pAttachTemp COMMA_LOCKVAL_SRC_POS);
6161
6162 if (pAttachTemp->i_getControllerName() == aName)
6163 {
6164 rc = i_detachDevice(pAttachTemp, alock, NULL);
6165 if (FAILED(rc)) return rc;
6166 }
6167 }
6168 }
6169
6170 /* We can remove it now. */
6171 i_setModified(IsModified_Storage);
6172 mStorageControllers.backup();
6173
6174 ctrl->i_unshare();
6175
6176 mStorageControllers->remove(ctrl);
6177
6178 /* inform the direct session if any */
6179 alock.release();
6180 i_onStorageControllerChange();
6181
6182 return S_OK;
6183}
6184
6185HRESULT Machine::addUSBController(const com::Utf8Str &aName, USBControllerType_T aType,
6186 ComPtr<IUSBController> &aController)
6187{
6188 if ( (aType <= USBControllerType_Null)
6189 || (aType >= USBControllerType_Last))
6190 return setError(E_INVALIDARG,
6191 tr("Invalid USB controller type: %d"),
6192 aType);
6193
6194 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6195
6196 HRESULT rc = i_checkStateDependency(MutableStateDep);
6197 if (FAILED(rc)) return rc;
6198
6199 /* try to find one with the same type first. */
6200 ComObjPtr<USBController> ctrl;
6201
6202 rc = i_getUSBControllerByName(aName, ctrl, false /* aSetError */);
6203 if (SUCCEEDED(rc))
6204 return setError(VBOX_E_OBJECT_IN_USE,
6205 tr("USB controller named '%s' already exists"),
6206 aName.c_str());
6207
6208 /* Check that we don't exceed the maximum number of USB controllers for the given type. */
6209 ULONG maxInstances;
6210 rc = mParent->i_getSystemProperties()->GetMaxInstancesOfUSBControllerType(mHWData->mChipsetType, aType, &maxInstances);
6211 if (FAILED(rc))
6212 return rc;
6213
6214 ULONG cInstances = i_getUSBControllerCountByType(aType);
6215 if (cInstances >= maxInstances)
6216 return setError(E_INVALIDARG,
6217 tr("Too many USB controllers of this type"));
6218
6219 ctrl.createObject();
6220
6221 rc = ctrl->init(this, aName, aType);
6222 if (FAILED(rc)) return rc;
6223
6224 i_setModified(IsModified_USB);
6225 mUSBControllers.backup();
6226 mUSBControllers->push_back(ctrl);
6227
6228 ctrl.queryInterfaceTo(aController.asOutParam());
6229
6230 /* inform the direct session if any */
6231 alock.release();
6232 i_onUSBControllerChange();
6233
6234 return S_OK;
6235}
6236
6237HRESULT Machine::getUSBControllerByName(const com::Utf8Str &aName, ComPtr<IUSBController> &aController)
6238{
6239 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6240
6241 ComObjPtr<USBController> ctrl;
6242
6243 HRESULT rc = i_getUSBControllerByName(aName, ctrl, true /* aSetError */);
6244 if (SUCCEEDED(rc))
6245 ctrl.queryInterfaceTo(aController.asOutParam());
6246
6247 return rc;
6248}
6249
6250HRESULT Machine::getUSBControllerCountByType(USBControllerType_T aType,
6251 ULONG *aControllers)
6252{
6253 if ( (aType <= USBControllerType_Null)
6254 || (aType >= USBControllerType_Last))
6255 return setError(E_INVALIDARG,
6256 tr("Invalid USB controller type: %d"),
6257 aType);
6258
6259 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6260
6261 ComObjPtr<USBController> ctrl;
6262
6263 *aControllers = i_getUSBControllerCountByType(aType);
6264
6265 return S_OK;
6266}
6267
6268HRESULT Machine::removeUSBController(const com::Utf8Str &aName)
6269{
6270
6271 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6272
6273 HRESULT rc = i_checkStateDependency(MutableStateDep);
6274 if (FAILED(rc)) return rc;
6275
6276 ComObjPtr<USBController> ctrl;
6277 rc = i_getUSBControllerByName(aName, ctrl, true /* aSetError */);
6278 if (FAILED(rc)) return rc;
6279
6280 i_setModified(IsModified_USB);
6281 mUSBControllers.backup();
6282
6283 ctrl->i_unshare();
6284
6285 mUSBControllers->remove(ctrl);
6286
6287 /* inform the direct session if any */
6288 alock.release();
6289 i_onUSBControllerChange();
6290
6291 return S_OK;
6292}
6293
6294HRESULT Machine::querySavedGuestScreenInfo(ULONG aScreenId,
6295 ULONG *aOriginX,
6296 ULONG *aOriginY,
6297 ULONG *aWidth,
6298 ULONG *aHeight,
6299 BOOL *aEnabled)
6300{
6301 uint32_t u32OriginX= 0;
6302 uint32_t u32OriginY= 0;
6303 uint32_t u32Width = 0;
6304 uint32_t u32Height = 0;
6305 uint16_t u16Flags = 0;
6306
6307 int vrc = readSavedGuestScreenInfo(mSSData->strStateFilePath, aScreenId,
6308 &u32OriginX, &u32OriginY, &u32Width, &u32Height, &u16Flags);
6309 if (RT_FAILURE(vrc))
6310 {
6311#ifdef RT_OS_WINDOWS
6312 /* HACK: GUI sets *pfEnabled to 'true' and expects it to stay so if the API fails.
6313 * This works with XPCOM. But Windows COM sets all output parameters to zero.
6314 * So just assign fEnable to TRUE again.
6315 * The right fix would be to change GUI API wrappers to make sure that parameters
6316 * are changed only if API succeeds.
6317 */
6318 *aEnabled = TRUE;
6319#endif
6320 return setError(VBOX_E_IPRT_ERROR,
6321 tr("Saved guest size is not available (%Rrc)"),
6322 vrc);
6323 }
6324
6325 *aOriginX = u32OriginX;
6326 *aOriginY = u32OriginY;
6327 *aWidth = u32Width;
6328 *aHeight = u32Height;
6329 *aEnabled = (u16Flags & VBVA_SCREEN_F_DISABLED) == 0;
6330
6331 return S_OK;
6332}
6333
6334HRESULT Machine::readSavedThumbnailToArray(ULONG aScreenId, BitmapFormat_T aBitmapFormat,
6335 ULONG *aWidth, ULONG *aHeight, std::vector<BYTE> &aData)
6336{
6337 if (aScreenId != 0)
6338 return E_NOTIMPL;
6339
6340 if ( aBitmapFormat != BitmapFormat_BGR0
6341 && aBitmapFormat != BitmapFormat_BGRA
6342 && aBitmapFormat != BitmapFormat_RGBA
6343 && aBitmapFormat != BitmapFormat_PNG)
6344 return setError(E_NOTIMPL,
6345 tr("Unsupported saved thumbnail format 0x%08X"), aBitmapFormat);
6346
6347 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6348
6349 uint8_t *pu8Data = NULL;
6350 uint32_t cbData = 0;
6351 uint32_t u32Width = 0;
6352 uint32_t u32Height = 0;
6353
6354 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6355
6356 if (RT_FAILURE(vrc))
6357 return setError(VBOX_E_IPRT_ERROR,
6358 tr("Saved thumbnail data is not available (%Rrc)"),
6359 vrc);
6360
6361 HRESULT hr = S_OK;
6362
6363 *aWidth = u32Width;
6364 *aHeight = u32Height;
6365
6366 if (cbData > 0)
6367 {
6368 /* Convert pixels to the format expected by the API caller. */
6369 if (aBitmapFormat == BitmapFormat_BGR0)
6370 {
6371 /* [0] B, [1] G, [2] R, [3] 0. */
6372 aData.resize(cbData);
6373 memcpy(&aData.front(), pu8Data, cbData);
6374 }
6375 else if (aBitmapFormat == BitmapFormat_BGRA)
6376 {
6377 /* [0] B, [1] G, [2] R, [3] A. */
6378 aData.resize(cbData);
6379 for (uint32_t i = 0; i < cbData; i += 4)
6380 {
6381 aData[i] = pu8Data[i];
6382 aData[i + 1] = pu8Data[i + 1];
6383 aData[i + 2] = pu8Data[i + 2];
6384 aData[i + 3] = 0xff;
6385 }
6386 }
6387 else if (aBitmapFormat == BitmapFormat_RGBA)
6388 {
6389 /* [0] R, [1] G, [2] B, [3] A. */
6390 aData.resize(cbData);
6391 for (uint32_t i = 0; i < cbData; i += 4)
6392 {
6393 aData[i] = pu8Data[i + 2];
6394 aData[i + 1] = pu8Data[i + 1];
6395 aData[i + 2] = pu8Data[i];
6396 aData[i + 3] = 0xff;
6397 }
6398 }
6399 else if (aBitmapFormat == BitmapFormat_PNG)
6400 {
6401 uint8_t *pu8PNG = NULL;
6402 uint32_t cbPNG = 0;
6403 uint32_t cxPNG = 0;
6404 uint32_t cyPNG = 0;
6405
6406 vrc = DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
6407
6408 if (RT_SUCCESS(vrc))
6409 {
6410 aData.resize(cbPNG);
6411 if (cbPNG)
6412 memcpy(&aData.front(), pu8PNG, cbPNG);
6413 }
6414 else
6415 hr = setError(VBOX_E_IPRT_ERROR,
6416 tr("Could not convert saved thumbnail to PNG (%Rrc)"),
6417 vrc);
6418
6419 RTMemFree(pu8PNG);
6420 }
6421 }
6422
6423 freeSavedDisplayScreenshot(pu8Data);
6424
6425 return hr;
6426}
6427
6428HRESULT Machine::querySavedScreenshotInfo(ULONG aScreenId,
6429 ULONG *aWidth,
6430 ULONG *aHeight,
6431 std::vector<BitmapFormat_T> &aBitmapFormats)
6432{
6433 if (aScreenId != 0)
6434 return E_NOTIMPL;
6435
6436 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6437
6438 uint8_t *pu8Data = NULL;
6439 uint32_t cbData = 0;
6440 uint32_t u32Width = 0;
6441 uint32_t u32Height = 0;
6442
6443 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6444
6445 if (RT_FAILURE(vrc))
6446 return setError(VBOX_E_IPRT_ERROR,
6447 tr("Saved screenshot data is not available (%Rrc)"),
6448 vrc);
6449
6450 *aWidth = u32Width;
6451 *aHeight = u32Height;
6452 aBitmapFormats.resize(1);
6453 aBitmapFormats[0] = BitmapFormat_PNG;
6454
6455 freeSavedDisplayScreenshot(pu8Data);
6456
6457 return S_OK;
6458}
6459
6460HRESULT Machine::readSavedScreenshotToArray(ULONG aScreenId,
6461 BitmapFormat_T aBitmapFormat,
6462 ULONG *aWidth,
6463 ULONG *aHeight,
6464 std::vector<BYTE> &aData)
6465{
6466 if (aScreenId != 0)
6467 return E_NOTIMPL;
6468
6469 if (aBitmapFormat != BitmapFormat_PNG)
6470 return E_NOTIMPL;
6471
6472 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6473
6474 uint8_t *pu8Data = NULL;
6475 uint32_t cbData = 0;
6476 uint32_t u32Width = 0;
6477 uint32_t u32Height = 0;
6478
6479 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6480
6481 if (RT_FAILURE(vrc))
6482 return setError(VBOX_E_IPRT_ERROR,
6483 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
6484 vrc);
6485
6486 *aWidth = u32Width;
6487 *aHeight = u32Height;
6488
6489 aData.resize(cbData);
6490 if (cbData)
6491 memcpy(&aData.front(), pu8Data, cbData);
6492
6493 freeSavedDisplayScreenshot(pu8Data);
6494
6495 return S_OK;
6496}
6497
6498HRESULT Machine::hotPlugCPU(ULONG aCpu)
6499{
6500 HRESULT rc = S_OK;
6501 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6502
6503 if (!mHWData->mCPUHotPlugEnabled)
6504 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6505
6506 if (aCpu >= mHWData->mCPUCount)
6507 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
6508
6509 if (mHWData->mCPUAttached[aCpu])
6510 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
6511
6512 alock.release();
6513 rc = i_onCPUChange(aCpu, false);
6514 alock.acquire();
6515 if (FAILED(rc)) return rc;
6516
6517 i_setModified(IsModified_MachineData);
6518 mHWData.backup();
6519 mHWData->mCPUAttached[aCpu] = true;
6520
6521 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
6522 if (Global::IsOnline(mData->mMachineState))
6523 i_saveSettings(NULL);
6524
6525 return S_OK;
6526}
6527
6528HRESULT Machine::hotUnplugCPU(ULONG aCpu)
6529{
6530 HRESULT rc = S_OK;
6531
6532 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6533
6534 if (!mHWData->mCPUHotPlugEnabled)
6535 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6536
6537 if (aCpu >= SchemaDefs::MaxCPUCount)
6538 return setError(E_INVALIDARG,
6539 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
6540 SchemaDefs::MaxCPUCount);
6541
6542 if (!mHWData->mCPUAttached[aCpu])
6543 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
6544
6545 /* CPU 0 can't be detached */
6546 if (aCpu == 0)
6547 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
6548
6549 alock.release();
6550 rc = i_onCPUChange(aCpu, true);
6551 alock.acquire();
6552 if (FAILED(rc)) return rc;
6553
6554 i_setModified(IsModified_MachineData);
6555 mHWData.backup();
6556 mHWData->mCPUAttached[aCpu] = false;
6557
6558 /** Save settings if online - @todo why is this required? -- @bugref{6818} */
6559 if (Global::IsOnline(mData->mMachineState))
6560 i_saveSettings(NULL);
6561
6562 return S_OK;
6563}
6564
6565HRESULT Machine::getCPUStatus(ULONG aCpu, BOOL *aAttached)
6566{
6567 *aAttached = false;
6568
6569 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6570
6571 /* If hotplug is enabled the CPU is always enabled. */
6572 if (!mHWData->mCPUHotPlugEnabled)
6573 {
6574 if (aCpu < mHWData->mCPUCount)
6575 *aAttached = true;
6576 }
6577 else
6578 {
6579 if (aCpu < SchemaDefs::MaxCPUCount)
6580 *aAttached = mHWData->mCPUAttached[aCpu];
6581 }
6582
6583 return S_OK;
6584}
6585
6586HRESULT Machine::queryLogFilename(ULONG aIdx, com::Utf8Str &aFilename)
6587{
6588 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6589
6590 Utf8Str log = i_getLogFilename(aIdx);
6591 if (!RTFileExists(log.c_str()))
6592 log.setNull();
6593 aFilename = log;
6594
6595 return S_OK;
6596}
6597
6598HRESULT Machine::readLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, std::vector<BYTE> &aData)
6599{
6600 if (aSize < 0)
6601 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
6602
6603 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6604
6605 HRESULT rc = S_OK;
6606 Utf8Str log = i_getLogFilename(aIdx);
6607
6608 /* do not unnecessarily hold the lock while doing something which does
6609 * not need the lock and potentially takes a long time. */
6610 alock.release();
6611
6612 /* Limit the chunk size to 32K for now, as that gives better performance
6613 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
6614 * One byte expands to approx. 25 bytes of breathtaking XML. */
6615 size_t cbData = (size_t)RT_MIN(aSize, 32768);
6616 aData.resize(cbData);
6617
6618 RTFILE LogFile;
6619 int vrc = RTFileOpen(&LogFile, log.c_str(),
6620 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
6621 if (RT_SUCCESS(vrc))
6622 {
6623 vrc = RTFileReadAt(LogFile, aOffset, cbData? &aData.front(): NULL, cbData, &cbData);
6624 if (RT_SUCCESS(vrc))
6625 aData.resize(cbData);
6626 else
6627 rc = setError(VBOX_E_IPRT_ERROR,
6628 tr("Could not read log file '%s' (%Rrc)"),
6629 log.c_str(), vrc);
6630 RTFileClose(LogFile);
6631 }
6632 else
6633 rc = setError(VBOX_E_IPRT_ERROR,
6634 tr("Could not open log file '%s' (%Rrc)"),
6635 log.c_str(), vrc);
6636
6637 if (FAILED(rc))
6638 aData.resize(0);
6639
6640 return rc;
6641}
6642
6643
6644/**
6645 * Currently this method doesn't attach device to the running VM,
6646 * just makes sure it's plugged on next VM start.
6647 */
6648HRESULT Machine::attachHostPCIDevice(LONG aHostAddress, LONG aDesiredGuestAddress, BOOL /* aTryToUnbind */)
6649{
6650 // lock scope
6651 {
6652 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6653
6654 HRESULT rc = i_checkStateDependency(MutableStateDep);
6655 if (FAILED(rc)) return rc;
6656
6657 ChipsetType_T aChipset = ChipsetType_PIIX3;
6658 COMGETTER(ChipsetType)(&aChipset);
6659
6660 if (aChipset != ChipsetType_ICH9)
6661 {
6662 return setError(E_INVALIDARG,
6663 tr("Host PCI attachment only supported with ICH9 chipset"));
6664 }
6665
6666 // check if device with this host PCI address already attached
6667 for (HWData::PCIDeviceAssignmentList::iterator it = mHWData->mPCIDeviceAssignments.begin();
6668 it != mHWData->mPCIDeviceAssignments.end();
6669 ++it)
6670 {
6671 LONG iHostAddress = -1;
6672 ComPtr<PCIDeviceAttachment> pAttach;
6673 pAttach = *it;
6674 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6675 if (iHostAddress == aHostAddress)
6676 return setError(E_INVALIDARG,
6677 tr("Device with host PCI address already attached to this VM"));
6678 }
6679
6680 ComObjPtr<PCIDeviceAttachment> pda;
6681 char name[32];
6682
6683 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (aHostAddress>>8) & 0xff,
6684 (aHostAddress & 0xf8) >> 3, aHostAddress & 7);
6685 Bstr bname(name);
6686 pda.createObject();
6687 pda->init(this, bname, aHostAddress, aDesiredGuestAddress, TRUE);
6688 i_setModified(IsModified_MachineData);
6689 mHWData.backup();
6690 mHWData->mPCIDeviceAssignments.push_back(pda);
6691 }
6692
6693 return S_OK;
6694}
6695
6696/**
6697 * Currently this method doesn't detach device from the running VM,
6698 * just makes sure it's not plugged on next VM start.
6699 */
6700HRESULT Machine::detachHostPCIDevice(LONG aHostAddress)
6701{
6702 ComObjPtr<PCIDeviceAttachment> pAttach;
6703 bool fRemoved = false;
6704 HRESULT rc;
6705
6706 // lock scope
6707 {
6708 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6709
6710 rc = i_checkStateDependency(MutableStateDep);
6711 if (FAILED(rc)) return rc;
6712
6713 for (HWData::PCIDeviceAssignmentList::iterator it = mHWData->mPCIDeviceAssignments.begin();
6714 it != mHWData->mPCIDeviceAssignments.end();
6715 ++it)
6716 {
6717 LONG iHostAddress = -1;
6718 pAttach = *it;
6719 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6720 if (iHostAddress != -1 && iHostAddress == aHostAddress)
6721 {
6722 i_setModified(IsModified_MachineData);
6723 mHWData.backup();
6724 mHWData->mPCIDeviceAssignments.remove(pAttach);
6725 fRemoved = true;
6726 break;
6727 }
6728 }
6729 }
6730
6731
6732 /* Fire event outside of the lock */
6733 if (fRemoved)
6734 {
6735 Assert(!pAttach.isNull());
6736 ComPtr<IEventSource> es;
6737 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
6738 Assert(SUCCEEDED(rc));
6739 Bstr mid;
6740 rc = this->COMGETTER(Id)(mid.asOutParam());
6741 Assert(SUCCEEDED(rc));
6742 fireHostPCIDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
6743 }
6744
6745 return fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
6746 tr("No host PCI device %08x attached"),
6747 aHostAddress
6748 );
6749}
6750
6751HRESULT Machine::getPCIDeviceAssignments(std::vector<ComPtr<IPCIDeviceAttachment> > &aPCIDeviceAssignments)
6752{
6753 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6754
6755 aPCIDeviceAssignments.resize(mHWData->mPCIDeviceAssignments.size());
6756
6757 size_t i = 0;
6758 for (std::list<ComObjPtr<PCIDeviceAttachment> >::const_iterator it = mHWData->mPCIDeviceAssignments.begin();
6759 it != mHWData->mPCIDeviceAssignments.end();
6760 ++i, ++it)
6761 (*it).queryInterfaceTo(aPCIDeviceAssignments[i].asOutParam());
6762
6763 return S_OK;
6764}
6765
6766HRESULT Machine::getBandwidthControl(ComPtr<IBandwidthControl> &aBandwidthControl)
6767{
6768 mBandwidthControl.queryInterfaceTo(aBandwidthControl.asOutParam());
6769
6770 return S_OK;
6771}
6772
6773HRESULT Machine::getTracingEnabled(BOOL *aTracingEnabled)
6774{
6775 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6776
6777 *aTracingEnabled = mHWData->mDebugging.fTracingEnabled;
6778
6779 return S_OK;
6780}
6781
6782HRESULT Machine::setTracingEnabled(BOOL aTracingEnabled)
6783{
6784 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6785 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6786 if (SUCCEEDED(hrc))
6787 {
6788 hrc = mHWData.backupEx();
6789 if (SUCCEEDED(hrc))
6790 {
6791 i_setModified(IsModified_MachineData);
6792 mHWData->mDebugging.fTracingEnabled = aTracingEnabled != FALSE;
6793 }
6794 }
6795 return hrc;
6796}
6797
6798HRESULT Machine::getTracingConfig(com::Utf8Str &aTracingConfig)
6799{
6800 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6801 aTracingConfig = mHWData->mDebugging.strTracingConfig;
6802 return S_OK;
6803}
6804
6805HRESULT Machine::setTracingConfig(const com::Utf8Str &aTracingConfig)
6806{
6807 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6808 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6809 if (SUCCEEDED(hrc))
6810 {
6811 hrc = mHWData.backupEx();
6812 if (SUCCEEDED(hrc))
6813 {
6814 mHWData->mDebugging.strTracingConfig = aTracingConfig;
6815 if (SUCCEEDED(hrc))
6816 i_setModified(IsModified_MachineData);
6817 }
6818 }
6819 return hrc;
6820}
6821
6822HRESULT Machine::getAllowTracingToAccessVM(BOOL *aAllowTracingToAccessVM)
6823{
6824 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6825
6826 *aAllowTracingToAccessVM = mHWData->mDebugging.fAllowTracingToAccessVM;
6827
6828 return S_OK;
6829}
6830
6831HRESULT Machine::setAllowTracingToAccessVM(BOOL aAllowTracingToAccessVM)
6832{
6833 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6834 HRESULT hrc = i_checkStateDependency(MutableStateDep);
6835 if (SUCCEEDED(hrc))
6836 {
6837 hrc = mHWData.backupEx();
6838 if (SUCCEEDED(hrc))
6839 {
6840 i_setModified(IsModified_MachineData);
6841 mHWData->mDebugging.fAllowTracingToAccessVM = aAllowTracingToAccessVM != FALSE;
6842 }
6843 }
6844 return hrc;
6845}
6846
6847HRESULT Machine::getAutostartEnabled(BOOL *aAutostartEnabled)
6848{
6849 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6850
6851 *aAutostartEnabled = mHWData->mAutostart.fAutostartEnabled;
6852
6853 return S_OK;
6854}
6855
6856HRESULT Machine::setAutostartEnabled(BOOL aAutostartEnabled)
6857{
6858 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6859
6860 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
6861 if ( SUCCEEDED(hrc)
6862 && mHWData->mAutostart.fAutostartEnabled != !!aAutostartEnabled)
6863 {
6864 AutostartDb *autostartDb = mParent->i_getAutostartDb();
6865 int vrc;
6866
6867 if (aAutostartEnabled)
6868 vrc = autostartDb->addAutostartVM(mUserData->s.strName.c_str());
6869 else
6870 vrc = autostartDb->removeAutostartVM(mUserData->s.strName.c_str());
6871
6872 if (RT_SUCCESS(vrc))
6873 {
6874 hrc = mHWData.backupEx();
6875 if (SUCCEEDED(hrc))
6876 {
6877 i_setModified(IsModified_MachineData);
6878 mHWData->mAutostart.fAutostartEnabled = aAutostartEnabled != FALSE;
6879 }
6880 }
6881 else if (vrc == VERR_NOT_SUPPORTED)
6882 hrc = setError(VBOX_E_NOT_SUPPORTED,
6883 tr("The VM autostart feature is not supported on this platform"));
6884 else if (vrc == VERR_PATH_NOT_FOUND)
6885 hrc = setError(E_FAIL,
6886 tr("The path to the autostart database is not set"));
6887 else
6888 hrc = setError(E_UNEXPECTED,
6889 tr("%s machine '%s' to the autostart database failed with %Rrc"),
6890 aAutostartEnabled ? "Adding" : "Removing",
6891 mUserData->s.strName.c_str(), vrc);
6892 }
6893 return hrc;
6894}
6895
6896HRESULT Machine::getAutostartDelay(ULONG *aAutostartDelay)
6897{
6898 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6899
6900 *aAutostartDelay = mHWData->mAutostart.uAutostartDelay;
6901
6902 return S_OK;
6903}
6904
6905HRESULT Machine::setAutostartDelay(ULONG aAutostartDelay)
6906{
6907 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6908 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
6909 if (SUCCEEDED(hrc))
6910 {
6911 hrc = mHWData.backupEx();
6912 if (SUCCEEDED(hrc))
6913 {
6914 i_setModified(IsModified_MachineData);
6915 mHWData->mAutostart.uAutostartDelay = aAutostartDelay;
6916 }
6917 }
6918 return hrc;
6919}
6920
6921HRESULT Machine::getAutostopType(AutostopType_T *aAutostopType)
6922{
6923 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6924
6925 *aAutostopType = mHWData->mAutostart.enmAutostopType;
6926
6927 return S_OK;
6928}
6929
6930HRESULT Machine::setAutostopType(AutostopType_T aAutostopType)
6931{
6932 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6933 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
6934 if ( SUCCEEDED(hrc)
6935 && mHWData->mAutostart.enmAutostopType != aAutostopType)
6936 {
6937 AutostartDb *autostartDb = mParent->i_getAutostartDb();
6938 int vrc;
6939
6940 if (aAutostopType != AutostopType_Disabled)
6941 vrc = autostartDb->addAutostopVM(mUserData->s.strName.c_str());
6942 else
6943 vrc = autostartDb->removeAutostopVM(mUserData->s.strName.c_str());
6944
6945 if (RT_SUCCESS(vrc))
6946 {
6947 hrc = mHWData.backupEx();
6948 if (SUCCEEDED(hrc))
6949 {
6950 i_setModified(IsModified_MachineData);
6951 mHWData->mAutostart.enmAutostopType = aAutostopType;
6952 }
6953 }
6954 else if (vrc == VERR_NOT_SUPPORTED)
6955 hrc = setError(VBOX_E_NOT_SUPPORTED,
6956 tr("The VM autostop feature is not supported on this platform"));
6957 else if (vrc == VERR_PATH_NOT_FOUND)
6958 hrc = setError(E_FAIL,
6959 tr("The path to the autostart database is not set"));
6960 else
6961 hrc = setError(E_UNEXPECTED,
6962 tr("%s machine '%s' to the autostop database failed with %Rrc"),
6963 aAutostopType != AutostopType_Disabled ? "Adding" : "Removing",
6964 mUserData->s.strName.c_str(), vrc);
6965 }
6966 return hrc;
6967}
6968
6969HRESULT Machine::getDefaultFrontend(com::Utf8Str &aDefaultFrontend)
6970{
6971 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6972
6973 aDefaultFrontend = mHWData->mDefaultFrontend;
6974
6975 return S_OK;
6976}
6977
6978HRESULT Machine::setDefaultFrontend(const com::Utf8Str &aDefaultFrontend)
6979{
6980 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6981 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
6982 if (SUCCEEDED(hrc))
6983 {
6984 hrc = mHWData.backupEx();
6985 if (SUCCEEDED(hrc))
6986 {
6987 i_setModified(IsModified_MachineData);
6988 mHWData->mDefaultFrontend = aDefaultFrontend;
6989 }
6990 }
6991 return hrc;
6992}
6993
6994HRESULT Machine::getIcon(std::vector<BYTE> &aIcon)
6995{
6996 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6997 size_t cbIcon = mUserData->mIcon.size();
6998 aIcon.resize(cbIcon);
6999 if (cbIcon)
7000 memcpy(&aIcon.front(), &mUserData->mIcon[0], cbIcon);
7001 return S_OK;
7002}
7003
7004HRESULT Machine::setIcon(const std::vector<BYTE> &aIcon)
7005{
7006 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7007 HRESULT hrc = i_checkStateDependency(MutableOrSavedStateDep);
7008 if (SUCCEEDED(hrc))
7009 {
7010 i_setModified(IsModified_MachineData);
7011 mUserData.backup();
7012 size_t cbIcon = aIcon.size();
7013 mUserData->mIcon.resize(cbIcon);
7014 if (cbIcon)
7015 memcpy(&mUserData->mIcon[0], &aIcon.front(), cbIcon);
7016 }
7017 return hrc;
7018}
7019
7020HRESULT Machine::getUSBProxyAvailable(BOOL *aUSBProxyAvailable)
7021{
7022#ifdef VBOX_WITH_USB
7023 *aUSBProxyAvailable = true;
7024#else
7025 *aUSBProxyAvailable = false;
7026#endif
7027 return S_OK;
7028}
7029
7030HRESULT Machine::getVMProcessPriority(com::Utf8Str &aVMProcessPriority)
7031{
7032 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7033
7034 aVMProcessPriority = mUserData->s.strVMPriority;
7035
7036 return S_OK;
7037}
7038
7039HRESULT Machine::setVMProcessPriority(const com::Utf8Str &aVMProcessPriority)
7040{
7041 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7042 HRESULT hrc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
7043 if (SUCCEEDED(hrc))
7044 {
7045 /** @todo r=klaus: currently this is marked as not implemented, as
7046 * the code for setting the priority of the process is not there
7047 * (neither when starting the VM nor at runtime). */
7048 ReturnComNotImplemented();
7049 hrc = mUserData.backupEx();
7050 if (SUCCEEDED(hrc))
7051 {
7052 i_setModified(IsModified_MachineData);
7053 mUserData->s.strVMPriority = aVMProcessPriority;
7054 }
7055 }
7056 return hrc;
7057}
7058
7059HRESULT Machine::cloneTo(const ComPtr<IMachine> &aTarget, CloneMode_T aMode, const std::vector<CloneOptions_T> &aOptions,
7060 ComPtr<IProgress> &aProgress)
7061{
7062 ComObjPtr<Progress> pP;
7063 Progress *ppP = pP;
7064 IProgress *iP = static_cast<IProgress *>(ppP);
7065 IProgress **pProgress = &iP;
7066
7067 IMachine *pTarget = aTarget;
7068
7069 /* Convert the options. */
7070 RTCList<CloneOptions_T> optList;
7071 if (aOptions.size())
7072 for (size_t i = 0; i < aOptions.size(); ++i)
7073 optList.append(aOptions[i]);
7074
7075 if (optList.contains(CloneOptions_Link))
7076 {
7077 if (!i_isSnapshotMachine())
7078 return setError(E_INVALIDARG,
7079 tr("Linked clone can only be created from a snapshot"));
7080 if (aMode != CloneMode_MachineState)
7081 return setError(E_INVALIDARG,
7082 tr("Linked clone can only be created for a single machine state"));
7083 }
7084 AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_INVALIDARG);
7085
7086 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), aMode, optList);
7087
7088 HRESULT rc = pWorker->start(pProgress);
7089
7090 pP = static_cast<Progress *>(*pProgress);
7091 pP.queryInterfaceTo(aProgress.asOutParam());
7092
7093 return rc;
7094
7095}
7096
7097HRESULT Machine::saveState(ComPtr<IProgress> &aProgress)
7098{
7099 NOREF(aProgress);
7100 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7101
7102 // This check should always fail.
7103 HRESULT rc = i_checkStateDependency(MutableStateDep);
7104 if (FAILED(rc)) return rc;
7105
7106 AssertFailedReturn(E_NOTIMPL);
7107}
7108
7109HRESULT Machine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
7110{
7111 NOREF(aSavedStateFile);
7112 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7113
7114 // This check should always fail.
7115 HRESULT rc = i_checkStateDependency(MutableStateDep);
7116 if (FAILED(rc)) return rc;
7117
7118 AssertFailedReturn(E_NOTIMPL);
7119}
7120
7121HRESULT Machine::discardSavedState(BOOL aFRemoveFile)
7122{
7123 NOREF(aFRemoveFile);
7124 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7125
7126 // This check should always fail.
7127 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
7128 if (FAILED(rc)) return rc;
7129
7130 AssertFailedReturn(E_NOTIMPL);
7131}
7132
7133// public methods for internal purposes
7134/////////////////////////////////////////////////////////////////////////////
7135
7136/**
7137 * Adds the given IsModified_* flag to the dirty flags of the machine.
7138 * This must be called either during i_loadSettings or under the machine write lock.
7139 * @param fl
7140 */
7141void Machine::i_setModified(uint32_t fl, bool fAllowStateModification /* = true */)
7142{
7143 mData->flModifications |= fl;
7144 if (fAllowStateModification && i_isStateModificationAllowed())
7145 mData->mCurrentStateModified = true;
7146}
7147
7148/**
7149 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
7150 * care of the write locking.
7151 *
7152 * @param fModifications The flag to add.
7153 */
7154void Machine::i_setModifiedLock(uint32_t fModification, bool fAllowStateModification /* = true */)
7155{
7156 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7157 i_setModified(fModification, fAllowStateModification);
7158}
7159
7160/**
7161 * Saves the registry entry of this machine to the given configuration node.
7162 *
7163 * @param aEntryNode Node to save the registry entry to.
7164 *
7165 * @note locks this object for reading.
7166 */
7167HRESULT Machine::i_saveRegistryEntry(settings::MachineRegistryEntry &data)
7168{
7169 AutoLimitedCaller autoCaller(this);
7170 AssertComRCReturnRC(autoCaller.rc());
7171
7172 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7173
7174 data.uuid = mData->mUuid;
7175 data.strSettingsFile = mData->m_strConfigFile;
7176
7177 return S_OK;
7178}
7179
7180/**
7181 * Calculates the absolute path of the given path taking the directory of the
7182 * machine settings file as the current directory.
7183 *
7184 * @param aPath Path to calculate the absolute path for.
7185 * @param aResult Where to put the result (used only on success, can be the
7186 * same Utf8Str instance as passed in @a aPath).
7187 * @return IPRT result.
7188 *
7189 * @note Locks this object for reading.
7190 */
7191int Machine::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
7192{
7193 AutoCaller autoCaller(this);
7194 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7195
7196 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7197
7198 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
7199
7200 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
7201
7202 strSettingsDir.stripFilename();
7203 char folder[RTPATH_MAX];
7204 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
7205 if (RT_SUCCESS(vrc))
7206 aResult = folder;
7207
7208 return vrc;
7209}
7210
7211/**
7212 * Copies strSource to strTarget, making it relative to the machine folder
7213 * if it is a subdirectory thereof, or simply copying it otherwise.
7214 *
7215 * @param strSource Path to evaluate and copy.
7216 * @param strTarget Buffer to receive target path.
7217 *
7218 * @note Locks this object for reading.
7219 */
7220void Machine::i_copyPathRelativeToMachine(const Utf8Str &strSource,
7221 Utf8Str &strTarget)
7222{
7223 AutoCaller autoCaller(this);
7224 AssertComRCReturn(autoCaller.rc(), (void)0);
7225
7226 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7227
7228 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
7229 // use strTarget as a temporary buffer to hold the machine settings dir
7230 strTarget = mData->m_strConfigFileFull;
7231 strTarget.stripFilename();
7232 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
7233 {
7234 // is relative: then append what's left
7235 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
7236 // for empty paths (only possible for subdirs) use "." to avoid
7237 // triggering default settings for not present config attributes.
7238 if (strTarget.isEmpty())
7239 strTarget = ".";
7240 }
7241 else
7242 // is not relative: then overwrite
7243 strTarget = strSource;
7244}
7245
7246/**
7247 * Returns the full path to the machine's log folder in the
7248 * \a aLogFolder argument.
7249 */
7250void Machine::i_getLogFolder(Utf8Str &aLogFolder)
7251{
7252 AutoCaller autoCaller(this);
7253 AssertComRCReturnVoid(autoCaller.rc());
7254
7255 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7256
7257 char szTmp[RTPATH_MAX];
7258 int vrc = RTEnvGetEx(RTENV_DEFAULT, "VBOX_USER_VMLOGDIR", szTmp, sizeof(szTmp), NULL);
7259 if (RT_SUCCESS(vrc))
7260 {
7261 if (szTmp[0] && !mUserData.isNull())
7262 {
7263 char szTmp2[RTPATH_MAX];
7264 vrc = RTPathAbs(szTmp, szTmp2, sizeof(szTmp2));
7265 if (RT_SUCCESS(vrc))
7266 aLogFolder = BstrFmt("%s%c%s",
7267 szTmp2,
7268 RTPATH_DELIMITER,
7269 mUserData->s.strName.c_str()); // path/to/logfolder/vmname
7270 }
7271 else
7272 vrc = VERR_PATH_IS_RELATIVE;
7273 }
7274
7275 if (RT_FAILURE(vrc))
7276 {
7277 // fallback if VBOX_USER_LOGHOME is not set or invalid
7278 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7279 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
7280 aLogFolder.append(RTPATH_DELIMITER);
7281 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
7282 }
7283}
7284
7285/**
7286 * Returns the full path to the machine's log file for an given index.
7287 */
7288Utf8Str Machine::i_getLogFilename(ULONG idx)
7289{
7290 Utf8Str logFolder;
7291 getLogFolder(logFolder);
7292 Assert(logFolder.length());
7293
7294 Utf8Str log;
7295 if (idx == 0)
7296 log = Utf8StrFmt("%s%cVBox.log", logFolder.c_str(), RTPATH_DELIMITER);
7297#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7298 else if (idx == 1)
7299 log = Utf8StrFmt("%s%cVBoxHardening.log", logFolder.c_str(), RTPATH_DELIMITER);
7300 else
7301 log = Utf8StrFmt("%s%cVBox.log.%u", logFolder.c_str(), RTPATH_DELIMITER, idx - 1);
7302#else
7303 else
7304 log = Utf8StrFmt("%s%cVBox.log.%u", logFolder.c_str(), RTPATH_DELIMITER, idx);
7305#endif
7306 return log;
7307}
7308
7309/**
7310 * Returns the full path to the machine's hardened log file.
7311 */
7312Utf8Str Machine::i_getHardeningLogFilename(void)
7313{
7314 Utf8Str strFilename;
7315 getLogFolder(strFilename);
7316 Assert(strFilename.length());
7317 strFilename.append(RTPATH_SLASH_STR "VBoxHardening.log");
7318 return strFilename;
7319}
7320
7321
7322/**
7323 * Composes a unique saved state filename based on the current system time. The filename is
7324 * granular to the second so this will work so long as no more than one snapshot is taken on
7325 * a machine per second.
7326 *
7327 * Before version 4.1, we used this formula for saved state files:
7328 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
7329 * which no longer works because saved state files can now be shared between the saved state of the
7330 * "saved" machine and an online snapshot, and the following would cause problems:
7331 * 1) save machine
7332 * 2) create online snapshot from that machine state --> reusing saved state file
7333 * 3) save machine again --> filename would be reused, breaking the online snapshot
7334 *
7335 * So instead we now use a timestamp.
7336 *
7337 * @param str
7338 */
7339
7340void Machine::i_composeSavedStateFilename(Utf8Str &strStateFilePath)
7341{
7342 AutoCaller autoCaller(this);
7343 AssertComRCReturnVoid(autoCaller.rc());
7344
7345 {
7346 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7347 i_calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
7348 }
7349
7350 RTTIMESPEC ts;
7351 RTTimeNow(&ts);
7352 RTTIME time;
7353 RTTimeExplode(&time, &ts);
7354
7355 strStateFilePath += RTPATH_DELIMITER;
7356 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
7357 time.i32Year, time.u8Month, time.u8MonthDay,
7358 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
7359}
7360
7361/**
7362 * Returns the full path to the default video capture file.
7363 */
7364void Machine::i_getDefaultVideoCaptureFile(Utf8Str &strFile)
7365{
7366 AutoCaller autoCaller(this);
7367 AssertComRCReturnVoid(autoCaller.rc());
7368
7369 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7370
7371 strFile = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7372 strFile.stripSuffix(); // path/to/machinesfolder/vmname/vmname
7373 strFile.append(".webm"); // path/to/machinesfolder/vmname/vmname.webm
7374}
7375
7376/**
7377 * Returns whether at least one USB controller is present for the VM.
7378 */
7379bool Machine::i_isUSBControllerPresent()
7380{
7381 AutoCaller autoCaller(this);
7382 AssertComRCReturn(autoCaller.rc(), false);
7383
7384 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7385
7386 return (mUSBControllers->size() > 0);
7387}
7388
7389/**
7390 * @note Locks this object for writing, calls the client process
7391 * (inside the lock).
7392 */
7393HRESULT Machine::i_launchVMProcess(IInternalSessionControl *aControl,
7394 const Utf8Str &strFrontend,
7395 const Utf8Str &strEnvironment,
7396 ProgressProxy *aProgress)
7397{
7398 LogFlowThisFuncEnter();
7399
7400 AssertReturn(aControl, E_FAIL);
7401 AssertReturn(aProgress, E_FAIL);
7402 AssertReturn(!strFrontend.isEmpty(), E_FAIL);
7403
7404 AutoCaller autoCaller(this);
7405 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7406
7407 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7408
7409 if (!mData->mRegistered)
7410 return setError(E_UNEXPECTED,
7411 tr("The machine '%s' is not registered"),
7412 mUserData->s.strName.c_str());
7413
7414 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
7415
7416 /* The process started when launching a VM with separate UI/VM processes is always
7417 * the UI process, i.e. needs special handling as it won't claim the session. */
7418 bool fSeparate = strFrontend.endsWith("separate", Utf8Str::CaseInsensitive);
7419
7420 if (fSeparate)
7421 {
7422 if (mData->mSession.mState != SessionState_Unlocked && mData->mSession.mName != "headless")
7423 return setError(VBOX_E_INVALID_OBJECT_STATE,
7424 tr("The machine '%s' is in a state which is incompatible with launching a separate UI process"),
7425 mUserData->s.strName.c_str());
7426 }
7427 else
7428 {
7429 if ( mData->mSession.mState == SessionState_Locked
7430 || mData->mSession.mState == SessionState_Spawning
7431 || mData->mSession.mState == SessionState_Unlocking)
7432 return setError(VBOX_E_INVALID_OBJECT_STATE,
7433 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
7434 mUserData->s.strName.c_str());
7435
7436 /* may not be busy */
7437 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
7438 }
7439
7440 /* get the path to the executable */
7441 char szPath[RTPATH_MAX];
7442 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
7443 size_t cchBufLeft = strlen(szPath);
7444 szPath[cchBufLeft++] = RTPATH_DELIMITER;
7445 szPath[cchBufLeft] = 0;
7446 char *pszNamePart = szPath + cchBufLeft;
7447 cchBufLeft = sizeof(szPath) - cchBufLeft;
7448
7449 int vrc = VINF_SUCCESS;
7450 RTPROCESS pid = NIL_RTPROCESS;
7451
7452 RTENV env = RTENV_DEFAULT;
7453
7454 if (!strEnvironment.isEmpty())
7455 {
7456 char *newEnvStr = NULL;
7457
7458 do
7459 {
7460 /* clone the current environment */
7461 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
7462 AssertRCBreakStmt(vrc2, vrc = vrc2);
7463
7464 newEnvStr = RTStrDup(strEnvironment.c_str());
7465 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
7466
7467 /* put new variables to the environment
7468 * (ignore empty variable names here since RTEnv API
7469 * intentionally doesn't do that) */
7470 char *var = newEnvStr;
7471 for (char *p = newEnvStr; *p; ++p)
7472 {
7473 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
7474 {
7475 *p = '\0';
7476 if (*var)
7477 {
7478 char *val = strchr(var, '=');
7479 if (val)
7480 {
7481 *val++ = '\0';
7482 vrc2 = RTEnvSetEx(env, var, val);
7483 }
7484 else
7485 vrc2 = RTEnvUnsetEx(env, var);
7486 if (RT_FAILURE(vrc2))
7487 break;
7488 }
7489 var = p + 1;
7490 }
7491 }
7492 if (RT_SUCCESS(vrc2) && *var)
7493 vrc2 = RTEnvPutEx(env, var);
7494
7495 AssertRCBreakStmt(vrc2, vrc = vrc2);
7496 }
7497 while (0);
7498
7499 if (newEnvStr != NULL)
7500 RTStrFree(newEnvStr);
7501 }
7502
7503 /* Hardening logging */
7504#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7505 Utf8Str strSupHardeningLogArg("--sup-hardening-log=");
7506 {
7507 Utf8Str strHardeningLogFile = i_getHardeningLogFilename();
7508 int vrc2 = RTFileDelete(strHardeningLogFile.c_str());
7509 if (vrc2 == VERR_PATH_NOT_FOUND || vrc2 == VERR_FILE_NOT_FOUND)
7510 {
7511 Utf8Str strStartupLogDir = strHardeningLogFile;
7512 strStartupLogDir.stripFilename();
7513 RTDirCreateFullPath(strStartupLogDir.c_str(), 0755); /** @todo add a variant for creating the path to a
7514 file without stripping the file. */
7515 }
7516 strSupHardeningLogArg.append(strHardeningLogFile);
7517
7518 /* Remove legacy log filename to avoid confusion. */
7519 Utf8Str strOldStartupLogFile;
7520 getLogFolder(strOldStartupLogFile);
7521 strOldStartupLogFile.append(RTPATH_SLASH_STR "VBoxStartup.log");
7522 RTFileDelete(strOldStartupLogFile.c_str());
7523 }
7524 const char *pszSupHardeningLogArg = strSupHardeningLogArg.c_str();
7525#else
7526 const char *pszSupHardeningLogArg = NULL;
7527#endif
7528
7529 Utf8Str strCanonicalName;
7530
7531#ifdef VBOX_WITH_QTGUI
7532 if ( !strFrontend.compare("gui", Utf8Str::CaseInsensitive)
7533 || !strFrontend.compare("GUI/Qt", Utf8Str::CaseInsensitive)
7534 || !strFrontend.compare("separate", Utf8Str::CaseInsensitive)
7535 || !strFrontend.compare("gui/separate", Utf8Str::CaseInsensitive)
7536 || !strFrontend.compare("GUI/Qt/separate", Utf8Str::CaseInsensitive))
7537 {
7538 strCanonicalName = "GUI/Qt";
7539# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
7540 /* Modify the base path so that we don't need to use ".." below. */
7541 RTPathStripTrailingSlash(szPath);
7542 RTPathStripFilename(szPath);
7543 cchBufLeft = strlen(szPath);
7544 pszNamePart = szPath + cchBufLeft;
7545 cchBufLeft = sizeof(szPath) - cchBufLeft;
7546
7547# define OSX_APP_NAME "VirtualBoxVM"
7548# define OSX_APP_PATH_FMT "/Resources/%s.app/Contents/MacOS/VirtualBoxVM"
7549
7550 Utf8Str strAppOverride = i_getExtraData(Utf8Str("VBoxInternal2/VirtualBoxVMAppOverride"));
7551 if ( strAppOverride.contains(".")
7552 || strAppOverride.contains("/")
7553 || strAppOverride.contains("\\")
7554 || strAppOverride.contains(":"))
7555 strAppOverride.setNull();
7556 Utf8Str strAppPath;
7557 if (!strAppOverride.isEmpty())
7558 {
7559 strAppPath = Utf8StrFmt(OSX_APP_PATH_FMT, strAppOverride.c_str());
7560 Utf8Str strFullPath(szPath);
7561 strFullPath.append(strAppPath);
7562 /* there is a race, but people using this deserve the failure */
7563 if (!RTFileExists(strFullPath.c_str()))
7564 strAppOverride.setNull();
7565 }
7566 if (strAppOverride.isEmpty())
7567 strAppPath = Utf8StrFmt(OSX_APP_PATH_FMT, OSX_APP_NAME);
7568 AssertReturn(cchBufLeft > strAppPath.length(), E_UNEXPECTED);
7569 strcpy(pszNamePart, strAppPath.c_str());
7570# else
7571 static const char s_szVirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
7572 Assert(cchBufLeft >= sizeof(s_szVirtualBox_exe));
7573 strcpy(pszNamePart, s_szVirtualBox_exe);
7574# endif
7575
7576 Utf8Str idStr = mData->mUuid.toString();
7577 const char *apszArgs[] =
7578 {
7579 szPath,
7580 "--comment", mUserData->s.strName.c_str(),
7581 "--startvm", idStr.c_str(),
7582 "--no-startvm-errormsgbox",
7583 NULL, /* For "--separate". */
7584 NULL, /* For "--sup-startup-log". */
7585 NULL
7586 };
7587 unsigned iArg = 6;
7588 if (fSeparate)
7589 apszArgs[iArg++] = "--separate";
7590 apszArgs[iArg++] = pszSupHardeningLogArg;
7591
7592 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7593 }
7594#else /* !VBOX_WITH_QTGUI */
7595 if (0)
7596 ;
7597#endif /* VBOX_WITH_QTGUI */
7598
7599 else
7600
7601#ifdef VBOX_WITH_VBOXSDL
7602 if ( !strFrontend.compare("sdl", Utf8Str::CaseInsensitive)
7603 || !strFrontend.compare("GUI/SDL", Utf8Str::CaseInsensitive)
7604 || !strFrontend.compare("sdl/separate", Utf8Str::CaseInsensitive)
7605 || !strFrontend.compare("GUI/SDL/separate", Utf8Str::CaseInsensitive))
7606 {
7607 strCanonicalName = "GUI/SDL";
7608 static const char s_szVBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
7609 Assert(cchBufLeft >= sizeof(s_szVBoxSDL_exe));
7610 strcpy(pszNamePart, s_szVBoxSDL_exe);
7611
7612 Utf8Str idStr = mData->mUuid.toString();
7613 const char *apszArgs[] =
7614 {
7615 szPath,
7616 "--comment", mUserData->s.strName.c_str(),
7617 "--startvm", idStr.c_str(),
7618 NULL, /* For "--separate". */
7619 NULL, /* For "--sup-startup-log". */
7620 NULL
7621 };
7622 unsigned iArg = 5;
7623 if (fSeparate)
7624 apszArgs[iArg++] = "--separate";
7625 apszArgs[iArg++] = pszSupHardeningLogArg;
7626
7627 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7628 }
7629#else /* !VBOX_WITH_VBOXSDL */
7630 if (0)
7631 ;
7632#endif /* !VBOX_WITH_VBOXSDL */
7633
7634 else
7635
7636#ifdef VBOX_WITH_HEADLESS
7637 if ( !strFrontend.compare("headless", Utf8Str::CaseInsensitive)
7638 || !strFrontend.compare("capture", Utf8Str::CaseInsensitive)
7639 || !strFrontend.compare("vrdp", Utf8Str::CaseInsensitive) /* Deprecated. Same as headless. */
7640 )
7641 {
7642 strCanonicalName = "headless";
7643 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
7644 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
7645 * and a VM works even if the server has not been installed.
7646 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
7647 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
7648 * differently in 4.0 and 3.x.
7649 */
7650 static const char s_szVBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
7651 Assert(cchBufLeft >= sizeof(s_szVBoxHeadless_exe));
7652 strcpy(pszNamePart, s_szVBoxHeadless_exe);
7653
7654 Utf8Str idStr = mData->mUuid.toString();
7655 const char *apszArgs[] =
7656 {
7657 szPath,
7658 "--comment", mUserData->s.strName.c_str(),
7659 "--startvm", idStr.c_str(),
7660 "--vrde", "config",
7661 NULL, /* For "--capture". */
7662 NULL, /* For "--sup-startup-log". */
7663 NULL
7664 };
7665 unsigned iArg = 7;
7666 if (!strFrontend.compare("capture", Utf8Str::CaseInsensitive))
7667 apszArgs[iArg++] = "--capture";
7668 apszArgs[iArg++] = pszSupHardeningLogArg;
7669
7670# ifdef RT_OS_WINDOWS
7671 vrc = RTProcCreate(szPath, apszArgs, env, RTPROC_FLAGS_NO_WINDOW, &pid);
7672# else
7673 vrc = RTProcCreate(szPath, apszArgs, env, 0, &pid);
7674# endif
7675 }
7676#else /* !VBOX_WITH_HEADLESS */
7677 if (0)
7678 ;
7679#endif /* !VBOX_WITH_HEADLESS */
7680 else
7681 {
7682 RTEnvDestroy(env);
7683 return setError(E_INVALIDARG,
7684 tr("Invalid frontend name: '%s'"),
7685 strFrontend.c_str());
7686 }
7687
7688 RTEnvDestroy(env);
7689
7690 if (RT_FAILURE(vrc))
7691 return setError(VBOX_E_IPRT_ERROR,
7692 tr("Could not launch a process for the machine '%s' (%Rrc)"),
7693 mUserData->s.strName.c_str(), vrc);
7694
7695 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
7696
7697 if (!fSeparate)
7698 {
7699 /*
7700 * Note that we don't release the lock here before calling the client,
7701 * because it doesn't need to call us back if called with a NULL argument.
7702 * Releasing the lock here is dangerous because we didn't prepare the
7703 * launch data yet, but the client we've just started may happen to be
7704 * too fast and call LockMachine() that will fail (because of PID, etc.),
7705 * so that the Machine will never get out of the Spawning session state.
7706 */
7707
7708 /* inform the session that it will be a remote one */
7709 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
7710#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
7711 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write, Bstr::Empty.raw());
7712#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
7713 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write, NULL);
7714#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
7715 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
7716
7717 if (FAILED(rc))
7718 {
7719 /* restore the session state */
7720 mData->mSession.mState = SessionState_Unlocked;
7721 alock.release();
7722 mParent->i_addProcessToReap(pid);
7723 /* The failure may occur w/o any error info (from RPC), so provide one */
7724 return setError(VBOX_E_VM_ERROR,
7725 tr("Failed to assign the machine to the session (%Rhrc)"), rc);
7726 }
7727
7728 /* attach launch data to the machine */
7729 Assert(mData->mSession.mPID == NIL_RTPROCESS);
7730 mData->mSession.mRemoteControls.push_back(aControl);
7731 mData->mSession.mProgress = aProgress;
7732 mData->mSession.mPID = pid;
7733 mData->mSession.mState = SessionState_Spawning;
7734 Assert(strCanonicalName.isNotEmpty());
7735 mData->mSession.mName = strCanonicalName;
7736 }
7737 else
7738 {
7739 /* For separate UI process we declare the launch as completed instantly, as the
7740 * actual headless VM start may or may not come. No point in remembering anything
7741 * yet, as what matters for us is when the headless VM gets started. */
7742 aProgress->i_notifyComplete(S_OK);
7743 }
7744
7745 alock.release();
7746 mParent->i_addProcessToReap(pid);
7747
7748 LogFlowThisFuncLeave();
7749 return S_OK;
7750}
7751
7752/**
7753 * Returns @c true if the given session machine instance has an open direct
7754 * session (and optionally also for direct sessions which are closing) and
7755 * returns the session control machine instance if so.
7756 *
7757 * Note that when the method returns @c false, the arguments remain unchanged.
7758 *
7759 * @param aMachine Session machine object.
7760 * @param aControl Direct session control object (optional).
7761 * @param aRequireVM If true then only allow VM sessions.
7762 * @param aAllowClosing If true then additionally a session which is currently
7763 * being closed will also be allowed.
7764 *
7765 * @note locks this object for reading.
7766 */
7767bool Machine::i_isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7768 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7769 bool aRequireVM /*= false*/,
7770 bool aAllowClosing /*= false*/)
7771{
7772 AutoLimitedCaller autoCaller(this);
7773 AssertComRCReturn(autoCaller.rc(), false);
7774
7775 /* just return false for inaccessible machines */
7776 if (getObjectState().getState() != ObjectState::Ready)
7777 return false;
7778
7779 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7780
7781 if ( ( mData->mSession.mState == SessionState_Locked
7782 && (!aRequireVM || mData->mSession.mLockType == LockType_VM))
7783 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
7784 )
7785 {
7786 AssertReturn(!mData->mSession.mMachine.isNull(), false);
7787
7788 aMachine = mData->mSession.mMachine;
7789
7790 if (aControl != NULL)
7791 *aControl = mData->mSession.mDirectControl;
7792
7793 return true;
7794 }
7795
7796 return false;
7797}
7798
7799/**
7800 * Returns @c true if the given machine has an spawning direct session.
7801 *
7802 * @note locks this object for reading.
7803 */
7804bool Machine::i_isSessionSpawning()
7805{
7806 AutoLimitedCaller autoCaller(this);
7807 AssertComRCReturn(autoCaller.rc(), false);
7808
7809 /* just return false for inaccessible machines */
7810 if (getObjectState().getState() != ObjectState::Ready)
7811 return false;
7812
7813 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7814
7815 if (mData->mSession.mState == SessionState_Spawning)
7816 return true;
7817
7818 return false;
7819}
7820
7821/**
7822 * Called from the client watcher thread to check for unexpected client process
7823 * death during Session_Spawning state (e.g. before it successfully opened a
7824 * direct session).
7825 *
7826 * On Win32 and on OS/2, this method is called only when we've got the
7827 * direct client's process termination notification, so it always returns @c
7828 * true.
7829 *
7830 * On other platforms, this method returns @c true if the client process is
7831 * terminated and @c false if it's still alive.
7832 *
7833 * @note Locks this object for writing.
7834 */
7835bool Machine::i_checkForSpawnFailure()
7836{
7837 AutoCaller autoCaller(this);
7838 if (!autoCaller.isOk())
7839 {
7840 /* nothing to do */
7841 LogFlowThisFunc(("Already uninitialized!\n"));
7842 return true;
7843 }
7844
7845 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7846
7847 if (mData->mSession.mState != SessionState_Spawning)
7848 {
7849 /* nothing to do */
7850 LogFlowThisFunc(("Not spawning any more!\n"));
7851 return true;
7852 }
7853
7854 HRESULT rc = S_OK;
7855
7856 /* PID not yet initialized, skip check. */
7857 if (mData->mSession.mPID == NIL_RTPROCESS)
7858 return false;
7859
7860 RTPROCSTATUS status;
7861 int vrc = RTProcWait(mData->mSession.mPID, RTPROCWAIT_FLAGS_NOBLOCK, &status);
7862
7863 if (vrc != VERR_PROCESS_RUNNING)
7864 {
7865 Utf8Str strExtraInfo;
7866
7867#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
7868 /* If the startup logfile exists and is of non-zero length, tell the
7869 user to look there for more details to encourage them to attach it
7870 when reporting startup issues. */
7871 Utf8Str strHardeningLogFile = i_getHardeningLogFilename();
7872 uint64_t cbStartupLogFile = 0;
7873 int vrc2 = RTFileQuerySize(strHardeningLogFile.c_str(), &cbStartupLogFile);
7874 if (RT_SUCCESS(vrc2) && cbStartupLogFile > 0)
7875 strExtraInfo.append(Utf8StrFmt(tr(". More details may be available in '%s'"), strHardeningLogFile.c_str()));
7876#endif
7877
7878 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
7879 rc = setError(E_FAIL,
7880 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d (%#x)%s"),
7881 i_getName().c_str(), status.iStatus, status.iStatus, strExtraInfo.c_str());
7882 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
7883 rc = setError(E_FAIL,
7884 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d%s"),
7885 i_getName().c_str(), status.iStatus, strExtraInfo.c_str());
7886 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
7887 rc = setError(E_FAIL,
7888 tr("The virtual machine '%s' has terminated abnormally (iStatus=%#x)%s"),
7889 i_getName().c_str(), status.iStatus, strExtraInfo.c_str());
7890 else
7891 rc = setError(E_FAIL,
7892 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)%s"),
7893 i_getName().c_str(), vrc, strExtraInfo.c_str());
7894 }
7895
7896 if (FAILED(rc))
7897 {
7898 /* Close the remote session, remove the remote control from the list
7899 * and reset session state to Closed (@note keep the code in sync with
7900 * the relevant part in LockMachine()). */
7901
7902 Assert(mData->mSession.mRemoteControls.size() == 1);
7903 if (mData->mSession.mRemoteControls.size() == 1)
7904 {
7905 ErrorInfoKeeper eik;
7906 mData->mSession.mRemoteControls.front()->Uninitialize();
7907 }
7908
7909 mData->mSession.mRemoteControls.clear();
7910 mData->mSession.mState = SessionState_Unlocked;
7911
7912 /* finalize the progress after setting the state */
7913 if (!mData->mSession.mProgress.isNull())
7914 {
7915 mData->mSession.mProgress->notifyComplete(rc);
7916 mData->mSession.mProgress.setNull();
7917 }
7918
7919 mData->mSession.mPID = NIL_RTPROCESS;
7920
7921 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
7922 return true;
7923 }
7924
7925 return false;
7926}
7927
7928/**
7929 * Checks whether the machine can be registered. If so, commits and saves
7930 * all settings.
7931 *
7932 * @note Must be called from mParent's write lock. Locks this object and
7933 * children for writing.
7934 */
7935HRESULT Machine::i_prepareRegister()
7936{
7937 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
7938
7939 AutoLimitedCaller autoCaller(this);
7940 AssertComRCReturnRC(autoCaller.rc());
7941
7942 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7943
7944 /* wait for state dependents to drop to zero */
7945 i_ensureNoStateDependencies();
7946
7947 if (!mData->mAccessible)
7948 return setError(VBOX_E_INVALID_OBJECT_STATE,
7949 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
7950 mUserData->s.strName.c_str(),
7951 mData->mUuid.toString().c_str());
7952
7953 AssertReturn(getObjectState().getState() == ObjectState::Ready, E_FAIL);
7954
7955 if (mData->mRegistered)
7956 return setError(VBOX_E_INVALID_OBJECT_STATE,
7957 tr("The machine '%s' with UUID {%s} is already registered"),
7958 mUserData->s.strName.c_str(),
7959 mData->mUuid.toString().c_str());
7960
7961 HRESULT rc = S_OK;
7962
7963 // Ensure the settings are saved. If we are going to be registered and
7964 // no config file exists yet, create it by calling i_saveSettings() too.
7965 if ( (mData->flModifications)
7966 || (!mData->pMachineConfigFile->fileExists())
7967 )
7968 {
7969 rc = i_saveSettings(NULL);
7970 // no need to check whether VirtualBox.xml needs saving too since
7971 // we can't have a machine XML file rename pending
7972 if (FAILED(rc)) return rc;
7973 }
7974
7975 /* more config checking goes here */
7976
7977 if (SUCCEEDED(rc))
7978 {
7979 /* we may have had implicit modifications we want to fix on success */
7980 i_commit();
7981
7982 mData->mRegistered = true;
7983 }
7984 else
7985 {
7986 /* we may have had implicit modifications we want to cancel on failure*/
7987 i_rollback(false /* aNotify */);
7988 }
7989
7990 return rc;
7991}
7992
7993/**
7994 * Increases the number of objects dependent on the machine state or on the
7995 * registered state. Guarantees that these two states will not change at least
7996 * until #releaseStateDependency() is called.
7997 *
7998 * Depending on the @a aDepType value, additional state checks may be made.
7999 * These checks will set extended error info on failure. See
8000 * #checkStateDependency() for more info.
8001 *
8002 * If this method returns a failure, the dependency is not added and the caller
8003 * is not allowed to rely on any particular machine state or registration state
8004 * value and may return the failed result code to the upper level.
8005 *
8006 * @param aDepType Dependency type to add.
8007 * @param aState Current machine state (NULL if not interested).
8008 * @param aRegistered Current registered state (NULL if not interested).
8009 *
8010 * @note Locks this object for writing.
8011 */
8012HRESULT Machine::i_addStateDependency(StateDependency aDepType /* = AnyStateDep */,
8013 MachineState_T *aState /* = NULL */,
8014 BOOL *aRegistered /* = NULL */)
8015{
8016 AutoCaller autoCaller(this);
8017 AssertComRCReturnRC(autoCaller.rc());
8018
8019 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8020
8021 HRESULT rc = i_checkStateDependency(aDepType);
8022 if (FAILED(rc)) return rc;
8023
8024 {
8025 if (mData->mMachineStateChangePending != 0)
8026 {
8027 /* i_ensureNoStateDependencies() is waiting for state dependencies to
8028 * drop to zero so don't add more. It may make sense to wait a bit
8029 * and retry before reporting an error (since the pending state
8030 * transition should be really quick) but let's just assert for
8031 * now to see if it ever happens on practice. */
8032
8033 AssertFailed();
8034
8035 return setError(E_ACCESSDENIED,
8036 tr("Machine state change is in progress. Please retry the operation later."));
8037 }
8038
8039 ++mData->mMachineStateDeps;
8040 Assert(mData->mMachineStateDeps != 0 /* overflow */);
8041 }
8042
8043 if (aState)
8044 *aState = mData->mMachineState;
8045 if (aRegistered)
8046 *aRegistered = mData->mRegistered;
8047
8048 return S_OK;
8049}
8050
8051/**
8052 * Decreases the number of objects dependent on the machine state.
8053 * Must always complete the #addStateDependency() call after the state
8054 * dependency is no more necessary.
8055 */
8056void Machine::i_releaseStateDependency()
8057{
8058 AutoCaller autoCaller(this);
8059 AssertComRCReturnVoid(autoCaller.rc());
8060
8061 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8062
8063 /* releaseStateDependency() w/o addStateDependency()? */
8064 AssertReturnVoid(mData->mMachineStateDeps != 0);
8065 -- mData->mMachineStateDeps;
8066
8067 if (mData->mMachineStateDeps == 0)
8068 {
8069 /* inform i_ensureNoStateDependencies() that there are no more deps */
8070 if (mData->mMachineStateChangePending != 0)
8071 {
8072 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
8073 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
8074 }
8075 }
8076}
8077
8078Utf8Str Machine::i_getExtraData(const Utf8Str &strKey)
8079{
8080 /* start with nothing found */
8081 Utf8Str strResult("");
8082
8083 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8084
8085 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
8086 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
8087 // found:
8088 strResult = it->second; // source is a Utf8Str
8089
8090 return strResult;
8091}
8092
8093// protected methods
8094/////////////////////////////////////////////////////////////////////////////
8095
8096/**
8097 * Performs machine state checks based on the @a aDepType value. If a check
8098 * fails, this method will set extended error info, otherwise it will return
8099 * S_OK. It is supposed, that on failure, the caller will immediately return
8100 * the return value of this method to the upper level.
8101 *
8102 * When @a aDepType is AnyStateDep, this method always returns S_OK.
8103 *
8104 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
8105 * current state of this machine object allows to change settings of the
8106 * machine (i.e. the machine is not registered, or registered but not running
8107 * and not saved). It is useful to call this method from Machine setters
8108 * before performing any change.
8109 *
8110 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
8111 * as for MutableStateDep except that if the machine is saved, S_OK is also
8112 * returned. This is useful in setters which allow changing machine
8113 * properties when it is in the saved state.
8114 *
8115 * When @a aDepType is MutableOrRunningStateDep, this method returns S_OK only
8116 * if the current state of this machine object allows to change runtime
8117 * changeable settings of the machine (i.e. the machine is not registered, or
8118 * registered but either running or not running and not saved). It is useful
8119 * to call this method from Machine setters before performing any changes to
8120 * runtime changeable settings.
8121 *
8122 * When @a aDepType is MutableOrSavedOrRunningStateDep, this method behaves
8123 * the same as for MutableOrRunningStateDep except that if the machine is
8124 * saved, S_OK is also returned. This is useful in setters which allow
8125 * changing runtime and saved state changeable machine properties.
8126 *
8127 * @param aDepType Dependency type to check.
8128 *
8129 * @note Non Machine based classes should use #addStateDependency() and
8130 * #releaseStateDependency() methods or the smart AutoStateDependency
8131 * template.
8132 *
8133 * @note This method must be called from under this object's read or write
8134 * lock.
8135 */
8136HRESULT Machine::i_checkStateDependency(StateDependency aDepType)
8137{
8138 switch (aDepType)
8139 {
8140 case AnyStateDep:
8141 {
8142 break;
8143 }
8144 case MutableStateDep:
8145 {
8146 if ( mData->mRegistered
8147 && ( !i_isSessionMachine()
8148 || ( mData->mMachineState != MachineState_Aborted
8149 && mData->mMachineState != MachineState_Teleported
8150 && mData->mMachineState != MachineState_PoweredOff
8151 )
8152 )
8153 )
8154 return setError(VBOX_E_INVALID_VM_STATE,
8155 tr("The machine is not mutable (state is %s)"),
8156 Global::stringifyMachineState(mData->mMachineState));
8157 break;
8158 }
8159 case MutableOrSavedStateDep:
8160 {
8161 if ( mData->mRegistered
8162 && ( !i_isSessionMachine()
8163 || ( mData->mMachineState != MachineState_Aborted
8164 && mData->mMachineState != MachineState_Teleported
8165 && mData->mMachineState != MachineState_Saved
8166 && mData->mMachineState != MachineState_PoweredOff
8167 )
8168 )
8169 )
8170 return setError(VBOX_E_INVALID_VM_STATE,
8171 tr("The machine is not mutable or saved (state is %s)"),
8172 Global::stringifyMachineState(mData->mMachineState));
8173 break;
8174 }
8175 case MutableOrRunningStateDep:
8176 {
8177 if ( mData->mRegistered
8178 && ( !i_isSessionMachine()
8179 || ( mData->mMachineState != MachineState_Aborted
8180 && mData->mMachineState != MachineState_Teleported
8181 && mData->mMachineState != MachineState_PoweredOff
8182 && !Global::IsOnline(mData->mMachineState)
8183 )
8184 )
8185 )
8186 return setError(VBOX_E_INVALID_VM_STATE,
8187 tr("The machine is not mutable or running (state is %s)"),
8188 Global::stringifyMachineState(mData->mMachineState));
8189 break;
8190 }
8191 case MutableOrSavedOrRunningStateDep:
8192 {
8193 if ( mData->mRegistered
8194 && ( !i_isSessionMachine()
8195 || ( mData->mMachineState != MachineState_Aborted
8196 && mData->mMachineState != MachineState_Teleported
8197 && mData->mMachineState != MachineState_Saved
8198 && mData->mMachineState != MachineState_PoweredOff
8199 && !Global::IsOnline(mData->mMachineState)
8200 )
8201 )
8202 )
8203 return setError(VBOX_E_INVALID_VM_STATE,
8204 tr("The machine is not mutable, saved or running (state is %s)"),
8205 Global::stringifyMachineState(mData->mMachineState));
8206 break;
8207 }
8208 }
8209
8210 return S_OK;
8211}
8212
8213/**
8214 * Helper to initialize all associated child objects and allocate data
8215 * structures.
8216 *
8217 * This method must be called as a part of the object's initialization procedure
8218 * (usually done in the #init() method).
8219 *
8220 * @note Must be called only from #init() or from #registeredInit().
8221 */
8222HRESULT Machine::initDataAndChildObjects()
8223{
8224 AutoCaller autoCaller(this);
8225 AssertComRCReturnRC(autoCaller.rc());
8226 AssertComRCReturn( getObjectState().getState() == ObjectState::InInit
8227 || getObjectState().getState() == ObjectState::Limited, E_FAIL);
8228
8229 AssertReturn(!mData->mAccessible, E_FAIL);
8230
8231 /* allocate data structures */
8232 mSSData.allocate();
8233 mUserData.allocate();
8234 mHWData.allocate();
8235 mMediaData.allocate();
8236 mStorageControllers.allocate();
8237 mUSBControllers.allocate();
8238
8239 /* initialize mOSTypeId */
8240 mUserData->s.strOsType = mParent->i_getUnknownOSType()->i_id();
8241
8242 /* create associated BIOS settings object */
8243 unconst(mBIOSSettings).createObject();
8244 mBIOSSettings->init(this);
8245
8246 /* create an associated VRDE object (default is disabled) */
8247 unconst(mVRDEServer).createObject();
8248 mVRDEServer->init(this);
8249
8250 /* create associated serial port objects */
8251 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8252 {
8253 unconst(mSerialPorts[slot]).createObject();
8254 mSerialPorts[slot]->init(this, slot);
8255 }
8256
8257 /* create associated parallel port objects */
8258 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8259 {
8260 unconst(mParallelPorts[slot]).createObject();
8261 mParallelPorts[slot]->init(this, slot);
8262 }
8263
8264 /* create the audio adapter object (always present, default is disabled) */
8265 unconst(mAudioAdapter).createObject();
8266 mAudioAdapter->init(this);
8267
8268 /* create the USB device filters object (always present) */
8269 unconst(mUSBDeviceFilters).createObject();
8270 mUSBDeviceFilters->init(this);
8271
8272 /* create associated network adapter objects */
8273 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
8274 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8275 {
8276 unconst(mNetworkAdapters[slot]).createObject();
8277 mNetworkAdapters[slot]->init(this, slot);
8278 }
8279
8280 /* create the bandwidth control */
8281 unconst(mBandwidthControl).createObject();
8282 mBandwidthControl->init(this);
8283
8284 return S_OK;
8285}
8286
8287/**
8288 * Helper to uninitialize all associated child objects and to free all data
8289 * structures.
8290 *
8291 * This method must be called as a part of the object's uninitialization
8292 * procedure (usually done in the #uninit() method).
8293 *
8294 * @note Must be called only from #uninit() or from #registeredInit().
8295 */
8296void Machine::uninitDataAndChildObjects()
8297{
8298 AutoCaller autoCaller(this);
8299 AssertComRCReturnVoid(autoCaller.rc());
8300 AssertComRCReturnVoid( getObjectState().getState() == ObjectState::InUninit
8301 || getObjectState().getState() == ObjectState::Limited);
8302
8303 /* tell all our other child objects we've been uninitialized */
8304 if (mBandwidthControl)
8305 {
8306 mBandwidthControl->uninit();
8307 unconst(mBandwidthControl).setNull();
8308 }
8309
8310 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
8311 {
8312 if (mNetworkAdapters[slot])
8313 {
8314 mNetworkAdapters[slot]->uninit();
8315 unconst(mNetworkAdapters[slot]).setNull();
8316 }
8317 }
8318
8319 if (mUSBDeviceFilters)
8320 {
8321 mUSBDeviceFilters->uninit();
8322 unconst(mUSBDeviceFilters).setNull();
8323 }
8324
8325 if (mAudioAdapter)
8326 {
8327 mAudioAdapter->uninit();
8328 unconst(mAudioAdapter).setNull();
8329 }
8330
8331 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
8332 {
8333 if (mParallelPorts[slot])
8334 {
8335 mParallelPorts[slot]->uninit();
8336 unconst(mParallelPorts[slot]).setNull();
8337 }
8338 }
8339
8340 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
8341 {
8342 if (mSerialPorts[slot])
8343 {
8344 mSerialPorts[slot]->uninit();
8345 unconst(mSerialPorts[slot]).setNull();
8346 }
8347 }
8348
8349 if (mVRDEServer)
8350 {
8351 mVRDEServer->uninit();
8352 unconst(mVRDEServer).setNull();
8353 }
8354
8355 if (mBIOSSettings)
8356 {
8357 mBIOSSettings->uninit();
8358 unconst(mBIOSSettings).setNull();
8359 }
8360
8361 /* Deassociate media (only when a real Machine or a SnapshotMachine
8362 * instance is uninitialized; SessionMachine instances refer to real
8363 * Machine media). This is necessary for a clean re-initialization of
8364 * the VM after successfully re-checking the accessibility state. Note
8365 * that in case of normal Machine or SnapshotMachine uninitialization (as
8366 * a result of unregistering or deleting the snapshot), outdated media
8367 * attachments will already be uninitialized and deleted, so this
8368 * code will not affect them. */
8369 if ( !!mMediaData
8370 && (!i_isSessionMachine())
8371 )
8372 {
8373 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8374 it != mMediaData->mAttachments.end();
8375 ++it)
8376 {
8377 ComObjPtr<Medium> pMedium = (*it)->i_getMedium();
8378 if (pMedium.isNull())
8379 continue;
8380 HRESULT rc = pMedium->i_removeBackReference(mData->mUuid, i_getSnapshotId());
8381 AssertComRC(rc);
8382 }
8383 }
8384
8385 if (!i_isSessionMachine() && !i_isSnapshotMachine())
8386 {
8387 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
8388 if (mData->mFirstSnapshot)
8389 {
8390 // snapshots tree is protected by machine write lock; strictly
8391 // this isn't necessary here since we're deleting the entire
8392 // machine, but otherwise we assert in Snapshot::uninit()
8393 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8394 mData->mFirstSnapshot->uninit();
8395 mData->mFirstSnapshot.setNull();
8396 }
8397
8398 mData->mCurrentSnapshot.setNull();
8399 }
8400
8401 /* free data structures (the essential mData structure is not freed here
8402 * since it may be still in use) */
8403 mMediaData.free();
8404 mStorageControllers.free();
8405 mUSBControllers.free();
8406 mHWData.free();
8407 mUserData.free();
8408 mSSData.free();
8409}
8410
8411/**
8412 * Returns a pointer to the Machine object for this machine that acts like a
8413 * parent for complex machine data objects such as shared folders, etc.
8414 *
8415 * For primary Machine objects and for SnapshotMachine objects, returns this
8416 * object's pointer itself. For SessionMachine objects, returns the peer
8417 * (primary) machine pointer.
8418 */
8419Machine* Machine::i_getMachine()
8420{
8421 if (i_isSessionMachine())
8422 return (Machine*)mPeer;
8423 return this;
8424}
8425
8426/**
8427 * Makes sure that there are no machine state dependents. If necessary, waits
8428 * for the number of dependents to drop to zero.
8429 *
8430 * Make sure this method is called from under this object's write lock to
8431 * guarantee that no new dependents may be added when this method returns
8432 * control to the caller.
8433 *
8434 * @note Locks this object for writing. The lock will be released while waiting
8435 * (if necessary).
8436 *
8437 * @warning To be used only in methods that change the machine state!
8438 */
8439void Machine::i_ensureNoStateDependencies()
8440{
8441 AssertReturnVoid(isWriteLockOnCurrentThread());
8442
8443 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8444
8445 /* Wait for all state dependents if necessary */
8446 if (mData->mMachineStateDeps != 0)
8447 {
8448 /* lazy semaphore creation */
8449 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
8450 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
8451
8452 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
8453 mData->mMachineStateDeps));
8454
8455 ++mData->mMachineStateChangePending;
8456
8457 /* reset the semaphore before waiting, the last dependent will signal
8458 * it */
8459 RTSemEventMultiReset(mData->mMachineStateDepsSem);
8460
8461 alock.release();
8462
8463 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
8464
8465 alock.acquire();
8466
8467 -- mData->mMachineStateChangePending;
8468 }
8469}
8470
8471/**
8472 * Changes the machine state and informs callbacks.
8473 *
8474 * This method is not intended to fail so it either returns S_OK or asserts (and
8475 * returns a failure).
8476 *
8477 * @note Locks this object for writing.
8478 */
8479HRESULT Machine::i_setMachineState(MachineState_T aMachineState)
8480{
8481 LogFlowThisFuncEnter();
8482 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
8483 Assert(aMachineState != MachineState_Null);
8484
8485 AutoCaller autoCaller(this);
8486 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8487
8488 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8489
8490 /* wait for state dependents to drop to zero */
8491 i_ensureNoStateDependencies();
8492
8493 MachineState_T const enmOldState = mData->mMachineState;
8494 if (enmOldState != aMachineState)
8495 {
8496 mData->mMachineState = aMachineState;
8497 RTTimeNow(&mData->mLastStateChange);
8498
8499#ifdef VBOX_WITH_DTRACE_R3_MAIN
8500 VBOXAPI_MACHINE_STATE_CHANGED(this, aMachineState, enmOldState, mData->mUuid.toStringCurly().c_str());
8501#endif
8502 mParent->i_onMachineStateChange(mData->mUuid, aMachineState);
8503 }
8504
8505 LogFlowThisFuncLeave();
8506 return S_OK;
8507}
8508
8509/**
8510 * Searches for a shared folder with the given logical name
8511 * in the collection of shared folders.
8512 *
8513 * @param aName logical name of the shared folder
8514 * @param aSharedFolder where to return the found object
8515 * @param aSetError whether to set the error info if the folder is
8516 * not found
8517 * @return
8518 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
8519 *
8520 * @note
8521 * must be called from under the object's lock!
8522 */
8523HRESULT Machine::i_findSharedFolder(const Utf8Str &aName,
8524 ComObjPtr<SharedFolder> &aSharedFolder,
8525 bool aSetError /* = false */)
8526{
8527 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
8528 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8529 it != mHWData->mSharedFolders.end();
8530 ++it)
8531 {
8532 SharedFolder *pSF = *it;
8533 AutoCaller autoCaller(pSF);
8534 if (pSF->i_getName() == aName)
8535 {
8536 aSharedFolder = pSF;
8537 rc = S_OK;
8538 break;
8539 }
8540 }
8541
8542 if (aSetError && FAILED(rc))
8543 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
8544
8545 return rc;
8546}
8547
8548/**
8549 * Initializes all machine instance data from the given settings structures
8550 * from XML. The exception is the machine UUID which needs special handling
8551 * depending on the caller's use case, so the caller needs to set that herself.
8552 *
8553 * This gets called in several contexts during machine initialization:
8554 *
8555 * -- When machine XML exists on disk already and needs to be loaded into memory,
8556 * for example, from registeredInit() to load all registered machines on
8557 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
8558 * attached to the machine should be part of some media registry already.
8559 *
8560 * -- During OVF import, when a machine config has been constructed from an
8561 * OVF file. In this case, puuidRegistry is set to the machine UUID to
8562 * ensure that the media listed as attachments in the config (which have
8563 * been imported from the OVF) receive the correct registry ID.
8564 *
8565 * -- During VM cloning.
8566 *
8567 * @param config Machine settings from XML.
8568 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID
8569 * for each attached medium in the config.
8570 * @return
8571 */
8572HRESULT Machine::i_loadMachineDataFromSettings(const settings::MachineConfigFile &config,
8573 const Guid *puuidRegistry)
8574{
8575 // copy name, description, OS type, teleporter, UTC etc.
8576 mUserData->s = config.machineUserData;
8577
8578 // Decode the Icon overide data from config userdata and set onto Machine.
8579 #define DECODE_STR_MAX _1M
8580 const char* pszStr = config.machineUserData.ovIcon.c_str();
8581 ssize_t cbOut = RTBase64DecodedSize(pszStr, NULL);
8582 if (cbOut > DECODE_STR_MAX)
8583 return setError(E_FAIL,
8584 tr("Icon Data too long.'%d' > '%d'"),
8585 cbOut,
8586 DECODE_STR_MAX);
8587 mUserData->mIcon.resize(cbOut);
8588 int vrc = VINF_SUCCESS;
8589 if (cbOut)
8590 vrc = RTBase64Decode(pszStr, &mUserData->mIcon.front(), cbOut, NULL, NULL);
8591 if (RT_FAILURE(vrc))
8592 {
8593 mUserData->mIcon.resize(0);
8594 return setError(E_FAIL,
8595 tr("Failure to Decode Icon Data. '%s' (%Rrc)"),
8596 pszStr,
8597 vrc);
8598 }
8599
8600 // look up the object by Id to check it is valid
8601 ComPtr<IGuestOSType> guestOSType;
8602 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
8603 guestOSType.asOutParam());
8604 if (FAILED(rc)) return rc;
8605
8606 // stateFile (optional)
8607 if (config.strStateFile.isEmpty())
8608 mSSData->strStateFilePath.setNull();
8609 else
8610 {
8611 Utf8Str stateFilePathFull(config.strStateFile);
8612 vrc = i_calculateFullPath(stateFilePathFull, stateFilePathFull);
8613 if (RT_FAILURE(vrc))
8614 return setError(E_FAIL,
8615 tr("Invalid saved state file path '%s' (%Rrc)"),
8616 config.strStateFile.c_str(),
8617 vrc);
8618 mSSData->strStateFilePath = stateFilePathFull;
8619 }
8620
8621 // snapshot folder needs special processing so set it again
8622 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
8623 if (FAILED(rc)) return rc;
8624
8625 /* Copy the extra data items (Not in any case config is already the same as
8626 * mData->pMachineConfigFile, like when the xml files are read from disk. So
8627 * make sure the extra data map is copied). */
8628 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
8629
8630 /* currentStateModified (optional, default is true) */
8631 mData->mCurrentStateModified = config.fCurrentStateModified;
8632
8633 mData->mLastStateChange = config.timeLastStateChange;
8634
8635 /*
8636 * note: all mUserData members must be assigned prior this point because
8637 * we need to commit changes in order to let mUserData be shared by all
8638 * snapshot machine instances.
8639 */
8640 mUserData.commitCopy();
8641
8642 // machine registry, if present (must be loaded before snapshots)
8643 if (config.canHaveOwnMediaRegistry())
8644 {
8645 // determine machine folder
8646 Utf8Str strMachineFolder = i_getSettingsFileFull();
8647 strMachineFolder.stripFilename();
8648 rc = mParent->initMedia(i_getId(), // media registry ID == machine UUID
8649 config.mediaRegistry,
8650 strMachineFolder);
8651 if (FAILED(rc)) return rc;
8652 }
8653
8654 /* Snapshot node (optional) */
8655 size_t cRootSnapshots;
8656 if ((cRootSnapshots = config.llFirstSnapshot.size()))
8657 {
8658 // there must be only one root snapshot
8659 Assert(cRootSnapshots == 1);
8660
8661 const settings::Snapshot &snap = config.llFirstSnapshot.front();
8662
8663 rc = i_loadSnapshot(snap,
8664 config.uuidCurrentSnapshot,
8665 NULL); // no parent == first snapshot
8666 if (FAILED(rc)) return rc;
8667 }
8668
8669 // hardware data
8670 rc = i_loadHardware(config.hardwareMachine, &config.debugging, &config.autostart);
8671 if (FAILED(rc)) return rc;
8672
8673 // load storage controllers
8674 rc = i_loadStorageControllers(config.storageMachine,
8675 puuidRegistry,
8676 NULL /* puuidSnapshot */);
8677 if (FAILED(rc)) return rc;
8678
8679 /*
8680 * NOTE: the assignment below must be the last thing to do,
8681 * otherwise it will be not possible to change the settings
8682 * somewhere in the code above because all setters will be
8683 * blocked by i_checkStateDependency(MutableStateDep).
8684 */
8685
8686 /* set the machine state to Aborted or Saved when appropriate */
8687 if (config.fAborted)
8688 {
8689 mSSData->strStateFilePath.setNull();
8690
8691 /* no need to use i_setMachineState() during init() */
8692 mData->mMachineState = MachineState_Aborted;
8693 }
8694 else if (!mSSData->strStateFilePath.isEmpty())
8695 {
8696 /* no need to use i_setMachineState() during init() */
8697 mData->mMachineState = MachineState_Saved;
8698 }
8699
8700 // after loading settings, we are no longer different from the XML on disk
8701 mData->flModifications = 0;
8702
8703 return S_OK;
8704}
8705
8706/**
8707 * Recursively loads all snapshots starting from the given.
8708 *
8709 * @param aNode <Snapshot> node.
8710 * @param aCurSnapshotId Current snapshot ID from the settings file.
8711 * @param aParentSnapshot Parent snapshot.
8712 */
8713HRESULT Machine::i_loadSnapshot(const settings::Snapshot &data,
8714 const Guid &aCurSnapshotId,
8715 Snapshot *aParentSnapshot)
8716{
8717 AssertReturn(!i_isSnapshotMachine(), E_FAIL);
8718 AssertReturn(!i_isSessionMachine(), E_FAIL);
8719
8720 HRESULT rc = S_OK;
8721
8722 Utf8Str strStateFile;
8723 if (!data.strStateFile.isEmpty())
8724 {
8725 /* optional */
8726 strStateFile = data.strStateFile;
8727 int vrc = i_calculateFullPath(strStateFile, strStateFile);
8728 if (RT_FAILURE(vrc))
8729 return setError(E_FAIL,
8730 tr("Invalid saved state file path '%s' (%Rrc)"),
8731 strStateFile.c_str(),
8732 vrc);
8733 }
8734
8735 /* create a snapshot machine object */
8736 ComObjPtr<SnapshotMachine> pSnapshotMachine;
8737 pSnapshotMachine.createObject();
8738 rc = pSnapshotMachine->initFromSettings(this,
8739 data.hardware,
8740 &data.debugging,
8741 &data.autostart,
8742 data.storage,
8743 data.uuid.ref(),
8744 strStateFile);
8745 if (FAILED(rc)) return rc;
8746
8747 /* create a snapshot object */
8748 ComObjPtr<Snapshot> pSnapshot;
8749 pSnapshot.createObject();
8750 /* initialize the snapshot */
8751 rc = pSnapshot->init(mParent, // VirtualBox object
8752 data.uuid,
8753 data.strName,
8754 data.strDescription,
8755 data.timestamp,
8756 pSnapshotMachine,
8757 aParentSnapshot);
8758 if (FAILED(rc)) return rc;
8759
8760 /* memorize the first snapshot if necessary */
8761 if (!mData->mFirstSnapshot)
8762 mData->mFirstSnapshot = pSnapshot;
8763
8764 /* memorize the current snapshot when appropriate */
8765 if ( !mData->mCurrentSnapshot
8766 && pSnapshot->i_getId() == aCurSnapshotId
8767 )
8768 mData->mCurrentSnapshot = pSnapshot;
8769
8770 // now create the children
8771 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
8772 it != data.llChildSnapshots.end();
8773 ++it)
8774 {
8775 const settings::Snapshot &childData = *it;
8776 // recurse
8777 rc = i_loadSnapshot(childData,
8778 aCurSnapshotId,
8779 pSnapshot); // parent = the one we created above
8780 if (FAILED(rc)) return rc;
8781 }
8782
8783 return rc;
8784}
8785
8786/**
8787 * Loads settings into mHWData.
8788 *
8789 * @param data Reference to the hardware settings.
8790 * @param pDbg Pointer to the debugging settings.
8791 * @param pAutostart Pointer to the autostart settings.
8792 */
8793HRESULT Machine::i_loadHardware(const settings::Hardware &data, const settings::Debugging *pDbg,
8794 const settings::Autostart *pAutostart)
8795{
8796 AssertReturn(!i_isSessionMachine(), E_FAIL);
8797
8798 HRESULT rc = S_OK;
8799
8800 try
8801 {
8802 /* The hardware version attribute (optional). */
8803 mHWData->mHWVersion = data.strVersion;
8804 mHWData->mHardwareUUID = data.uuid;
8805
8806 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
8807 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
8808 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
8809 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
8810 mHWData->mHWVirtExUXEnabled = data.fUnrestrictedExecution;
8811 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
8812 mHWData->mPAEEnabled = data.fPAE;
8813 mHWData->mLongMode = data.enmLongMode;
8814 mHWData->mTripleFaultReset = data.fTripleFaultReset;
8815 mHWData->mCPUCount = data.cCPUs;
8816 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
8817 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
8818 mHWData->mCpuIdPortabilityLevel = data.uCpuIdPortabilityLevel;
8819
8820 // cpu
8821 if (mHWData->mCPUHotPlugEnabled)
8822 {
8823 for (settings::CpuList::const_iterator it = data.llCpus.begin();
8824 it != data.llCpus.end();
8825 ++it)
8826 {
8827 const settings::Cpu &cpu = *it;
8828
8829 mHWData->mCPUAttached[cpu.ulId] = true;
8830 }
8831 }
8832
8833 // cpuid leafs
8834 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
8835 it != data.llCpuIdLeafs.end();
8836 ++it)
8837 {
8838 const settings::CpuIdLeaf &leaf = *it;
8839
8840 switch (leaf.ulId)
8841 {
8842 case 0x0:
8843 case 0x1:
8844 case 0x2:
8845 case 0x3:
8846 case 0x4:
8847 case 0x5:
8848 case 0x6:
8849 case 0x7:
8850 case 0x8:
8851 case 0x9:
8852 case 0xA:
8853 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
8854 break;
8855
8856 case 0x80000000:
8857 case 0x80000001:
8858 case 0x80000002:
8859 case 0x80000003:
8860 case 0x80000004:
8861 case 0x80000005:
8862 case 0x80000006:
8863 case 0x80000007:
8864 case 0x80000008:
8865 case 0x80000009:
8866 case 0x8000000A:
8867 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
8868 break;
8869
8870 default:
8871 /* just ignore */
8872 break;
8873 }
8874 }
8875
8876 mHWData->mMemorySize = data.ulMemorySizeMB;
8877 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
8878
8879 // boot order
8880 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
8881 {
8882 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
8883 if (it == data.mapBootOrder.end())
8884 mHWData->mBootOrder[i] = DeviceType_Null;
8885 else
8886 mHWData->mBootOrder[i] = it->second;
8887 }
8888
8889 mHWData->mGraphicsControllerType = data.graphicsControllerType;
8890 mHWData->mVRAMSize = data.ulVRAMSizeMB;
8891 mHWData->mMonitorCount = data.cMonitors;
8892 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
8893 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
8894 mHWData->mVideoCaptureWidth = data.ulVideoCaptureHorzRes;
8895 mHWData->mVideoCaptureHeight = data.ulVideoCaptureVertRes;
8896 mHWData->mVideoCaptureEnabled = data.fVideoCaptureEnabled;
8897 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->maVideoCaptureScreens); ++i)
8898 mHWData->maVideoCaptureScreens[i] = ASMBitTest(&data.u64VideoCaptureScreens, i);
8899 AssertCompile(RT_ELEMENTS(mHWData->maVideoCaptureScreens) == sizeof(data.u64VideoCaptureScreens) * 8);
8900 mHWData->mVideoCaptureRate = data.ulVideoCaptureRate;
8901 mHWData->mVideoCaptureFPS = data.ulVideoCaptureFPS;
8902 if (!data.strVideoCaptureFile.isEmpty())
8903 i_calculateFullPath(data.strVideoCaptureFile, mHWData->mVideoCaptureFile);
8904 else
8905 mHWData->mVideoCaptureFile.setNull();
8906 mHWData->mFirmwareType = data.firmwareType;
8907 mHWData->mPointingHIDType = data.pointingHIDType;
8908 mHWData->mKeyboardHIDType = data.keyboardHIDType;
8909 mHWData->mChipsetType = data.chipsetType;
8910 mHWData->mParavirtProvider = data.paravirtProvider;
8911 mHWData->mEmulatedUSBCardReaderEnabled = data.fEmulatedUSBCardReader;
8912 mHWData->mHPETEnabled = data.fHPETEnabled;
8913
8914 /* VRDEServer */
8915 rc = mVRDEServer->i_loadSettings(data.vrdeSettings);
8916 if (FAILED(rc)) return rc;
8917
8918 /* BIOS */
8919 rc = mBIOSSettings->i_loadSettings(data.biosSettings);
8920 if (FAILED(rc)) return rc;
8921
8922 // Bandwidth control (must come before network adapters)
8923 rc = mBandwidthControl->i_loadSettings(data.ioSettings);
8924 if (FAILED(rc)) return rc;
8925
8926 /* Shared folders */
8927 for (settings::USBControllerList::const_iterator it = data.usbSettings.llUSBControllers.begin();
8928 it != data.usbSettings.llUSBControllers.end();
8929 ++it)
8930 {
8931 const settings::USBController &settingsCtrl = *it;
8932 ComObjPtr<USBController> newCtrl;
8933
8934 newCtrl.createObject();
8935 newCtrl->init(this, settingsCtrl.strName, settingsCtrl.enmType);
8936 mUSBControllers->push_back(newCtrl);
8937 }
8938
8939 /* USB device filters */
8940 rc = mUSBDeviceFilters->i_loadSettings(data.usbSettings);
8941 if (FAILED(rc)) return rc;
8942
8943 // network adapters
8944 size_t newCount = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
8945 size_t oldCount = mNetworkAdapters.size();
8946 if (newCount > oldCount)
8947 {
8948 mNetworkAdapters.resize(newCount);
8949 for (size_t slot = oldCount; slot < mNetworkAdapters.size(); ++slot)
8950 {
8951 unconst(mNetworkAdapters[slot]).createObject();
8952 mNetworkAdapters[slot]->init(this, (ULONG)slot);
8953 }
8954 }
8955 else if (newCount < oldCount)
8956 mNetworkAdapters.resize(newCount);
8957 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
8958 it != data.llNetworkAdapters.end();
8959 ++it)
8960 {
8961 const settings::NetworkAdapter &nic = *it;
8962
8963 /* slot unicity is guaranteed by XML Schema */
8964 AssertBreak(nic.ulSlot < mNetworkAdapters.size());
8965 rc = mNetworkAdapters[nic.ulSlot]->i_loadSettings(mBandwidthControl, nic);
8966 if (FAILED(rc)) return rc;
8967 }
8968
8969 // serial ports
8970 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
8971 it != data.llSerialPorts.end();
8972 ++it)
8973 {
8974 const settings::SerialPort &s = *it;
8975
8976 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
8977 rc = mSerialPorts[s.ulSlot]->i_loadSettings(s);
8978 if (FAILED(rc)) return rc;
8979 }
8980
8981 // parallel ports (optional)
8982 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
8983 it != data.llParallelPorts.end();
8984 ++it)
8985 {
8986 const settings::ParallelPort &p = *it;
8987
8988 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
8989 rc = mParallelPorts[p.ulSlot]->i_loadSettings(p);
8990 if (FAILED(rc)) return rc;
8991 }
8992
8993 /* AudioAdapter */
8994 rc = mAudioAdapter->i_loadSettings(data.audioAdapter);
8995 if (FAILED(rc)) return rc;
8996
8997 /* Shared folders */
8998 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
8999 it != data.llSharedFolders.end();
9000 ++it)
9001 {
9002 const settings::SharedFolder &sf = *it;
9003
9004 ComObjPtr<SharedFolder> sharedFolder;
9005 /* Check for double entries. Not allowed! */
9006 rc = i_findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
9007 if (SUCCEEDED(rc))
9008 return setError(VBOX_E_OBJECT_IN_USE,
9009 tr("Shared folder named '%s' already exists"),
9010 sf.strName.c_str());
9011
9012 /* Create the new shared folder. Don't break on error. This will be
9013 * reported when the machine starts. */
9014 sharedFolder.createObject();
9015 rc = sharedFolder->init(i_getMachine(),
9016 sf.strName,
9017 sf.strHostPath,
9018 RT_BOOL(sf.fWritable),
9019 RT_BOOL(sf.fAutoMount),
9020 false /* fFailOnError */);
9021 if (FAILED(rc)) return rc;
9022 mHWData->mSharedFolders.push_back(sharedFolder);
9023 }
9024
9025 // Clipboard
9026 mHWData->mClipboardMode = data.clipboardMode;
9027
9028 // drag'n'drop
9029 mHWData->mDnDMode = data.dndMode;
9030
9031 // guest settings
9032 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
9033
9034 // IO settings
9035 mHWData->mIOCacheEnabled = data.ioSettings.fIOCacheEnabled;
9036 mHWData->mIOCacheSize = data.ioSettings.ulIOCacheSize;
9037
9038 // Host PCI devices
9039 for (settings::HostPCIDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
9040 it != data.pciAttachments.end();
9041 ++it)
9042 {
9043 const settings::HostPCIDeviceAttachment &hpda = *it;
9044 ComObjPtr<PCIDeviceAttachment> pda;
9045
9046 pda.createObject();
9047 pda->i_loadSettings(this, hpda);
9048 mHWData->mPCIDeviceAssignments.push_back(pda);
9049 }
9050
9051 /*
9052 * (The following isn't really real hardware, but it lives in HWData
9053 * for reasons of convenience.)
9054 */
9055
9056#ifdef VBOX_WITH_GUEST_PROPS
9057 /* Guest properties (optional) */
9058
9059 /* Only load transient guest properties for configs which have saved
9060 * state, because there shouldn't be any for powered off VMs. The same
9061 * logic applies for snapshots, as offline snapshots shouldn't have
9062 * any such properties. They confuse the code in various places.
9063 * Note: can't rely on the machine state, as it isn't set yet. */
9064 bool fSkipTransientGuestProperties = mSSData->strStateFilePath.isEmpty();
9065 /* apologies for the hacky unconst() usage, but this needs hacking
9066 * actually inconsistent settings into consistency, otherwise there
9067 * will be some corner cases where the inconsistency survives
9068 * surprisingly long without getting fixed, especially for snapshots
9069 * as there are no config changes. */
9070 settings::GuestPropertiesList &llGuestProperties = unconst(data.llGuestProperties);
9071 for (settings::GuestPropertiesList::iterator it = llGuestProperties.begin();
9072 it != llGuestProperties.end();
9073 /*nothing*/)
9074 {
9075 const settings::GuestProperty &prop = *it;
9076 uint32_t fFlags = guestProp::NILFLAG;
9077 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
9078 if ( fSkipTransientGuestProperties
9079 && ( fFlags & guestProp::TRANSIENT
9080 || fFlags & guestProp::TRANSRESET))
9081 {
9082 it = llGuestProperties.erase(it);
9083 continue;
9084 }
9085 HWData::GuestProperty property = { prop.strValue, (LONG64) prop.timestamp, fFlags };
9086 mHWData->mGuestProperties[prop.strName] = property;
9087 ++it;
9088 }
9089#endif /* VBOX_WITH_GUEST_PROPS defined */
9090
9091 rc = i_loadDebugging(pDbg);
9092 if (FAILED(rc))
9093 return rc;
9094
9095 mHWData->mAutostart = *pAutostart;
9096
9097 /* default frontend */
9098 mHWData->mDefaultFrontend = data.strDefaultFrontend;
9099 }
9100 catch(std::bad_alloc &)
9101 {
9102 return E_OUTOFMEMORY;
9103 }
9104
9105 AssertComRC(rc);
9106 return rc;
9107}
9108
9109/**
9110 * Called from Machine::loadHardware() to load the debugging settings of the
9111 * machine.
9112 *
9113 * @param pDbg Pointer to the settings.
9114 */
9115HRESULT Machine::i_loadDebugging(const settings::Debugging *pDbg)
9116{
9117 mHWData->mDebugging = *pDbg;
9118 /* no more processing currently required, this will probably change. */
9119 return S_OK;
9120}
9121
9122/**
9123 * Called from i_loadMachineDataFromSettings() for the storage controller data, including media.
9124 *
9125 * @param data
9126 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::i_loadMachineDataFromSettings()
9127 * @param puuidSnapshot
9128 * @return
9129 */
9130HRESULT Machine::i_loadStorageControllers(const settings::Storage &data,
9131 const Guid *puuidRegistry,
9132 const Guid *puuidSnapshot)
9133{
9134 AssertReturn(!i_isSessionMachine(), E_FAIL);
9135
9136 HRESULT rc = S_OK;
9137
9138 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
9139 it != data.llStorageControllers.end();
9140 ++it)
9141 {
9142 const settings::StorageController &ctlData = *it;
9143
9144 ComObjPtr<StorageController> pCtl;
9145 /* Try to find one with the name first. */
9146 rc = i_getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
9147 if (SUCCEEDED(rc))
9148 return setError(VBOX_E_OBJECT_IN_USE,
9149 tr("Storage controller named '%s' already exists"),
9150 ctlData.strName.c_str());
9151
9152 pCtl.createObject();
9153 rc = pCtl->init(this,
9154 ctlData.strName,
9155 ctlData.storageBus,
9156 ctlData.ulInstance,
9157 ctlData.fBootable);
9158 if (FAILED(rc)) return rc;
9159
9160 mStorageControllers->push_back(pCtl);
9161
9162 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
9163 if (FAILED(rc)) return rc;
9164
9165 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
9166 if (FAILED(rc)) return rc;
9167
9168 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
9169 if (FAILED(rc)) return rc;
9170
9171 /* Load the attached devices now. */
9172 rc = i_loadStorageDevices(pCtl,
9173 ctlData,
9174 puuidRegistry,
9175 puuidSnapshot);
9176 if (FAILED(rc)) return rc;
9177 }
9178
9179 return S_OK;
9180}
9181
9182/**
9183 * Called from i_loadStorageControllers for a controller's devices.
9184 *
9185 * @param aStorageController
9186 * @param data
9187 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::i_loadMachineDataFromSettings()
9188 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
9189 * @return
9190 */
9191HRESULT Machine::i_loadStorageDevices(StorageController *aStorageController,
9192 const settings::StorageController &data,
9193 const Guid *puuidRegistry,
9194 const Guid *puuidSnapshot)
9195{
9196 HRESULT rc = S_OK;
9197
9198 /* paranoia: detect duplicate attachments */
9199 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
9200 it != data.llAttachedDevices.end();
9201 ++it)
9202 {
9203 const settings::AttachedDevice &ad = *it;
9204
9205 for (settings::AttachedDevicesList::const_iterator it2 = it;
9206 it2 != data.llAttachedDevices.end();
9207 ++it2)
9208 {
9209 if (it == it2)
9210 continue;
9211
9212 const settings::AttachedDevice &ad2 = *it2;
9213
9214 if ( ad.lPort == ad2.lPort
9215 && ad.lDevice == ad2.lDevice)
9216 {
9217 return setError(E_FAIL,
9218 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
9219 aStorageController->i_getName().c_str(),
9220 ad.lPort,
9221 ad.lDevice,
9222 mUserData->s.strName.c_str());
9223 }
9224 }
9225 }
9226
9227 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
9228 it != data.llAttachedDevices.end();
9229 ++it)
9230 {
9231 const settings::AttachedDevice &dev = *it;
9232 ComObjPtr<Medium> medium;
9233
9234 switch (dev.deviceType)
9235 {
9236 case DeviceType_Floppy:
9237 case DeviceType_DVD:
9238 if (dev.strHostDriveSrc.isNotEmpty())
9239 rc = mParent->i_host()->i_findHostDriveByName(dev.deviceType, dev.strHostDriveSrc,
9240 false /* fRefresh */, medium);
9241 else
9242 rc = mParent->i_findRemoveableMedium(dev.deviceType,
9243 dev.uuid,
9244 false /* fRefresh */,
9245 false /* aSetError */,
9246 medium);
9247 if (rc == VBOX_E_OBJECT_NOT_FOUND)
9248 // This is not an error. The host drive or UUID might have vanished, so just go
9249 // ahead without this removeable medium attachment
9250 rc = S_OK;
9251 break;
9252
9253 case DeviceType_HardDisk:
9254 {
9255 /* find a hard disk by UUID */
9256 rc = mParent->i_findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
9257 if (FAILED(rc))
9258 {
9259 if (i_isSnapshotMachine())
9260 {
9261 // wrap another error message around the "cannot find hard disk" set by findHardDisk
9262 // so the user knows that the bad disk is in a snapshot somewhere
9263 com::ErrorInfo info;
9264 return setError(E_FAIL,
9265 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
9266 puuidSnapshot->raw(),
9267 info.getText().raw());
9268 }
9269 else
9270 return rc;
9271 }
9272
9273 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
9274
9275 if (medium->i_getType() == MediumType_Immutable)
9276 {
9277 if (i_isSnapshotMachine())
9278 return setError(E_FAIL,
9279 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9280 "of the virtual machine '%s' ('%s')"),
9281 medium->i_getLocationFull().c_str(),
9282 dev.uuid.raw(),
9283 puuidSnapshot->raw(),
9284 mUserData->s.strName.c_str(),
9285 mData->m_strConfigFileFull.c_str());
9286
9287 return setError(E_FAIL,
9288 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9289 medium->i_getLocationFull().c_str(),
9290 dev.uuid.raw(),
9291 mUserData->s.strName.c_str(),
9292 mData->m_strConfigFileFull.c_str());
9293 }
9294
9295 if (medium->i_getType() == MediumType_MultiAttach)
9296 {
9297 if (i_isSnapshotMachine())
9298 return setError(E_FAIL,
9299 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9300 "of the virtual machine '%s' ('%s')"),
9301 medium->i_getLocationFull().c_str(),
9302 dev.uuid.raw(),
9303 puuidSnapshot->raw(),
9304 mUserData->s.strName.c_str(),
9305 mData->m_strConfigFileFull.c_str());
9306
9307 return setError(E_FAIL,
9308 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9309 medium->i_getLocationFull().c_str(),
9310 dev.uuid.raw(),
9311 mUserData->s.strName.c_str(),
9312 mData->m_strConfigFileFull.c_str());
9313 }
9314
9315 if ( !i_isSnapshotMachine()
9316 && medium->i_getChildren().size() != 0
9317 )
9318 return setError(E_FAIL,
9319 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
9320 "because it has %d differencing child hard disks"),
9321 medium->i_getLocationFull().c_str(),
9322 dev.uuid.raw(),
9323 mUserData->s.strName.c_str(),
9324 mData->m_strConfigFileFull.c_str(),
9325 medium->i_getChildren().size());
9326
9327 if (i_findAttachment(mMediaData->mAttachments,
9328 medium))
9329 return setError(E_FAIL,
9330 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
9331 medium->i_getLocationFull().c_str(),
9332 dev.uuid.raw(),
9333 mUserData->s.strName.c_str(),
9334 mData->m_strConfigFileFull.c_str());
9335
9336 break;
9337 }
9338
9339 default:
9340 return setError(E_FAIL,
9341 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
9342 medium->i_getLocationFull().c_str(),
9343 mUserData->s.strName.c_str(),
9344 mData->m_strConfigFileFull.c_str());
9345 }
9346
9347 if (FAILED(rc))
9348 break;
9349
9350 /* Bandwidth groups are loaded at this point. */
9351 ComObjPtr<BandwidthGroup> pBwGroup;
9352
9353 if (!dev.strBwGroup.isEmpty())
9354 {
9355 rc = mBandwidthControl->i_getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
9356 if (FAILED(rc))
9357 return setError(E_FAIL,
9358 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
9359 medium->i_getLocationFull().c_str(),
9360 dev.strBwGroup.c_str(),
9361 mUserData->s.strName.c_str(),
9362 mData->m_strConfigFileFull.c_str());
9363 pBwGroup->i_reference();
9364 }
9365
9366 const Bstr controllerName = aStorageController->i_getName();
9367 ComObjPtr<MediumAttachment> pAttachment;
9368 pAttachment.createObject();
9369 rc = pAttachment->init(this,
9370 medium,
9371 controllerName,
9372 dev.lPort,
9373 dev.lDevice,
9374 dev.deviceType,
9375 false,
9376 dev.fPassThrough,
9377 dev.fTempEject,
9378 dev.fNonRotational,
9379 dev.fDiscard,
9380 dev.fHotPluggable,
9381 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->i_getName());
9382 if (FAILED(rc)) break;
9383
9384 /* associate the medium with this machine and snapshot */
9385 if (!medium.isNull())
9386 {
9387 AutoCaller medCaller(medium);
9388 if (FAILED(medCaller.rc())) return medCaller.rc();
9389 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
9390
9391 if (i_isSnapshotMachine())
9392 rc = medium->i_addBackReference(mData->mUuid, *puuidSnapshot);
9393 else
9394 rc = medium->i_addBackReference(mData->mUuid);
9395 /* If the medium->addBackReference fails it sets an appropriate
9396 * error message, so no need to do any guesswork here. */
9397
9398 if (puuidRegistry)
9399 // caller wants registry ID to be set on all attached media (OVF import case)
9400 medium->i_addRegistry(*puuidRegistry);
9401 }
9402
9403 if (FAILED(rc))
9404 break;
9405
9406 /* back up mMediaData to let registeredInit() properly rollback on failure
9407 * (= limited accessibility) */
9408 i_setModified(IsModified_Storage);
9409 mMediaData.backup();
9410 mMediaData->mAttachments.push_back(pAttachment);
9411 }
9412
9413 return rc;
9414}
9415
9416/**
9417 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
9418 *
9419 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
9420 * @param aSnapshot where to return the found snapshot
9421 * @param aSetError true to set extended error info on failure
9422 */
9423HRESULT Machine::i_findSnapshotById(const Guid &aId,
9424 ComObjPtr<Snapshot> &aSnapshot,
9425 bool aSetError /* = false */)
9426{
9427 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9428
9429 if (!mData->mFirstSnapshot)
9430 {
9431 if (aSetError)
9432 return setError(E_FAIL, tr("This machine does not have any snapshots"));
9433 return E_FAIL;
9434 }
9435
9436 if (aId.isZero())
9437 aSnapshot = mData->mFirstSnapshot;
9438 else
9439 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(aId.ref());
9440
9441 if (!aSnapshot)
9442 {
9443 if (aSetError)
9444 return setError(E_FAIL,
9445 tr("Could not find a snapshot with UUID {%s}"),
9446 aId.toString().c_str());
9447 return E_FAIL;
9448 }
9449
9450 return S_OK;
9451}
9452
9453/**
9454 * Returns the snapshot with the given name or fails of no such snapshot.
9455 *
9456 * @param aName snapshot name to find
9457 * @param aSnapshot where to return the found snapshot
9458 * @param aSetError true to set extended error info on failure
9459 */
9460HRESULT Machine::i_findSnapshotByName(const Utf8Str &strName,
9461 ComObjPtr<Snapshot> &aSnapshot,
9462 bool aSetError /* = false */)
9463{
9464 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
9465
9466 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9467
9468 if (!mData->mFirstSnapshot)
9469 {
9470 if (aSetError)
9471 return setError(VBOX_E_OBJECT_NOT_FOUND,
9472 tr("This machine does not have any snapshots"));
9473 return VBOX_E_OBJECT_NOT_FOUND;
9474 }
9475
9476 aSnapshot = mData->mFirstSnapshot->i_findChildOrSelf(strName);
9477
9478 if (!aSnapshot)
9479 {
9480 if (aSetError)
9481 return setError(VBOX_E_OBJECT_NOT_FOUND,
9482 tr("Could not find a snapshot named '%s'"), strName.c_str());
9483 return VBOX_E_OBJECT_NOT_FOUND;
9484 }
9485
9486 return S_OK;
9487}
9488
9489/**
9490 * Returns a storage controller object with the given name.
9491 *
9492 * @param aName storage controller name to find
9493 * @param aStorageController where to return the found storage controller
9494 * @param aSetError true to set extended error info on failure
9495 */
9496HRESULT Machine::i_getStorageControllerByName(const Utf8Str &aName,
9497 ComObjPtr<StorageController> &aStorageController,
9498 bool aSetError /* = false */)
9499{
9500 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9501
9502 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
9503 it != mStorageControllers->end();
9504 ++it)
9505 {
9506 if ((*it)->i_getName() == aName)
9507 {
9508 aStorageController = (*it);
9509 return S_OK;
9510 }
9511 }
9512
9513 if (aSetError)
9514 return setError(VBOX_E_OBJECT_NOT_FOUND,
9515 tr("Could not find a storage controller named '%s'"),
9516 aName.c_str());
9517 return VBOX_E_OBJECT_NOT_FOUND;
9518}
9519
9520/**
9521 * Returns a USB controller object with the given name.
9522 *
9523 * @param aName USB controller name to find
9524 * @param aUSBController where to return the found USB controller
9525 * @param aSetError true to set extended error info on failure
9526 */
9527HRESULT Machine::i_getUSBControllerByName(const Utf8Str &aName,
9528 ComObjPtr<USBController> &aUSBController,
9529 bool aSetError /* = false */)
9530{
9531 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9532
9533 for (USBControllerList::const_iterator it = mUSBControllers->begin();
9534 it != mUSBControllers->end();
9535 ++it)
9536 {
9537 if ((*it)->i_getName() == aName)
9538 {
9539 aUSBController = (*it);
9540 return S_OK;
9541 }
9542 }
9543
9544 if (aSetError)
9545 return setError(VBOX_E_OBJECT_NOT_FOUND,
9546 tr("Could not find a storage controller named '%s'"),
9547 aName.c_str());
9548 return VBOX_E_OBJECT_NOT_FOUND;
9549}
9550
9551/**
9552 * Returns the number of USB controller instance of the given type.
9553 *
9554 * @param enmType USB controller type.
9555 */
9556ULONG Machine::i_getUSBControllerCountByType(USBControllerType_T enmType)
9557{
9558 ULONG cCtrls = 0;
9559
9560 for (USBControllerList::const_iterator it = mUSBControllers->begin();
9561 it != mUSBControllers->end();
9562 ++it)
9563 {
9564 if ((*it)->i_getControllerType() == enmType)
9565 cCtrls++;
9566 }
9567
9568 return cCtrls;
9569}
9570
9571HRESULT Machine::i_getMediumAttachmentsOfController(const Utf8Str &aName,
9572 MediaData::AttachmentList &atts)
9573{
9574 AutoCaller autoCaller(this);
9575 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9576
9577 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9578
9579 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
9580 it != mMediaData->mAttachments.end();
9581 ++it)
9582 {
9583 const ComObjPtr<MediumAttachment> &pAtt = *it;
9584 // should never happen, but deal with NULL pointers in the list.
9585 AssertStmt(!pAtt.isNull(), continue);
9586
9587 // getControllerName() needs caller+read lock
9588 AutoCaller autoAttCaller(pAtt);
9589 if (FAILED(autoAttCaller.rc()))
9590 {
9591 atts.clear();
9592 return autoAttCaller.rc();
9593 }
9594 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
9595
9596 if (pAtt->i_getControllerName() == aName)
9597 atts.push_back(pAtt);
9598 }
9599
9600 return S_OK;
9601}
9602
9603
9604/**
9605 * Helper for #i_saveSettings. Cares about renaming the settings directory and
9606 * file if the machine name was changed and about creating a new settings file
9607 * if this is a new machine.
9608 *
9609 * @note Must be never called directly but only from #saveSettings().
9610 */
9611HRESULT Machine::i_prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
9612{
9613 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9614
9615 HRESULT rc = S_OK;
9616
9617 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
9618
9619 /// @todo need to handle primary group change, too
9620
9621 /* attempt to rename the settings file if machine name is changed */
9622 if ( mUserData->s.fNameSync
9623 && mUserData.isBackedUp()
9624 && ( mUserData.backedUpData()->s.strName != mUserData->s.strName
9625 || mUserData.backedUpData()->s.llGroups.front() != mUserData->s.llGroups.front())
9626 )
9627 {
9628 bool dirRenamed = false;
9629 bool fileRenamed = false;
9630
9631 Utf8Str configFile, newConfigFile;
9632 Utf8Str configFilePrev, newConfigFilePrev;
9633 Utf8Str configDir, newConfigDir;
9634
9635 do
9636 {
9637 int vrc = VINF_SUCCESS;
9638
9639 Utf8Str name = mUserData.backedUpData()->s.strName;
9640 Utf8Str newName = mUserData->s.strName;
9641 Utf8Str group = mUserData.backedUpData()->s.llGroups.front();
9642 if (group == "/")
9643 group.setNull();
9644 Utf8Str newGroup = mUserData->s.llGroups.front();
9645 if (newGroup == "/")
9646 newGroup.setNull();
9647
9648 configFile = mData->m_strConfigFileFull;
9649
9650 /* first, rename the directory if it matches the group and machine name */
9651 Utf8Str groupPlusName = Utf8StrFmt("%s%c%s",
9652 group.c_str(), RTPATH_DELIMITER, name.c_str());
9653 /** @todo hack, make somehow use of ComposeMachineFilename */
9654 if (mUserData->s.fDirectoryIncludesUUID)
9655 groupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9656 Utf8Str newGroupPlusName = Utf8StrFmt("%s%c%s",
9657 newGroup.c_str(), RTPATH_DELIMITER, newName.c_str());
9658 /** @todo hack, make somehow use of ComposeMachineFilename */
9659 if (mUserData->s.fDirectoryIncludesUUID)
9660 newGroupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9661 configDir = configFile;
9662 configDir.stripFilename();
9663 newConfigDir = configDir;
9664 if ( configDir.length() >= groupPlusName.length()
9665 && !RTPathCompare(configDir.substr(configDir.length() - groupPlusName.length(), groupPlusName.length()).c_str(),
9666 groupPlusName.c_str()))
9667 {
9668 newConfigDir = newConfigDir.substr(0, configDir.length() - groupPlusName.length());
9669 Utf8Str newConfigBaseDir(newConfigDir);
9670 newConfigDir.append(newGroupPlusName);
9671 /* consistency: use \ if appropriate on the platform */
9672 RTPathChangeToDosSlashes(newConfigDir.mutableRaw(), false);
9673 /* new dir and old dir cannot be equal here because of 'if'
9674 * above and because name != newName */
9675 Assert(configDir != newConfigDir);
9676 if (!fSettingsFileIsNew)
9677 {
9678 /* perform real rename only if the machine is not new */
9679 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9680 if ( vrc == VERR_FILE_NOT_FOUND
9681 || vrc == VERR_PATH_NOT_FOUND)
9682 {
9683 /* create the parent directory, then retry renaming */
9684 Utf8Str parent(newConfigDir);
9685 parent.stripFilename();
9686 (void)RTDirCreateFullPath(parent.c_str(), 0700);
9687 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9688 }
9689 if (RT_FAILURE(vrc))
9690 {
9691 rc = setError(E_FAIL,
9692 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
9693 configDir.c_str(),
9694 newConfigDir.c_str(),
9695 vrc);
9696 break;
9697 }
9698 /* delete subdirectories which are no longer needed */
9699 Utf8Str dir(configDir);
9700 dir.stripFilename();
9701 while (dir != newConfigBaseDir && dir != ".")
9702 {
9703 vrc = RTDirRemove(dir.c_str());
9704 if (RT_FAILURE(vrc))
9705 break;
9706 dir.stripFilename();
9707 }
9708 dirRenamed = true;
9709 }
9710 }
9711
9712 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
9713 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
9714
9715 /* then try to rename the settings file itself */
9716 if (newConfigFile != configFile)
9717 {
9718 /* get the path to old settings file in renamed directory */
9719 configFile = Utf8StrFmt("%s%c%s",
9720 newConfigDir.c_str(),
9721 RTPATH_DELIMITER,
9722 RTPathFilename(configFile.c_str()));
9723 if (!fSettingsFileIsNew)
9724 {
9725 /* perform real rename only if the machine is not new */
9726 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
9727 if (RT_FAILURE(vrc))
9728 {
9729 rc = setError(E_FAIL,
9730 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
9731 configFile.c_str(),
9732 newConfigFile.c_str(),
9733 vrc);
9734 break;
9735 }
9736 fileRenamed = true;
9737 configFilePrev = configFile;
9738 configFilePrev += "-prev";
9739 newConfigFilePrev = newConfigFile;
9740 newConfigFilePrev += "-prev";
9741 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
9742 }
9743 }
9744
9745 // update m_strConfigFileFull amd mConfigFile
9746 mData->m_strConfigFileFull = newConfigFile;
9747 // compute the relative path too
9748 mParent->i_copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
9749
9750 // store the old and new so that VirtualBox::i_saveSettings() can update
9751 // the media registry
9752 if ( mData->mRegistered
9753 && (configDir != newConfigDir || configFile != newConfigFile))
9754 {
9755 mParent->i_rememberMachineNameChangeForMedia(configDir, newConfigDir);
9756
9757 if (pfNeedsGlobalSaveSettings)
9758 *pfNeedsGlobalSaveSettings = true;
9759 }
9760
9761 // in the saved state file path, replace the old directory with the new directory
9762 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
9763 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
9764
9765 // and do the same thing for the saved state file paths of all the online snapshots
9766 if (mData->mFirstSnapshot)
9767 mData->mFirstSnapshot->i_updateSavedStatePaths(configDir.c_str(),
9768 newConfigDir.c_str());
9769 }
9770 while (0);
9771
9772 if (FAILED(rc))
9773 {
9774 /* silently try to rename everything back */
9775 if (fileRenamed)
9776 {
9777 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
9778 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
9779 }
9780 if (dirRenamed)
9781 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
9782 }
9783
9784 if (FAILED(rc)) return rc;
9785 }
9786
9787 if (fSettingsFileIsNew)
9788 {
9789 /* create a virgin config file */
9790 int vrc = VINF_SUCCESS;
9791
9792 /* ensure the settings directory exists */
9793 Utf8Str path(mData->m_strConfigFileFull);
9794 path.stripFilename();
9795 if (!RTDirExists(path.c_str()))
9796 {
9797 vrc = RTDirCreateFullPath(path.c_str(), 0700);
9798 if (RT_FAILURE(vrc))
9799 {
9800 return setError(E_FAIL,
9801 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
9802 path.c_str(),
9803 vrc);
9804 }
9805 }
9806
9807 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
9808 path = Utf8Str(mData->m_strConfigFileFull);
9809 RTFILE f = NIL_RTFILE;
9810 vrc = RTFileOpen(&f, path.c_str(),
9811 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
9812 if (RT_FAILURE(vrc))
9813 return setError(E_FAIL,
9814 tr("Could not create the settings file '%s' (%Rrc)"),
9815 path.c_str(),
9816 vrc);
9817 RTFileClose(f);
9818 }
9819
9820 return rc;
9821}
9822
9823/**
9824 * Saves and commits machine data, user data and hardware data.
9825 *
9826 * Note that on failure, the data remains uncommitted.
9827 *
9828 * @a aFlags may combine the following flags:
9829 *
9830 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
9831 * Used when saving settings after an operation that makes them 100%
9832 * correspond to the settings from the current snapshot.
9833 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
9834 * #isReallyModified() returns false. This is necessary for cases when we
9835 * change machine data directly, not through the backup()/commit() mechanism.
9836 * - SaveS_Force: settings will be saved without doing a deep compare of the
9837 * settings structures. This is used when this is called because snapshots
9838 * have changed to avoid the overhead of the deep compare.
9839 *
9840 * @note Must be called from under this object's write lock. Locks children for
9841 * writing.
9842 *
9843 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
9844 * initialized to false and that will be set to true by this function if
9845 * the caller must invoke VirtualBox::i_saveSettings() because the global
9846 * settings have changed. This will happen if a machine rename has been
9847 * saved and the global machine and media registries will therefore need
9848 * updating.
9849 */
9850HRESULT Machine::i_saveSettings(bool *pfNeedsGlobalSaveSettings,
9851 int aFlags /*= 0*/)
9852{
9853 LogFlowThisFuncEnter();
9854
9855 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9856
9857 /* make sure child objects are unable to modify the settings while we are
9858 * saving them */
9859 i_ensureNoStateDependencies();
9860
9861 AssertReturn(!i_isSnapshotMachine(),
9862 E_FAIL);
9863
9864 HRESULT rc = S_OK;
9865 bool fNeedsWrite = false;
9866
9867 /* First, prepare to save settings. It will care about renaming the
9868 * settings directory and file if the machine name was changed and about
9869 * creating a new settings file if this is a new machine. */
9870 rc = i_prepareSaveSettings(pfNeedsGlobalSaveSettings);
9871 if (FAILED(rc)) return rc;
9872
9873 // keep a pointer to the current settings structures
9874 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
9875 settings::MachineConfigFile *pNewConfig = NULL;
9876
9877 try
9878 {
9879 // make a fresh one to have everyone write stuff into
9880 pNewConfig = new settings::MachineConfigFile(NULL);
9881 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
9882
9883 // now go and copy all the settings data from COM to the settings structures
9884 // (this calles i_saveSettings() on all the COM objects in the machine)
9885 i_copyMachineDataToSettings(*pNewConfig);
9886
9887 if (aFlags & SaveS_ResetCurStateModified)
9888 {
9889 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
9890 mData->mCurrentStateModified = FALSE;
9891 fNeedsWrite = true; // always, no need to compare
9892 }
9893 else if (aFlags & SaveS_Force)
9894 {
9895 fNeedsWrite = true; // always, no need to compare
9896 }
9897 else
9898 {
9899 if (!mData->mCurrentStateModified)
9900 {
9901 // do a deep compare of the settings that we just saved with the settings
9902 // previously stored in the config file; this invokes MachineConfigFile::operator==
9903 // which does a deep compare of all the settings, which is expensive but less expensive
9904 // than writing out XML in vain
9905 bool fAnySettingsChanged = !(*pNewConfig == *pOldConfig);
9906
9907 // could still be modified if any settings changed
9908 mData->mCurrentStateModified = fAnySettingsChanged;
9909
9910 fNeedsWrite = fAnySettingsChanged;
9911 }
9912 else
9913 fNeedsWrite = true;
9914 }
9915
9916 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
9917
9918 if (fNeedsWrite)
9919 // now spit it all out!
9920 pNewConfig->write(mData->m_strConfigFileFull);
9921
9922 mData->pMachineConfigFile = pNewConfig;
9923 delete pOldConfig;
9924 i_commit();
9925
9926 // after saving settings, we are no longer different from the XML on disk
9927 mData->flModifications = 0;
9928 }
9929 catch (HRESULT err)
9930 {
9931 // we assume that error info is set by the thrower
9932 rc = err;
9933
9934 // restore old config
9935 delete pNewConfig;
9936 mData->pMachineConfigFile = pOldConfig;
9937 }
9938 catch (...)
9939 {
9940 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
9941 }
9942
9943 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
9944 {
9945 /* Fire the data change event, even on failure (since we've already
9946 * committed all data). This is done only for SessionMachines because
9947 * mutable Machine instances are always not registered (i.e. private
9948 * to the client process that creates them) and thus don't need to
9949 * inform callbacks. */
9950 if (i_isSessionMachine())
9951 mParent->i_onMachineDataChange(mData->mUuid);
9952 }
9953
9954 LogFlowThisFunc(("rc=%08X\n", rc));
9955 LogFlowThisFuncLeave();
9956 return rc;
9957}
9958
9959/**
9960 * Implementation for saving the machine settings into the given
9961 * settings::MachineConfigFile instance. This copies machine extradata
9962 * from the previous machine config file in the instance data, if any.
9963 *
9964 * This gets called from two locations:
9965 *
9966 * -- Machine::i_saveSettings(), during the regular XML writing;
9967 *
9968 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
9969 * exported to OVF and we write the VirtualBox proprietary XML
9970 * into a <vbox:Machine> tag.
9971 *
9972 * This routine fills all the fields in there, including snapshots, *except*
9973 * for the following:
9974 *
9975 * -- fCurrentStateModified. There is some special logic associated with that.
9976 *
9977 * The caller can then call MachineConfigFile::write() or do something else
9978 * with it.
9979 *
9980 * Caller must hold the machine lock!
9981 *
9982 * This throws XML errors and HRESULT, so the caller must have a catch block!
9983 */
9984void Machine::i_copyMachineDataToSettings(settings::MachineConfigFile &config)
9985{
9986 // deep copy extradata
9987 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
9988
9989 config.uuid = mData->mUuid;
9990
9991 // copy name, description, OS type, teleport, UTC etc.
9992 config.machineUserData = mUserData->s;
9993
9994 // Encode the Icon Override data from Machine and store on config userdata.
9995 std::vector<BYTE> iconByte;
9996 getIcon(iconByte);
9997 ssize_t cbData = iconByte.size();
9998 if (cbData > 0)
9999 {
10000 ssize_t cchOut = RTBase64EncodedLength(cbData);
10001 Utf8Str strIconData;
10002 strIconData.reserve(cchOut+1);
10003 int vrc = RTBase64Encode(&iconByte.front(), cbData,
10004 strIconData.mutableRaw(), strIconData.capacity(),
10005 NULL);
10006 if (RT_FAILURE(vrc))
10007 throw setError(E_FAIL, tr("Failure to Encode Icon Data. '%s' (%Rrc)"), strIconData.mutableRaw(), vrc);
10008 strIconData.jolt();
10009 config.machineUserData.ovIcon = strIconData;
10010 }
10011 else
10012 config.machineUserData.ovIcon.setNull();
10013
10014 if ( mData->mMachineState == MachineState_Saved
10015 || mData->mMachineState == MachineState_Restoring
10016 // when doing certain snapshot operations we may or may not have
10017 // a saved state in the current state, so keep everything as is
10018 || ( ( mData->mMachineState == MachineState_Snapshotting
10019 || mData->mMachineState == MachineState_DeletingSnapshot
10020 || mData->mMachineState == MachineState_RestoringSnapshot)
10021 && (!mSSData->strStateFilePath.isEmpty())
10022 )
10023 )
10024 {
10025 Assert(!mSSData->strStateFilePath.isEmpty());
10026 /* try to make the file name relative to the settings file dir */
10027 i_copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
10028 }
10029 else
10030 {
10031 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
10032 config.strStateFile.setNull();
10033 }
10034
10035 if (mData->mCurrentSnapshot)
10036 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->i_getId();
10037 else
10038 config.uuidCurrentSnapshot.clear();
10039
10040 config.timeLastStateChange = mData->mLastStateChange;
10041 config.fAborted = (mData->mMachineState == MachineState_Aborted);
10042 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
10043
10044 HRESULT rc = i_saveHardware(config.hardwareMachine, &config.debugging, &config.autostart);
10045 if (FAILED(rc)) throw rc;
10046
10047 rc = i_saveStorageControllers(config.storageMachine);
10048 if (FAILED(rc)) throw rc;
10049
10050 // save machine's media registry if this is VirtualBox 4.0 or later
10051 if (config.canHaveOwnMediaRegistry())
10052 {
10053 // determine machine folder
10054 Utf8Str strMachineFolder = i_getSettingsFileFull();
10055 strMachineFolder.stripFilename();
10056 mParent->i_saveMediaRegistry(config.mediaRegistry,
10057 i_getId(), // only media with registry ID == machine UUID
10058 strMachineFolder);
10059 // this throws HRESULT
10060 }
10061
10062 // save snapshots
10063 rc = i_saveAllSnapshots(config);
10064 if (FAILED(rc)) throw rc;
10065}
10066
10067/**
10068 * Saves all snapshots of the machine into the given machine config file. Called
10069 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
10070 * @param config
10071 * @return
10072 */
10073HRESULT Machine::i_saveAllSnapshots(settings::MachineConfigFile &config)
10074{
10075 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10076
10077 HRESULT rc = S_OK;
10078
10079 try
10080 {
10081 config.llFirstSnapshot.clear();
10082
10083 if (mData->mFirstSnapshot)
10084 {
10085 // the settings use a list for "the first snapshot"
10086 config.llFirstSnapshot.push_back(settings::g_SnapshotEmpty);
10087
10088 // get reference to the snapshot on the list and work on that
10089 // element straight in the list to avoid excessive copying later
10090 rc = mData->mFirstSnapshot->i_saveSnapshot(config.llFirstSnapshot.back());
10091 if (FAILED(rc)) throw rc;
10092 }
10093
10094// if (mType == IsSessionMachine)
10095// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
10096
10097 }
10098 catch (HRESULT err)
10099 {
10100 /* we assume that error info is set by the thrower */
10101 rc = err;
10102 }
10103 catch (...)
10104 {
10105 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10106 }
10107
10108 return rc;
10109}
10110
10111/**
10112 * Saves the VM hardware configuration. It is assumed that the
10113 * given node is empty.
10114 *
10115 * @param data Reference to the settings object for the hardware config.
10116 * @param pDbg Pointer to the settings object for the debugging config
10117 * which happens to live in mHWData.
10118 * @param pAutostart Pointer to the settings object for the autostart config
10119 * which happens to live in mHWData.
10120 */
10121HRESULT Machine::i_saveHardware(settings::Hardware &data, settings::Debugging *pDbg,
10122 settings::Autostart *pAutostart)
10123{
10124 HRESULT rc = S_OK;
10125
10126 try
10127 {
10128 /* The hardware version attribute (optional).
10129 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
10130 if ( mHWData->mHWVersion == "1"
10131 && mSSData->strStateFilePath.isEmpty()
10132 )
10133 mHWData->mHWVersion = "2"; /** @todo Is this safe, to update mHWVersion here? If not some
10134 other point needs to be found where this can be done. */
10135
10136 data.strVersion = mHWData->mHWVersion;
10137 data.uuid = mHWData->mHardwareUUID;
10138
10139 // CPU
10140 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
10141 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
10142 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
10143 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
10144 data.fUnrestrictedExecution = !!mHWData->mHWVirtExUXEnabled;
10145 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
10146 data.fPAE = !!mHWData->mPAEEnabled;
10147 data.enmLongMode = mHWData->mLongMode;
10148 data.fTripleFaultReset = !!mHWData->mTripleFaultReset;
10149 data.cCPUs = mHWData->mCPUCount;
10150 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
10151 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
10152 data.uCpuIdPortabilityLevel = mHWData->mCpuIdPortabilityLevel;
10153
10154 data.llCpus.clear();
10155 if (data.fCpuHotPlug)
10156 {
10157 for (unsigned idx = 0; idx < data.cCPUs; ++idx)
10158 {
10159 if (mHWData->mCPUAttached[idx])
10160 {
10161 settings::Cpu cpu;
10162 cpu.ulId = idx;
10163 data.llCpus.push_back(cpu);
10164 }
10165 }
10166 }
10167
10168 /* Standard and Extended CPUID leafs. */
10169 data.llCpuIdLeafs.clear();
10170 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); ++idx)
10171 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
10172 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
10173 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); ++idx)
10174 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
10175 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
10176
10177 // memory
10178 data.ulMemorySizeMB = mHWData->mMemorySize;
10179 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
10180
10181 // firmware
10182 data.firmwareType = mHWData->mFirmwareType;
10183
10184 // HID
10185 data.pointingHIDType = mHWData->mPointingHIDType;
10186 data.keyboardHIDType = mHWData->mKeyboardHIDType;
10187
10188 // chipset
10189 data.chipsetType = mHWData->mChipsetType;
10190
10191 // paravirt
10192 data.paravirtProvider = mHWData->mParavirtProvider;
10193
10194
10195 data.fEmulatedUSBCardReader = !!mHWData->mEmulatedUSBCardReaderEnabled;
10196
10197 // HPET
10198 data.fHPETEnabled = !!mHWData->mHPETEnabled;
10199
10200 // boot order
10201 data.mapBootOrder.clear();
10202 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mBootOrder); ++i)
10203 data.mapBootOrder[i] = mHWData->mBootOrder[i];
10204
10205 // display
10206 data.graphicsControllerType = mHWData->mGraphicsControllerType;
10207 data.ulVRAMSizeMB = mHWData->mVRAMSize;
10208 data.cMonitors = mHWData->mMonitorCount;
10209 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
10210 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
10211 data.ulVideoCaptureHorzRes = mHWData->mVideoCaptureWidth;
10212 data.ulVideoCaptureVertRes = mHWData->mVideoCaptureHeight;
10213 data.ulVideoCaptureRate = mHWData->mVideoCaptureRate;
10214 data.ulVideoCaptureFPS = mHWData->mVideoCaptureFPS;
10215 data.fVideoCaptureEnabled = !!mHWData->mVideoCaptureEnabled;
10216 for (unsigned i = 0; i < sizeof(data.u64VideoCaptureScreens) * 8; ++i)
10217 {
10218 if (mHWData->maVideoCaptureScreens[i])
10219 ASMBitSet(&data.u64VideoCaptureScreens, i);
10220 else
10221 ASMBitClear(&data.u64VideoCaptureScreens, i);
10222 }
10223 /* store relative video capture file if possible */
10224 i_copyPathRelativeToMachine(mHWData->mVideoCaptureFile, data.strVideoCaptureFile);
10225
10226 /* VRDEServer settings (optional) */
10227 rc = mVRDEServer->i_saveSettings(data.vrdeSettings);
10228 if (FAILED(rc)) throw rc;
10229
10230 /* BIOS (required) */
10231 rc = mBIOSSettings->i_saveSettings(data.biosSettings);
10232 if (FAILED(rc)) throw rc;
10233
10234 /* USB Controller (required) */
10235 data.usbSettings.llUSBControllers.clear();
10236 for (USBControllerList::const_iterator it = mUSBControllers->begin(); it != mUSBControllers->end(); ++it)
10237 {
10238 ComObjPtr<USBController> ctrl = *it;
10239 settings::USBController settingsCtrl;
10240
10241 settingsCtrl.strName = ctrl->i_getName();
10242 settingsCtrl.enmType = ctrl->i_getControllerType();
10243
10244 data.usbSettings.llUSBControllers.push_back(settingsCtrl);
10245 }
10246
10247 /* USB device filters (required) */
10248 rc = mUSBDeviceFilters->i_saveSettings(data.usbSettings);
10249 if (FAILED(rc)) throw rc;
10250
10251 /* Network adapters (required) */
10252 size_t uMaxNICs = RT_MIN(Global::getMaxNetworkAdapters(mHWData->mChipsetType), mNetworkAdapters.size());
10253 data.llNetworkAdapters.clear();
10254 /* Write out only the nominal number of network adapters for this
10255 * chipset type. Since Machine::commit() hasn't been called there
10256 * may be extra NIC settings in the vector. */
10257 for (size_t slot = 0; slot < uMaxNICs; ++slot)
10258 {
10259 settings::NetworkAdapter nic;
10260 nic.ulSlot = (uint32_t)slot;
10261 /* paranoia check... must not be NULL, but must not crash either. */
10262 if (mNetworkAdapters[slot])
10263 {
10264 rc = mNetworkAdapters[slot]->i_saveSettings(nic);
10265 if (FAILED(rc)) throw rc;
10266
10267 data.llNetworkAdapters.push_back(nic);
10268 }
10269 }
10270
10271 /* Serial ports */
10272 data.llSerialPorts.clear();
10273 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
10274 {
10275 settings::SerialPort s;
10276 s.ulSlot = slot;
10277 rc = mSerialPorts[slot]->i_saveSettings(s);
10278 if (FAILED(rc)) return rc;
10279
10280 data.llSerialPorts.push_back(s);
10281 }
10282
10283 /* Parallel ports */
10284 data.llParallelPorts.clear();
10285 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
10286 {
10287 settings::ParallelPort p;
10288 p.ulSlot = slot;
10289 rc = mParallelPorts[slot]->i_saveSettings(p);
10290 if (FAILED(rc)) return rc;
10291
10292 data.llParallelPorts.push_back(p);
10293 }
10294
10295 /* Audio adapter */
10296 rc = mAudioAdapter->i_saveSettings(data.audioAdapter);
10297 if (FAILED(rc)) return rc;
10298
10299 /* Shared folders */
10300 data.llSharedFolders.clear();
10301 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
10302 it != mHWData->mSharedFolders.end();
10303 ++it)
10304 {
10305 SharedFolder *pSF = *it;
10306 AutoCaller sfCaller(pSF);
10307 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
10308 settings::SharedFolder sf;
10309 sf.strName = pSF->i_getName();
10310 sf.strHostPath = pSF->i_getHostPath();
10311 sf.fWritable = !!pSF->i_isWritable();
10312 sf.fAutoMount = !!pSF->i_isAutoMounted();
10313
10314 data.llSharedFolders.push_back(sf);
10315 }
10316
10317 // clipboard
10318 data.clipboardMode = mHWData->mClipboardMode;
10319
10320 // drag'n'drop
10321 data.dndMode = mHWData->mDnDMode;
10322
10323 /* Guest */
10324 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
10325
10326 // IO settings
10327 data.ioSettings.fIOCacheEnabled = !!mHWData->mIOCacheEnabled;
10328 data.ioSettings.ulIOCacheSize = mHWData->mIOCacheSize;
10329
10330 /* BandwidthControl (required) */
10331 rc = mBandwidthControl->i_saveSettings(data.ioSettings);
10332 if (FAILED(rc)) throw rc;
10333
10334 /* Host PCI devices */
10335 for (HWData::PCIDeviceAssignmentList::const_iterator it = mHWData->mPCIDeviceAssignments.begin();
10336 it != mHWData->mPCIDeviceAssignments.end();
10337 ++it)
10338 {
10339 ComObjPtr<PCIDeviceAttachment> pda = *it;
10340 settings::HostPCIDeviceAttachment hpda;
10341
10342 rc = pda->i_saveSettings(hpda);
10343 if (FAILED(rc)) throw rc;
10344
10345 data.pciAttachments.push_back(hpda);
10346 }
10347
10348
10349 // guest properties
10350 data.llGuestProperties.clear();
10351#ifdef VBOX_WITH_GUEST_PROPS
10352 for (HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.begin();
10353 it != mHWData->mGuestProperties.end();
10354 ++it)
10355 {
10356 HWData::GuestProperty property = it->second;
10357
10358 /* Remove transient guest properties at shutdown unless we
10359 * are saving state. Note that restoring snapshot intentionally
10360 * keeps them, they will be removed if appropriate once the final
10361 * machine state is set (as crashes etc. need to work). */
10362 if ( ( mData->mMachineState == MachineState_PoweredOff
10363 || mData->mMachineState == MachineState_Aborted
10364 || mData->mMachineState == MachineState_Teleported)
10365 && ( property.mFlags & guestProp::TRANSIENT
10366 || property.mFlags & guestProp::TRANSRESET))
10367 continue;
10368 settings::GuestProperty prop;
10369 prop.strName = it->first;
10370 prop.strValue = property.strValue;
10371 prop.timestamp = property.mTimestamp;
10372 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
10373 guestProp::writeFlags(property.mFlags, szFlags);
10374 prop.strFlags = szFlags;
10375
10376 data.llGuestProperties.push_back(prop);
10377 }
10378
10379 /* I presume this doesn't require a backup(). */
10380 mData->mGuestPropertiesModified = FALSE;
10381#endif /* VBOX_WITH_GUEST_PROPS defined */
10382
10383 *pDbg = mHWData->mDebugging;
10384 *pAutostart = mHWData->mAutostart;
10385
10386 data.strDefaultFrontend = mHWData->mDefaultFrontend;
10387 }
10388 catch(std::bad_alloc &)
10389 {
10390 return E_OUTOFMEMORY;
10391 }
10392
10393 AssertComRC(rc);
10394 return rc;
10395}
10396
10397/**
10398 * Saves the storage controller configuration.
10399 *
10400 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
10401 */
10402HRESULT Machine::i_saveStorageControllers(settings::Storage &data)
10403{
10404 data.llStorageControllers.clear();
10405
10406 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
10407 it != mStorageControllers->end();
10408 ++it)
10409 {
10410 HRESULT rc;
10411 ComObjPtr<StorageController> pCtl = *it;
10412
10413 settings::StorageController ctl;
10414 ctl.strName = pCtl->i_getName();
10415 ctl.controllerType = pCtl->i_getControllerType();
10416 ctl.storageBus = pCtl->i_getStorageBus();
10417 ctl.ulInstance = pCtl->i_getInstance();
10418 ctl.fBootable = pCtl->i_getBootable();
10419
10420 /* Save the port count. */
10421 ULONG portCount;
10422 rc = pCtl->COMGETTER(PortCount)(&portCount);
10423 ComAssertComRCRet(rc, rc);
10424 ctl.ulPortCount = portCount;
10425
10426 /* Save fUseHostIOCache */
10427 BOOL fUseHostIOCache;
10428 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
10429 ComAssertComRCRet(rc, rc);
10430 ctl.fUseHostIOCache = !!fUseHostIOCache;
10431
10432 /* save the devices now. */
10433 rc = i_saveStorageDevices(pCtl, ctl);
10434 ComAssertComRCRet(rc, rc);
10435
10436 data.llStorageControllers.push_back(ctl);
10437 }
10438
10439 return S_OK;
10440}
10441
10442/**
10443 * Saves the hard disk configuration.
10444 */
10445HRESULT Machine::i_saveStorageDevices(ComObjPtr<StorageController> aStorageController,
10446 settings::StorageController &data)
10447{
10448 MediaData::AttachmentList atts;
10449
10450 HRESULT rc = i_getMediumAttachmentsOfController(aStorageController->i_getName(), atts);
10451 if (FAILED(rc)) return rc;
10452
10453 data.llAttachedDevices.clear();
10454 for (MediaData::AttachmentList::const_iterator it = atts.begin();
10455 it != atts.end();
10456 ++it)
10457 {
10458 settings::AttachedDevice dev;
10459 IMediumAttachment *iA = *it;
10460 MediumAttachment *pAttach = static_cast<MediumAttachment *>(iA);
10461 Medium *pMedium = pAttach->i_getMedium();
10462
10463 dev.deviceType = pAttach->i_getType();
10464 dev.lPort = pAttach->i_getPort();
10465 dev.lDevice = pAttach->i_getDevice();
10466 dev.fPassThrough = pAttach->i_getPassthrough();
10467 dev.fHotPluggable = pAttach->i_getHotPluggable();
10468 if (pMedium)
10469 {
10470 if (pMedium->i_isHostDrive())
10471 dev.strHostDriveSrc = pMedium->i_getLocationFull();
10472 else
10473 dev.uuid = pMedium->i_getId();
10474 dev.fTempEject = pAttach->i_getTempEject();
10475 dev.fNonRotational = pAttach->i_getNonRotational();
10476 dev.fDiscard = pAttach->i_getDiscard();
10477 }
10478
10479 dev.strBwGroup = pAttach->i_getBandwidthGroup();
10480
10481 data.llAttachedDevices.push_back(dev);
10482 }
10483
10484 return S_OK;
10485}
10486
10487/**
10488 * Saves machine state settings as defined by aFlags
10489 * (SaveSTS_* values).
10490 *
10491 * @param aFlags Combination of SaveSTS_* flags.
10492 *
10493 * @note Locks objects for writing.
10494 */
10495HRESULT Machine::i_saveStateSettings(int aFlags)
10496{
10497 if (aFlags == 0)
10498 return S_OK;
10499
10500 AutoCaller autoCaller(this);
10501 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10502
10503 /* This object's write lock is also necessary to serialize file access
10504 * (prevent concurrent reads and writes) */
10505 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10506
10507 HRESULT rc = S_OK;
10508
10509 Assert(mData->pMachineConfigFile);
10510
10511 try
10512 {
10513 if (aFlags & SaveSTS_CurStateModified)
10514 mData->pMachineConfigFile->fCurrentStateModified = true;
10515
10516 if (aFlags & SaveSTS_StateFilePath)
10517 {
10518 if (!mSSData->strStateFilePath.isEmpty())
10519 /* try to make the file name relative to the settings file dir */
10520 i_copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
10521 else
10522 mData->pMachineConfigFile->strStateFile.setNull();
10523 }
10524
10525 if (aFlags & SaveSTS_StateTimeStamp)
10526 {
10527 Assert( mData->mMachineState != MachineState_Aborted
10528 || mSSData->strStateFilePath.isEmpty());
10529
10530 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
10531
10532 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
10533//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
10534 }
10535
10536 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
10537 }
10538 catch (...)
10539 {
10540 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10541 }
10542
10543 return rc;
10544}
10545
10546/**
10547 * Ensures that the given medium is added to a media registry. If this machine
10548 * was created with 4.0 or later, then the machine registry is used. Otherwise
10549 * the global VirtualBox media registry is used.
10550 *
10551 * Caller must NOT hold machine lock, media tree or any medium locks!
10552 *
10553 * @param pMedium
10554 */
10555void Machine::i_addMediumToRegistry(ComObjPtr<Medium> &pMedium)
10556{
10557 /* Paranoia checks: do not hold machine or media tree locks. */
10558 AssertReturnVoid(!isWriteLockOnCurrentThread());
10559 AssertReturnVoid(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
10560
10561 ComObjPtr<Medium> pBase;
10562 {
10563 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10564 pBase = pMedium->i_getBase();
10565 }
10566
10567 /* Paranoia checks: do not hold medium locks. */
10568 AssertReturnVoid(!pMedium->isWriteLockOnCurrentThread());
10569 AssertReturnVoid(!pBase->isWriteLockOnCurrentThread());
10570
10571 // decide which medium registry to use now that the medium is attached:
10572 Guid uuid;
10573 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
10574 // machine XML is VirtualBox 4.0 or higher:
10575 uuid = i_getId(); // machine UUID
10576 else
10577 uuid = mParent->i_getGlobalRegistryId(); // VirtualBox global registry UUID
10578
10579 if (pMedium->i_addRegistry(uuid))
10580 mParent->i_markRegistryModified(uuid);
10581
10582 /* For more complex hard disk structures it can happen that the base
10583 * medium isn't yet associated with any medium registry. Do that now. */
10584 if (pMedium != pBase)
10585 {
10586 /* Tree lock needed by Medium::addRegistry when recursing. */
10587 AutoReadLock treeLock(&mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10588 if (pBase->i_addRegistryRecursive(uuid))
10589 {
10590 treeLock.release();
10591 mParent->i_markRegistryModified(uuid);
10592 }
10593 }
10594}
10595
10596/**
10597 * Creates differencing hard disks for all normal hard disks attached to this
10598 * machine and a new set of attachments to refer to created disks.
10599 *
10600 * Used when taking a snapshot or when deleting the current state. Gets called
10601 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
10602 *
10603 * This method assumes that mMediaData contains the original hard disk attachments
10604 * it needs to create diffs for. On success, these attachments will be replaced
10605 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
10606 * called to delete created diffs which will also rollback mMediaData and restore
10607 * whatever was backed up before calling this method.
10608 *
10609 * Attachments with non-normal hard disks are left as is.
10610 *
10611 * If @a aOnline is @c false then the original hard disks that require implicit
10612 * diffs will be locked for reading. Otherwise it is assumed that they are
10613 * already locked for writing (when the VM was started). Note that in the latter
10614 * case it is responsibility of the caller to lock the newly created diffs for
10615 * writing if this method succeeds.
10616 *
10617 * @param aProgress Progress object to run (must contain at least as
10618 * many operations left as the number of hard disks
10619 * attached).
10620 * @param aOnline Whether the VM was online prior to this operation.
10621 *
10622 * @note The progress object is not marked as completed, neither on success nor
10623 * on failure. This is a responsibility of the caller.
10624 *
10625 * @note Locks this object and the media tree for writing.
10626 */
10627HRESULT Machine::i_createImplicitDiffs(IProgress *aProgress,
10628 ULONG aWeight,
10629 bool aOnline)
10630{
10631 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10632
10633 AutoCaller autoCaller(this);
10634 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10635
10636 AutoMultiWriteLock2 alock(this->lockHandle(),
10637 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10638
10639 /* must be in a protective state because we release the lock below */
10640 AssertReturn( mData->mMachineState == MachineState_Snapshotting
10641 || mData->mMachineState == MachineState_OnlineSnapshotting
10642 || mData->mMachineState == MachineState_LiveSnapshotting
10643 || mData->mMachineState == MachineState_RestoringSnapshot
10644 || mData->mMachineState == MachineState_DeletingSnapshot
10645 , E_FAIL);
10646
10647 HRESULT rc = S_OK;
10648
10649 // use appropriate locked media map (online or offline)
10650 MediumLockListMap lockedMediaOffline;
10651 MediumLockListMap *lockedMediaMap;
10652 if (aOnline)
10653 lockedMediaMap = &mData->mSession.mLockedMedia;
10654 else
10655 lockedMediaMap = &lockedMediaOffline;
10656
10657 try
10658 {
10659 if (!aOnline)
10660 {
10661 /* lock all attached hard disks early to detect "in use"
10662 * situations before creating actual diffs */
10663 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10664 it != mMediaData->mAttachments.end();
10665 ++it)
10666 {
10667 MediumAttachment* pAtt = *it;
10668 if (pAtt->i_getType() == DeviceType_HardDisk)
10669 {
10670 Medium* pMedium = pAtt->i_getMedium();
10671 Assert(pMedium);
10672
10673 MediumLockList *pMediumLockList(new MediumLockList());
10674 alock.release();
10675 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
10676 false /* fMediumLockWrite */,
10677 false /* fMediumLockWriteAll */,
10678 NULL,
10679 *pMediumLockList);
10680 alock.acquire();
10681 if (FAILED(rc))
10682 {
10683 delete pMediumLockList;
10684 throw rc;
10685 }
10686 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10687 if (FAILED(rc))
10688 {
10689 throw setError(rc,
10690 tr("Collecting locking information for all attached media failed"));
10691 }
10692 }
10693 }
10694
10695 /* Now lock all media. If this fails, nothing is locked. */
10696 alock.release();
10697 rc = lockedMediaMap->Lock();
10698 alock.acquire();
10699 if (FAILED(rc))
10700 {
10701 throw setError(rc,
10702 tr("Locking of attached media failed"));
10703 }
10704 }
10705
10706 /* remember the current list (note that we don't use backup() since
10707 * mMediaData may be already backed up) */
10708 MediaData::AttachmentList atts = mMediaData->mAttachments;
10709
10710 /* start from scratch */
10711 mMediaData->mAttachments.clear();
10712
10713 /* go through remembered attachments and create diffs for normal hard
10714 * disks and attach them */
10715 for (MediaData::AttachmentList::const_iterator it = atts.begin();
10716 it != atts.end();
10717 ++it)
10718 {
10719 MediumAttachment* pAtt = *it;
10720
10721 DeviceType_T devType = pAtt->i_getType();
10722 Medium* pMedium = pAtt->i_getMedium();
10723
10724 if ( devType != DeviceType_HardDisk
10725 || pMedium == NULL
10726 || pMedium->i_getType() != MediumType_Normal)
10727 {
10728 /* copy the attachment as is */
10729
10730 /** @todo the progress object created in SessionMachine::TakeSnaphot
10731 * only expects operations for hard disks. Later other
10732 * device types need to show up in the progress as well. */
10733 if (devType == DeviceType_HardDisk)
10734 {
10735 if (pMedium == NULL)
10736 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
10737 aWeight); // weight
10738 else
10739 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
10740 pMedium->i_getBase()->i_getName().c_str()).raw(),
10741 aWeight); // weight
10742 }
10743
10744 mMediaData->mAttachments.push_back(pAtt);
10745 continue;
10746 }
10747
10748 /* need a diff */
10749 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
10750 pMedium->i_getBase()->i_getName().c_str()).raw(),
10751 aWeight); // weight
10752
10753 Utf8Str strFullSnapshotFolder;
10754 i_calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10755
10756 ComObjPtr<Medium> diff;
10757 diff.createObject();
10758 // store the diff in the same registry as the parent
10759 // (this cannot fail here because we can't create implicit diffs for
10760 // unregistered images)
10761 Guid uuidRegistryParent;
10762 bool fInRegistry = pMedium->i_getFirstRegistryMachineId(uuidRegistryParent);
10763 Assert(fInRegistry); NOREF(fInRegistry);
10764 rc = diff->init(mParent,
10765 pMedium->i_getPreferredDiffFormat(),
10766 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
10767 uuidRegistryParent,
10768 DeviceType_HardDisk);
10769 if (FAILED(rc)) throw rc;
10770
10771 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
10772 * the push_back? Looks like we're going to release medium with the
10773 * wrong kind of lock (general issue with if we fail anywhere at all)
10774 * and an orphaned VDI in the snapshots folder. */
10775
10776 /* update the appropriate lock list */
10777 MediumLockList *pMediumLockList;
10778 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
10779 AssertComRCThrowRC(rc);
10780 if (aOnline)
10781 {
10782 alock.release();
10783 /* The currently attached medium will be read-only, change
10784 * the lock type to read. */
10785 rc = pMediumLockList->Update(pMedium, false);
10786 alock.acquire();
10787 AssertComRCThrowRC(rc);
10788 }
10789
10790 /* release the locks before the potentially lengthy operation */
10791 alock.release();
10792 rc = pMedium->i_createDiffStorage(diff, MediumVariant_Standard,
10793 pMediumLockList,
10794 NULL /* aProgress */,
10795 true /* aWait */);
10796 alock.acquire();
10797 if (FAILED(rc)) throw rc;
10798
10799 /* actual lock list update is done in Medium::commitMedia */
10800
10801 rc = diff->i_addBackReference(mData->mUuid);
10802 AssertComRCThrowRC(rc);
10803
10804 /* add a new attachment */
10805 ComObjPtr<MediumAttachment> attachment;
10806 attachment.createObject();
10807 rc = attachment->init(this,
10808 diff,
10809 pAtt->i_getControllerName(),
10810 pAtt->i_getPort(),
10811 pAtt->i_getDevice(),
10812 DeviceType_HardDisk,
10813 true /* aImplicit */,
10814 false /* aPassthrough */,
10815 false /* aTempEject */,
10816 pAtt->i_getNonRotational(),
10817 pAtt->i_getDiscard(),
10818 pAtt->i_getHotPluggable(),
10819 pAtt->i_getBandwidthGroup());
10820 if (FAILED(rc)) throw rc;
10821
10822 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
10823 AssertComRCThrowRC(rc);
10824 mMediaData->mAttachments.push_back(attachment);
10825 }
10826 }
10827 catch (HRESULT aRC) { rc = aRC; }
10828
10829 /* unlock all hard disks we locked when there is no VM */
10830 if (!aOnline)
10831 {
10832 ErrorInfoKeeper eik;
10833
10834 HRESULT rc1 = lockedMediaMap->Clear();
10835 AssertComRC(rc1);
10836 }
10837
10838 return rc;
10839}
10840
10841/**
10842 * Deletes implicit differencing hard disks created either by
10843 * #createImplicitDiffs() or by #AttachDevice() and rolls back mMediaData.
10844 *
10845 * Note that to delete hard disks created by #AttachDevice() this method is
10846 * called from #fixupMedia() when the changes are rolled back.
10847 *
10848 * @note Locks this object and the media tree for writing.
10849 */
10850HRESULT Machine::i_deleteImplicitDiffs(bool aOnline)
10851{
10852 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10853
10854 AutoCaller autoCaller(this);
10855 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10856
10857 AutoMultiWriteLock2 alock(this->lockHandle(),
10858 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10859
10860 /* We absolutely must have backed up state. */
10861 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
10862
10863 /* Check if there are any implicitly created diff images. */
10864 bool fImplicitDiffs = false;
10865 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10866 it != mMediaData->mAttachments.end();
10867 ++it)
10868 {
10869 const ComObjPtr<MediumAttachment> &pAtt = *it;
10870 if (pAtt->i_isImplicit())
10871 {
10872 fImplicitDiffs = true;
10873 break;
10874 }
10875 }
10876 /* If there is nothing to do, leave early. This saves lots of image locking
10877 * effort. It also avoids a MachineStateChanged event without real reason.
10878 * This is important e.g. when loading a VM config, because there should be
10879 * no events. Otherwise API clients can become thoroughly confused for
10880 * inaccessible VMs (the code for loading VM configs uses this method for
10881 * cleanup if the config makes no sense), as they take such events as an
10882 * indication that the VM is alive, and they would force the VM config to
10883 * be reread, leading to an endless loop. */
10884 if (!fImplicitDiffs)
10885 return S_OK;
10886
10887 HRESULT rc = S_OK;
10888 MachineState_T oldState = mData->mMachineState;
10889
10890 /* will release the lock before the potentially lengthy operation,
10891 * so protect with the special state (unless already protected) */
10892 if ( oldState != MachineState_Snapshotting
10893 && oldState != MachineState_OnlineSnapshotting
10894 && oldState != MachineState_LiveSnapshotting
10895 && oldState != MachineState_RestoringSnapshot
10896 && oldState != MachineState_DeletingSnapshot
10897 && oldState != MachineState_DeletingSnapshotOnline
10898 && oldState != MachineState_DeletingSnapshotPaused
10899 )
10900 i_setMachineState(MachineState_SettingUp);
10901
10902 // use appropriate locked media map (online or offline)
10903 MediumLockListMap lockedMediaOffline;
10904 MediumLockListMap *lockedMediaMap;
10905 if (aOnline)
10906 lockedMediaMap = &mData->mSession.mLockedMedia;
10907 else
10908 lockedMediaMap = &lockedMediaOffline;
10909
10910 try
10911 {
10912 if (!aOnline)
10913 {
10914 /* lock all attached hard disks early to detect "in use"
10915 * situations before deleting actual diffs */
10916 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10917 it != mMediaData->mAttachments.end();
10918 ++it)
10919 {
10920 MediumAttachment* pAtt = *it;
10921 if (pAtt->i_getType() == DeviceType_HardDisk)
10922 {
10923 Medium* pMedium = pAtt->i_getMedium();
10924 Assert(pMedium);
10925
10926 MediumLockList *pMediumLockList(new MediumLockList());
10927 alock.release();
10928 rc = pMedium->i_createMediumLockList(true /* fFailIfInaccessible */,
10929 false /* fMediumLockWrite */,
10930 false /* fMediumLockWriteAll */,
10931 NULL,
10932 *pMediumLockList);
10933 alock.acquire();
10934
10935 if (FAILED(rc))
10936 {
10937 delete pMediumLockList;
10938 throw rc;
10939 }
10940
10941 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10942 if (FAILED(rc))
10943 throw rc;
10944 }
10945 }
10946
10947 if (FAILED(rc))
10948 throw rc;
10949 } // end of offline
10950
10951 /* Lock lists are now up to date and include implicitly created media */
10952
10953 /* Go through remembered attachments and delete all implicitly created
10954 * diffs and fix up the attachment information */
10955 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
10956 MediaData::AttachmentList implicitAtts;
10957 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10958 it != mMediaData->mAttachments.end();
10959 ++it)
10960 {
10961 ComObjPtr<MediumAttachment> pAtt = *it;
10962 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
10963 if (pMedium.isNull())
10964 continue;
10965
10966 // Implicit attachments go on the list for deletion and back references are removed.
10967 if (pAtt->i_isImplicit())
10968 {
10969 /* Deassociate and mark for deletion */
10970 LogFlowThisFunc(("Detaching '%s', pending deletion\n", pAtt->i_getLogName()));
10971 rc = pMedium->i_removeBackReference(mData->mUuid);
10972 if (FAILED(rc))
10973 throw rc;
10974 implicitAtts.push_back(pAtt);
10975 continue;
10976 }
10977
10978 /* Was this medium attached before? */
10979 if (!i_findAttachment(oldAtts, pMedium))
10980 {
10981 /* no: de-associate */
10982 LogFlowThisFunc(("Detaching '%s', no deletion\n", pAtt->i_getLogName()));
10983 rc = pMedium->i_removeBackReference(mData->mUuid);
10984 if (FAILED(rc))
10985 throw rc;
10986 continue;
10987 }
10988 LogFlowThisFunc(("Not detaching '%s'\n", pAtt->i_getLogName()));
10989 }
10990
10991 /* If there are implicit attachments to delete, throw away the lock
10992 * map contents (which will unlock all media) since the medium
10993 * attachments will be rolled back. Below we need to completely
10994 * recreate the lock map anyway since it is infinitely complex to
10995 * do this incrementally (would need reconstructing each attachment
10996 * change, which would be extremely hairy). */
10997 if (implicitAtts.size() != 0)
10998 {
10999 ErrorInfoKeeper eik;
11000
11001 HRESULT rc1 = lockedMediaMap->Clear();
11002 AssertComRC(rc1);
11003 }
11004
11005 /* rollback hard disk changes */
11006 mMediaData.rollback();
11007
11008 MultiResult mrc(S_OK);
11009
11010 // Delete unused implicit diffs.
11011 if (implicitAtts.size() != 0)
11012 {
11013 alock.release();
11014
11015 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin(); it != implicitAtts.end(); ++it)
11016 {
11017 // Remove medium associated with this attachment.
11018 ComObjPtr<MediumAttachment> pAtt = *it;
11019 Assert(pAtt);
11020 LogFlowThisFunc(("Deleting '%s'\n", pAtt->i_getLogName()));
11021 ComObjPtr<Medium> pMedium = pAtt->i_getMedium();
11022 Assert(pMedium);
11023
11024 rc = pMedium->i_deleteStorage(NULL /*aProgress*/, true /*aWait*/);
11025 // continue on delete failure, just collect error messages
11026 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, pAtt->i_getLogName(),
11027 pMedium->i_getLocationFull().c_str() ));
11028 mrc = rc;
11029 }
11030 // Clear the list of deleted implicit attachments now, while not
11031 // holding the lock, as it will ultimately trigger Medium::uninit()
11032 // calls which assume that the media tree lock isn't held.
11033 implicitAtts.clear();
11034
11035 alock.acquire();
11036
11037 /* if there is a VM recreate media lock map as mentioned above,
11038 * otherwise it is a waste of time and we leave things unlocked */
11039 if (aOnline)
11040 {
11041 const ComObjPtr<SessionMachine> pMachine = mData->mSession.mMachine;
11042 /* must never be NULL, but better safe than sorry */
11043 if (!pMachine.isNull())
11044 {
11045 alock.release();
11046 rc = mData->mSession.mMachine->i_lockMedia();
11047 alock.acquire();
11048 if (FAILED(rc))
11049 throw rc;
11050 }
11051 }
11052 }
11053 }
11054 catch (HRESULT aRC) {rc = aRC;}
11055
11056 if (mData->mMachineState == MachineState_SettingUp)
11057 i_setMachineState(oldState);
11058
11059 /* unlock all hard disks we locked when there is no VM */
11060 if (!aOnline)
11061 {
11062 ErrorInfoKeeper eik;
11063
11064 HRESULT rc1 = lockedMediaMap->Clear();
11065 AssertComRC(rc1);
11066 }
11067
11068 return rc;
11069}
11070
11071
11072/**
11073 * Looks through the given list of media attachments for one with the given parameters
11074 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11075 * can be searched as well if needed.
11076 *
11077 * @param list
11078 * @param aControllerName
11079 * @param aControllerPort
11080 * @param aDevice
11081 * @return
11082 */
11083MediumAttachment* Machine::i_findAttachment(const MediaData::AttachmentList &ll,
11084 const Utf8Str &aControllerName,
11085 LONG aControllerPort,
11086 LONG aDevice)
11087{
11088 for (MediaData::AttachmentList::const_iterator it = ll.begin(); it != ll.end(); ++it)
11089 {
11090 MediumAttachment *pAttach = *it;
11091 if (pAttach->i_matches(aControllerName, aControllerPort, aDevice))
11092 return pAttach;
11093 }
11094
11095 return NULL;
11096}
11097
11098/**
11099 * Looks through the given list of media attachments for one with the given parameters
11100 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11101 * can be searched as well if needed.
11102 *
11103 * @param list
11104 * @param aControllerName
11105 * @param aControllerPort
11106 * @param aDevice
11107 * @return
11108 */
11109MediumAttachment* Machine::i_findAttachment(const MediaData::AttachmentList &ll,
11110 ComObjPtr<Medium> pMedium)
11111{
11112 for (MediaData::AttachmentList::const_iterator it = ll.begin(); it != ll.end(); ++it)
11113 {
11114 MediumAttachment *pAttach = *it;
11115 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11116 if (pMediumThis == pMedium)
11117 return pAttach;
11118 }
11119
11120 return NULL;
11121}
11122
11123/**
11124 * Looks through the given list of media attachments for one with the given parameters
11125 * and returns it, or NULL if not found. The list is a parameter so that backup lists
11126 * can be searched as well if needed.
11127 *
11128 * @param list
11129 * @param aControllerName
11130 * @param aControllerPort
11131 * @param aDevice
11132 * @return
11133 */
11134MediumAttachment* Machine::i_findAttachment(const MediaData::AttachmentList &ll,
11135 Guid &id)
11136{
11137 for (MediaData::AttachmentList::const_iterator it = ll.begin(); it != ll.end(); ++it)
11138 {
11139 MediumAttachment *pAttach = *it;
11140 ComObjPtr<Medium> pMediumThis = pAttach->i_getMedium();
11141 if (pMediumThis->i_getId() == id)
11142 return pAttach;
11143 }
11144
11145 return NULL;
11146}
11147
11148/**
11149 * Main implementation for Machine::DetachDevice. This also gets called
11150 * from Machine::prepareUnregister() so it has been taken out for simplicity.
11151 *
11152 * @param pAttach Medium attachment to detach.
11153 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
11154 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a
11155 * SnapshotMachine, and this must be its snapshot.
11156 * @return
11157 */
11158HRESULT Machine::i_detachDevice(MediumAttachment *pAttach,
11159 AutoWriteLock &writeLock,
11160 Snapshot *pSnapshot)
11161{
11162 ComObjPtr<Medium> oldmedium = pAttach->i_getMedium();
11163 DeviceType_T mediumType = pAttach->i_getType();
11164
11165 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->i_getLocationFull().c_str() : "NULL"));
11166
11167 if (pAttach->i_isImplicit())
11168 {
11169 /* attempt to implicitly delete the implicitly created diff */
11170
11171 /// @todo move the implicit flag from MediumAttachment to Medium
11172 /// and forbid any hard disk operation when it is implicit. Or maybe
11173 /// a special media state for it to make it even more simple.
11174
11175 Assert(mMediaData.isBackedUp());
11176
11177 /* will release the lock before the potentially lengthy operation, so
11178 * protect with the special state */
11179 MachineState_T oldState = mData->mMachineState;
11180 i_setMachineState(MachineState_SettingUp);
11181
11182 writeLock.release();
11183
11184 HRESULT rc = oldmedium->i_deleteStorage(NULL /*aProgress*/,
11185 true /*aWait*/);
11186
11187 writeLock.acquire();
11188
11189 i_setMachineState(oldState);
11190
11191 if (FAILED(rc)) return rc;
11192 }
11193
11194 i_setModified(IsModified_Storage);
11195 mMediaData.backup();
11196 mMediaData->mAttachments.remove(pAttach);
11197
11198 if (!oldmedium.isNull())
11199 {
11200 // if this is from a snapshot, do not defer detachment to commitMedia()
11201 if (pSnapshot)
11202 oldmedium->i_removeBackReference(mData->mUuid, pSnapshot->i_getId());
11203 // else if non-hard disk media, do not defer detachment to commitMedia() either
11204 else if (mediumType != DeviceType_HardDisk)
11205 oldmedium->i_removeBackReference(mData->mUuid);
11206 }
11207
11208 return S_OK;
11209}
11210
11211/**
11212 * Goes thru all media of the given list and
11213 *
11214 * 1) calls i_detachDevice() on each of them for this machine and
11215 * 2) adds all Medium objects found in the process to the given list,
11216 * depending on cleanupMode.
11217 *
11218 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
11219 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
11220 * media to the list.
11221 *
11222 * This gets called from Machine::Unregister, both for the actual Machine and
11223 * the SnapshotMachine objects that might be found in the snapshots.
11224 *
11225 * Requires caller and locking. The machine lock must be passed in because it
11226 * will be passed on to i_detachDevice which needs it for temporary unlocking.
11227 *
11228 * @param writeLock Machine lock from top-level caller; this gets passed to i_detachDevice.
11229 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
11230 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if
11231 * Full, then all media get added;
11232 * otherwise no media get added.
11233 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
11234 * @return
11235 */
11236HRESULT Machine::i_detachAllMedia(AutoWriteLock &writeLock,
11237 Snapshot *pSnapshot,
11238 CleanupMode_T cleanupMode,
11239 MediaList &llMedia)
11240{
11241 Assert(isWriteLockOnCurrentThread());
11242
11243 HRESULT rc;
11244
11245 // make a temporary list because i_detachDevice invalidates iterators into
11246 // mMediaData->mAttachments
11247 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
11248
11249 for (MediaData::AttachmentList::iterator it = llAttachments2.begin(); it != llAttachments2.end(); ++it)
11250 {
11251 ComObjPtr<MediumAttachment> &pAttach = *it;
11252 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
11253
11254 if (!pMedium.isNull())
11255 {
11256 AutoCaller mac(pMedium);
11257 if (FAILED(mac.rc())) return mac.rc();
11258 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
11259 DeviceType_T devType = pMedium->i_getDeviceType();
11260 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
11261 && devType == DeviceType_HardDisk)
11262 || (cleanupMode == CleanupMode_Full)
11263 )
11264 {
11265 llMedia.push_back(pMedium);
11266 ComObjPtr<Medium> pParent = pMedium->i_getParent();
11267 /* Not allowed to keep this lock as below we need the parent
11268 * medium lock, and the lock order is parent to child. */
11269 lock.release();
11270 /*
11271 * Search for medias which are not attached to any machine, but
11272 * in the chain to an attached disk. Mediums are only consided
11273 * if they are:
11274 * - have only one child
11275 * - no references to any machines
11276 * - are of normal medium type
11277 */
11278 while (!pParent.isNull())
11279 {
11280 AutoCaller mac1(pParent);
11281 if (FAILED(mac1.rc())) return mac1.rc();
11282 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
11283 if (pParent->i_getChildren().size() == 1)
11284 {
11285 if ( pParent->i_getMachineBackRefCount() == 0
11286 && pParent->i_getType() == MediumType_Normal
11287 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
11288 llMedia.push_back(pParent);
11289 }
11290 else
11291 break;
11292 pParent = pParent->i_getParent();
11293 }
11294 }
11295 }
11296
11297 // real machine: then we need to use the proper method
11298 rc = i_detachDevice(pAttach, writeLock, pSnapshot);
11299
11300 if (FAILED(rc))
11301 return rc;
11302 }
11303
11304 return S_OK;
11305}
11306
11307/**
11308 * Perform deferred hard disk detachments.
11309 *
11310 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
11311 * backed up).
11312 *
11313 * If @a aOnline is @c true then this method will also unlock the old hard disks
11314 * for which the new implicit diffs were created and will lock these new diffs for
11315 * writing.
11316 *
11317 * @param aOnline Whether the VM was online prior to this operation.
11318 *
11319 * @note Locks this object for writing!
11320 */
11321void Machine::i_commitMedia(bool aOnline /*= false*/)
11322{
11323 AutoCaller autoCaller(this);
11324 AssertComRCReturnVoid(autoCaller.rc());
11325
11326 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11327
11328 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
11329
11330 HRESULT rc = S_OK;
11331
11332 /* no attach/detach operations -- nothing to do */
11333 if (!mMediaData.isBackedUp())
11334 return;
11335
11336 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
11337 bool fMediaNeedsLocking = false;
11338
11339 /* enumerate new attachments */
11340 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11341 it != mMediaData->mAttachments.end();
11342 ++it)
11343 {
11344 MediumAttachment *pAttach = *it;
11345
11346 pAttach->i_commit();
11347
11348 Medium* pMedium = pAttach->i_getMedium();
11349 bool fImplicit = pAttach->i_isImplicit();
11350
11351 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
11352 (pMedium) ? pMedium->i_getName().c_str() : "NULL",
11353 fImplicit));
11354
11355 /** @todo convert all this Machine-based voodoo to MediumAttachment
11356 * based commit logic. */
11357 if (fImplicit)
11358 {
11359 /* convert implicit attachment to normal */
11360 pAttach->i_setImplicit(false);
11361
11362 if ( aOnline
11363 && pMedium
11364 && pAttach->i_getType() == DeviceType_HardDisk
11365 )
11366 {
11367 /* update the appropriate lock list */
11368 MediumLockList *pMediumLockList;
11369 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11370 AssertComRC(rc);
11371 if (pMediumLockList)
11372 {
11373 /* unlock if there's a need to change the locking */
11374 if (!fMediaNeedsLocking)
11375 {
11376 rc = mData->mSession.mLockedMedia.Unlock();
11377 AssertComRC(rc);
11378 fMediaNeedsLocking = true;
11379 }
11380 rc = pMediumLockList->Update(pMedium->i_getParent(), false);
11381 AssertComRC(rc);
11382 rc = pMediumLockList->Append(pMedium, true);
11383 AssertComRC(rc);
11384 }
11385 }
11386
11387 continue;
11388 }
11389
11390 if (pMedium)
11391 {
11392 /* was this medium attached before? */
11393 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin(); oldIt != oldAtts.end(); ++oldIt)
11394 {
11395 MediumAttachment *pOldAttach = *oldIt;
11396 if (pOldAttach->i_getMedium() == pMedium)
11397 {
11398 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->i_getName().c_str()));
11399
11400 /* yes: remove from old to avoid de-association */
11401 oldAtts.erase(oldIt);
11402 break;
11403 }
11404 }
11405 }
11406 }
11407
11408 /* enumerate remaining old attachments and de-associate from the
11409 * current machine state */
11410 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin(); it != oldAtts.end(); ++it)
11411 {
11412 MediumAttachment *pAttach = *it;
11413 Medium* pMedium = pAttach->i_getMedium();
11414
11415 /* Detach only hard disks, since DVD/floppy media is detached
11416 * instantly in MountMedium. */
11417 if (pAttach->i_getType() == DeviceType_HardDisk && pMedium)
11418 {
11419 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->i_getName().c_str()));
11420
11421 /* now de-associate from the current machine state */
11422 rc = pMedium->i_removeBackReference(mData->mUuid);
11423 AssertComRC(rc);
11424
11425 if (aOnline)
11426 {
11427 /* unlock since medium is not used anymore */
11428 MediumLockList *pMediumLockList;
11429 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11430 if (RT_UNLIKELY(rc == VBOX_E_INVALID_OBJECT_STATE))
11431 {
11432 /* this happens for online snapshots, there the attachment
11433 * is changing, but only to a diff image created under
11434 * the old one, so there is no separate lock list */
11435 Assert(!pMediumLockList);
11436 }
11437 else
11438 {
11439 AssertComRC(rc);
11440 if (pMediumLockList)
11441 {
11442 rc = mData->mSession.mLockedMedia.Remove(pAttach);
11443 AssertComRC(rc);
11444 }
11445 }
11446 }
11447 }
11448 }
11449
11450 /* take media locks again so that the locking state is consistent */
11451 if (fMediaNeedsLocking)
11452 {
11453 Assert(aOnline);
11454 rc = mData->mSession.mLockedMedia.Lock();
11455 AssertComRC(rc);
11456 }
11457
11458 /* commit the hard disk changes */
11459 mMediaData.commit();
11460
11461 if (i_isSessionMachine())
11462 {
11463 /*
11464 * Update the parent machine to point to the new owner.
11465 * This is necessary because the stored parent will point to the
11466 * session machine otherwise and cause crashes or errors later
11467 * when the session machine gets invalid.
11468 */
11469 /** @todo Change the MediumAttachment class to behave like any other
11470 * class in this regard by creating peer MediumAttachment
11471 * objects for session machines and share the data with the peer
11472 * machine.
11473 */
11474 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11475 it != mMediaData->mAttachments.end();
11476 ++it)
11477 (*it)->i_updateParentMachine(mPeer);
11478
11479 /* attach new data to the primary machine and reshare it */
11480 mPeer->mMediaData.attach(mMediaData);
11481 }
11482
11483 return;
11484}
11485
11486/**
11487 * Perform deferred deletion of implicitly created diffs.
11488 *
11489 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
11490 * backed up).
11491 *
11492 * @note Locks this object for writing!
11493 */
11494void Machine::i_rollbackMedia()
11495{
11496 AutoCaller autoCaller(this);
11497 AssertComRCReturnVoid(autoCaller.rc());
11498
11499 // AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11500 LogFlowThisFunc(("Entering rollbackMedia\n"));
11501
11502 HRESULT rc = S_OK;
11503
11504 /* no attach/detach operations -- nothing to do */
11505 if (!mMediaData.isBackedUp())
11506 return;
11507
11508 /* enumerate new attachments */
11509 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11510 it != mMediaData->mAttachments.end();
11511 ++it)
11512 {
11513 MediumAttachment *pAttach = *it;
11514 /* Fix up the backrefs for DVD/floppy media. */
11515 if (pAttach->i_getType() != DeviceType_HardDisk)
11516 {
11517 Medium* pMedium = pAttach->i_getMedium();
11518 if (pMedium)
11519 {
11520 rc = pMedium->i_removeBackReference(mData->mUuid);
11521 AssertComRC(rc);
11522 }
11523 }
11524
11525 (*it)->i_rollback();
11526
11527 pAttach = *it;
11528 /* Fix up the backrefs for DVD/floppy media. */
11529 if (pAttach->i_getType() != DeviceType_HardDisk)
11530 {
11531 Medium* pMedium = pAttach->i_getMedium();
11532 if (pMedium)
11533 {
11534 rc = pMedium->i_addBackReference(mData->mUuid);
11535 AssertComRC(rc);
11536 }
11537 }
11538 }
11539
11540 /** @todo convert all this Machine-based voodoo to MediumAttachment
11541 * based rollback logic. */
11542 i_deleteImplicitDiffs(Global::IsOnline(mData->mMachineState));
11543
11544 return;
11545}
11546
11547/**
11548 * Returns true if the settings file is located in the directory named exactly
11549 * as the machine; this means, among other things, that the machine directory
11550 * should be auto-renamed.
11551 *
11552 * @param aSettingsDir if not NULL, the full machine settings file directory
11553 * name will be assigned there.
11554 *
11555 * @note Doesn't lock anything.
11556 * @note Not thread safe (must be called from this object's lock).
11557 */
11558bool Machine::i_isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
11559{
11560 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11561 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
11562 if (aSettingsDir)
11563 *aSettingsDir = strMachineDirName;
11564 strMachineDirName.stripPath(); // vmname
11565 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11566 strConfigFileOnly.stripPath() // vmname.vbox
11567 .stripSuffix(); // vmname
11568 /** @todo hack, make somehow use of ComposeMachineFilename */
11569 if (mUserData->s.fDirectoryIncludesUUID)
11570 strConfigFileOnly += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
11571
11572 AssertReturn(!strMachineDirName.isEmpty(), false);
11573 AssertReturn(!strConfigFileOnly.isEmpty(), false);
11574
11575 return strMachineDirName == strConfigFileOnly;
11576}
11577
11578/**
11579 * Discards all changes to machine settings.
11580 *
11581 * @param aNotify Whether to notify the direct session about changes or not.
11582 *
11583 * @note Locks objects for writing!
11584 */
11585void Machine::i_rollback(bool aNotify)
11586{
11587 AutoCaller autoCaller(this);
11588 AssertComRCReturn(autoCaller.rc(), (void)0);
11589
11590 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11591
11592 if (!mStorageControllers.isNull())
11593 {
11594 if (mStorageControllers.isBackedUp())
11595 {
11596 /* unitialize all new devices (absent in the backed up list). */
11597 StorageControllerList::const_iterator it = mStorageControllers->begin();
11598 StorageControllerList *backedList = mStorageControllers.backedUpData();
11599 while (it != mStorageControllers->end())
11600 {
11601 if ( std::find(backedList->begin(), backedList->end(), *it)
11602 == backedList->end()
11603 )
11604 {
11605 (*it)->uninit();
11606 }
11607 ++it;
11608 }
11609
11610 /* restore the list */
11611 mStorageControllers.rollback();
11612 }
11613
11614 /* rollback any changes to devices after restoring the list */
11615 if (mData->flModifications & IsModified_Storage)
11616 {
11617 StorageControllerList::const_iterator it = mStorageControllers->begin();
11618 while (it != mStorageControllers->end())
11619 {
11620 (*it)->i_rollback();
11621 ++it;
11622 }
11623 }
11624 }
11625
11626 if (!mUSBControllers.isNull())
11627 {
11628 if (mUSBControllers.isBackedUp())
11629 {
11630 /* unitialize all new devices (absent in the backed up list). */
11631 USBControllerList::const_iterator it = mUSBControllers->begin();
11632 USBControllerList *backedList = mUSBControllers.backedUpData();
11633 while (it != mUSBControllers->end())
11634 {
11635 if ( std::find(backedList->begin(), backedList->end(), *it)
11636 == backedList->end()
11637 )
11638 {
11639 (*it)->uninit();
11640 }
11641 ++it;
11642 }
11643
11644 /* restore the list */
11645 mUSBControllers.rollback();
11646 }
11647
11648 /* rollback any changes to devices after restoring the list */
11649 if (mData->flModifications & IsModified_USB)
11650 {
11651 USBControllerList::const_iterator it = mUSBControllers->begin();
11652 while (it != mUSBControllers->end())
11653 {
11654 (*it)->i_rollback();
11655 ++it;
11656 }
11657 }
11658 }
11659
11660 mUserData.rollback();
11661
11662 mHWData.rollback();
11663
11664 if (mData->flModifications & IsModified_Storage)
11665 i_rollbackMedia();
11666
11667 if (mBIOSSettings)
11668 mBIOSSettings->i_rollback();
11669
11670 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
11671 mVRDEServer->i_rollback();
11672
11673 if (mAudioAdapter)
11674 mAudioAdapter->i_rollback();
11675
11676 if (mUSBDeviceFilters && (mData->flModifications & IsModified_USB))
11677 mUSBDeviceFilters->i_rollback();
11678
11679 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
11680 mBandwidthControl->i_rollback();
11681
11682 if (!mHWData.isNull())
11683 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
11684 NetworkAdapterVector networkAdapters(mNetworkAdapters.size());
11685 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
11686 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
11687
11688 if (mData->flModifications & IsModified_NetworkAdapters)
11689 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
11690 if ( mNetworkAdapters[slot]
11691 && mNetworkAdapters[slot]->i_isModified())
11692 {
11693 mNetworkAdapters[slot]->i_rollback();
11694 networkAdapters[slot] = mNetworkAdapters[slot];
11695 }
11696
11697 if (mData->flModifications & IsModified_SerialPorts)
11698 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
11699 if ( mSerialPorts[slot]
11700 && mSerialPorts[slot]->i_isModified())
11701 {
11702 mSerialPorts[slot]->i_rollback();
11703 serialPorts[slot] = mSerialPorts[slot];
11704 }
11705
11706 if (mData->flModifications & IsModified_ParallelPorts)
11707 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
11708 if ( mParallelPorts[slot]
11709 && mParallelPorts[slot]->i_isModified())
11710 {
11711 mParallelPorts[slot]->i_rollback();
11712 parallelPorts[slot] = mParallelPorts[slot];
11713 }
11714
11715 if (aNotify)
11716 {
11717 /* inform the direct session about changes */
11718
11719 ComObjPtr<Machine> that = this;
11720 uint32_t flModifications = mData->flModifications;
11721 alock.release();
11722
11723 if (flModifications & IsModified_SharedFolders)
11724 that->i_onSharedFolderChange();
11725
11726 if (flModifications & IsModified_VRDEServer)
11727 that->i_onVRDEServerChange(/* aRestart */ TRUE);
11728 if (flModifications & IsModified_USB)
11729 that->i_onUSBControllerChange();
11730
11731 for (ULONG slot = 0; slot < networkAdapters.size(); ++slot)
11732 if (networkAdapters[slot])
11733 that->i_onNetworkAdapterChange(networkAdapters[slot], FALSE);
11734 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); ++slot)
11735 if (serialPorts[slot])
11736 that->i_onSerialPortChange(serialPorts[slot]);
11737 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); ++slot)
11738 if (parallelPorts[slot])
11739 that->i_onParallelPortChange(parallelPorts[slot]);
11740
11741 if (flModifications & IsModified_Storage)
11742 that->i_onStorageControllerChange();
11743
11744#if 0
11745 if (flModifications & IsModified_BandwidthControl)
11746 that->onBandwidthControlChange();
11747#endif
11748 }
11749}
11750
11751/**
11752 * Commits all the changes to machine settings.
11753 *
11754 * Note that this operation is supposed to never fail.
11755 *
11756 * @note Locks this object and children for writing.
11757 */
11758void Machine::i_commit()
11759{
11760 AutoCaller autoCaller(this);
11761 AssertComRCReturnVoid(autoCaller.rc());
11762
11763 AutoCaller peerCaller(mPeer);
11764 AssertComRCReturnVoid(peerCaller.rc());
11765
11766 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
11767
11768 /*
11769 * use safe commit to ensure Snapshot machines (that share mUserData)
11770 * will still refer to a valid memory location
11771 */
11772 mUserData.commitCopy();
11773
11774 mHWData.commit();
11775
11776 if (mMediaData.isBackedUp())
11777 i_commitMedia(Global::IsOnline(mData->mMachineState));
11778
11779 mBIOSSettings->i_commit();
11780 mVRDEServer->i_commit();
11781 mAudioAdapter->i_commit();
11782 mUSBDeviceFilters->i_commit();
11783 mBandwidthControl->i_commit();
11784
11785 /* Since mNetworkAdapters is a list which might have been changed (resized)
11786 * without using the Backupable<> template we need to handle the copying
11787 * of the list entries manually, including the creation of peers for the
11788 * new objects. */
11789 bool commitNetworkAdapters = false;
11790 size_t newSize = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
11791 if (mPeer)
11792 {
11793 /* commit everything, even the ones which will go away */
11794 for (size_t slot = 0; slot < mNetworkAdapters.size(); slot++)
11795 mNetworkAdapters[slot]->i_commit();
11796 /* copy over the new entries, creating a peer and uninit the original */
11797 mPeer->mNetworkAdapters.resize(RT_MAX(newSize, mPeer->mNetworkAdapters.size()));
11798 for (size_t slot = 0; slot < newSize; slot++)
11799 {
11800 /* look if this adapter has a peer device */
11801 ComObjPtr<NetworkAdapter> peer = mNetworkAdapters[slot]->i_getPeer();
11802 if (!peer)
11803 {
11804 /* no peer means the adapter is a newly created one;
11805 * create a peer owning data this data share it with */
11806 peer.createObject();
11807 peer->init(mPeer, mNetworkAdapters[slot], true /* aReshare */);
11808 }
11809 mPeer->mNetworkAdapters[slot] = peer;
11810 }
11811 /* uninit any no longer needed network adapters */
11812 for (size_t slot = newSize; slot < mNetworkAdapters.size(); ++slot)
11813 mNetworkAdapters[slot]->uninit();
11814 for (size_t slot = newSize; slot < mPeer->mNetworkAdapters.size(); ++slot)
11815 {
11816 if (mPeer->mNetworkAdapters[slot])
11817 mPeer->mNetworkAdapters[slot]->uninit();
11818 }
11819 /* Keep the original network adapter count until this point, so that
11820 * discarding a chipset type change will not lose settings. */
11821 mNetworkAdapters.resize(newSize);
11822 mPeer->mNetworkAdapters.resize(newSize);
11823 }
11824 else
11825 {
11826 /* we have no peer (our parent is the newly created machine);
11827 * just commit changes to the network adapters */
11828 commitNetworkAdapters = true;
11829 }
11830 if (commitNetworkAdapters)
11831 for (size_t slot = 0; slot < mNetworkAdapters.size(); ++slot)
11832 mNetworkAdapters[slot]->i_commit();
11833
11834 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
11835 mSerialPorts[slot]->i_commit();
11836 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
11837 mParallelPorts[slot]->i_commit();
11838
11839 bool commitStorageControllers = false;
11840
11841 if (mStorageControllers.isBackedUp())
11842 {
11843 mStorageControllers.commit();
11844
11845 if (mPeer)
11846 {
11847 /* Commit all changes to new controllers (this will reshare data with
11848 * peers for those who have peers) */
11849 StorageControllerList *newList = new StorageControllerList();
11850 StorageControllerList::const_iterator it = mStorageControllers->begin();
11851 while (it != mStorageControllers->end())
11852 {
11853 (*it)->i_commit();
11854
11855 /* look if this controller has a peer device */
11856 ComObjPtr<StorageController> peer = (*it)->i_getPeer();
11857 if (!peer)
11858 {
11859 /* no peer means the device is a newly created one;
11860 * create a peer owning data this device share it with */
11861 peer.createObject();
11862 peer->init(mPeer, *it, true /* aReshare */);
11863 }
11864 else
11865 {
11866 /* remove peer from the old list */
11867 mPeer->mStorageControllers->remove(peer);
11868 }
11869 /* and add it to the new list */
11870 newList->push_back(peer);
11871
11872 ++it;
11873 }
11874
11875 /* uninit old peer's controllers that are left */
11876 it = mPeer->mStorageControllers->begin();
11877 while (it != mPeer->mStorageControllers->end())
11878 {
11879 (*it)->uninit();
11880 ++it;
11881 }
11882
11883 /* attach new list of controllers to our peer */
11884 mPeer->mStorageControllers.attach(newList);
11885 }
11886 else
11887 {
11888 /* we have no peer (our parent is the newly created machine);
11889 * just commit changes to devices */
11890 commitStorageControllers = true;
11891 }
11892 }
11893 else
11894 {
11895 /* the list of controllers itself is not changed,
11896 * just commit changes to controllers themselves */
11897 commitStorageControllers = true;
11898 }
11899
11900 if (commitStorageControllers)
11901 {
11902 StorageControllerList::const_iterator it = mStorageControllers->begin();
11903 while (it != mStorageControllers->end())
11904 {
11905 (*it)->i_commit();
11906 ++it;
11907 }
11908 }
11909
11910 bool commitUSBControllers = false;
11911
11912 if (mUSBControllers.isBackedUp())
11913 {
11914 mUSBControllers.commit();
11915
11916 if (mPeer)
11917 {
11918 /* Commit all changes to new controllers (this will reshare data with
11919 * peers for those who have peers) */
11920 USBControllerList *newList = new USBControllerList();
11921 USBControllerList::const_iterator it = mUSBControllers->begin();
11922 while (it != mUSBControllers->end())
11923 {
11924 (*it)->i_commit();
11925
11926 /* look if this controller has a peer device */
11927 ComObjPtr<USBController> peer = (*it)->i_getPeer();
11928 if (!peer)
11929 {
11930 /* no peer means the device is a newly created one;
11931 * create a peer owning data this device share it with */
11932 peer.createObject();
11933 peer->init(mPeer, *it, true /* aReshare */);
11934 }
11935 else
11936 {
11937 /* remove peer from the old list */
11938 mPeer->mUSBControllers->remove(peer);
11939 }
11940 /* and add it to the new list */
11941 newList->push_back(peer);
11942
11943 ++it;
11944 }
11945
11946 /* uninit old peer's controllers that are left */
11947 it = mPeer->mUSBControllers->begin();
11948 while (it != mPeer->mUSBControllers->end())
11949 {
11950 (*it)->uninit();
11951 ++it;
11952 }
11953
11954 /* attach new list of controllers to our peer */
11955 mPeer->mUSBControllers.attach(newList);
11956 }
11957 else
11958 {
11959 /* we have no peer (our parent is the newly created machine);
11960 * just commit changes to devices */
11961 commitUSBControllers = true;
11962 }
11963 }
11964 else
11965 {
11966 /* the list of controllers itself is not changed,
11967 * just commit changes to controllers themselves */
11968 commitUSBControllers = true;
11969 }
11970
11971 if (commitUSBControllers)
11972 {
11973 USBControllerList::const_iterator it = mUSBControllers->begin();
11974 while (it != mUSBControllers->end())
11975 {
11976 (*it)->i_commit();
11977 ++it;
11978 }
11979 }
11980
11981 if (i_isSessionMachine())
11982 {
11983 /* attach new data to the primary machine and reshare it */
11984 mPeer->mUserData.attach(mUserData);
11985 mPeer->mHWData.attach(mHWData);
11986 /* mMediaData is reshared by fixupMedia */
11987 // mPeer->mMediaData.attach(mMediaData);
11988 Assert(mPeer->mMediaData.data() == mMediaData.data());
11989 }
11990}
11991
11992/**
11993 * Copies all the hardware data from the given machine.
11994 *
11995 * Currently, only called when the VM is being restored from a snapshot. In
11996 * particular, this implies that the VM is not running during this method's
11997 * call.
11998 *
11999 * @note This method must be called from under this object's lock.
12000 *
12001 * @note This method doesn't call #commit(), so all data remains backed up and
12002 * unsaved.
12003 */
12004void Machine::i_copyFrom(Machine *aThat)
12005{
12006 AssertReturnVoid(!i_isSnapshotMachine());
12007 AssertReturnVoid(aThat->i_isSnapshotMachine());
12008
12009 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
12010
12011 mHWData.assignCopy(aThat->mHWData);
12012
12013 // create copies of all shared folders (mHWData after attaching a copy
12014 // contains just references to original objects)
12015 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
12016 it != mHWData->mSharedFolders.end();
12017 ++it)
12018 {
12019 ComObjPtr<SharedFolder> folder;
12020 folder.createObject();
12021 HRESULT rc = folder->initCopy(i_getMachine(), *it);
12022 AssertComRC(rc);
12023 *it = folder;
12024 }
12025
12026 mBIOSSettings->i_copyFrom(aThat->mBIOSSettings);
12027 mVRDEServer->i_copyFrom(aThat->mVRDEServer);
12028 mAudioAdapter->i_copyFrom(aThat->mAudioAdapter);
12029 mUSBDeviceFilters->i_copyFrom(aThat->mUSBDeviceFilters);
12030 mBandwidthControl->i_copyFrom(aThat->mBandwidthControl);
12031
12032 /* create private copies of all controllers */
12033 mStorageControllers.backup();
12034 mStorageControllers->clear();
12035 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
12036 it != aThat->mStorageControllers->end();
12037 ++it)
12038 {
12039 ComObjPtr<StorageController> ctrl;
12040 ctrl.createObject();
12041 ctrl->initCopy(this, *it);
12042 mStorageControllers->push_back(ctrl);
12043 }
12044
12045 /* create private copies of all USB controllers */
12046 mUSBControllers.backup();
12047 mUSBControllers->clear();
12048 for (USBControllerList::iterator it = aThat->mUSBControllers->begin();
12049 it != aThat->mUSBControllers->end();
12050 ++it)
12051 {
12052 ComObjPtr<USBController> ctrl;
12053 ctrl.createObject();
12054 ctrl->initCopy(this, *it);
12055 mUSBControllers->push_back(ctrl);
12056 }
12057
12058 mNetworkAdapters.resize(aThat->mNetworkAdapters.size());
12059 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12060 mNetworkAdapters[slot]->i_copyFrom(aThat->mNetworkAdapters[slot]);
12061 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12062 mSerialPorts[slot]->i_copyFrom(aThat->mSerialPorts[slot]);
12063 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12064 mParallelPorts[slot]->i_copyFrom(aThat->mParallelPorts[slot]);
12065}
12066
12067/**
12068 * Returns whether the given storage controller is hotplug capable.
12069 *
12070 * @returns true if the controller supports hotplugging
12071 * false otherwise.
12072 * @param enmCtrlType The controller type to check for.
12073 */
12074bool Machine::i_isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
12075{
12076 ComPtr<ISystemProperties> systemProperties;
12077 HRESULT rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
12078 if (FAILED(rc))
12079 return false;
12080
12081 BOOL aHotplugCapable = FALSE;
12082 systemProperties->GetStorageControllerHotplugCapable(enmCtrlType, &aHotplugCapable);
12083
12084 return RT_BOOL(aHotplugCapable);
12085}
12086
12087#ifdef VBOX_WITH_RESOURCE_USAGE_API
12088
12089void Machine::i_getDiskList(MediaList &list)
12090{
12091 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
12092 it != mMediaData->mAttachments.end();
12093 ++it)
12094 {
12095 MediumAttachment* pAttach = *it;
12096 /* just in case */
12097 AssertStmt(pAttach, continue);
12098
12099 AutoCaller localAutoCallerA(pAttach);
12100 if (FAILED(localAutoCallerA.rc())) continue;
12101
12102 AutoReadLock local_alockA(pAttach COMMA_LOCKVAL_SRC_POS);
12103
12104 if (pAttach->i_getType() == DeviceType_HardDisk)
12105 list.push_back(pAttach->i_getMedium());
12106 }
12107}
12108
12109void Machine::i_registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
12110{
12111 AssertReturnVoid(isWriteLockOnCurrentThread());
12112 AssertPtrReturnVoid(aCollector);
12113
12114 pm::CollectorHAL *hal = aCollector->getHAL();
12115 /* Create sub metrics */
12116 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
12117 "Percentage of processor time spent in user mode by the VM process.");
12118 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
12119 "Percentage of processor time spent in kernel mode by the VM process.");
12120 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
12121 "Size of resident portion of VM process in memory.");
12122 pm::SubMetric *diskUsageUsed = new pm::SubMetric("Disk/Usage/Used",
12123 "Actual size of all VM disks combined.");
12124 pm::SubMetric *machineNetRx = new pm::SubMetric("Net/Rate/Rx",
12125 "Network receive rate.");
12126 pm::SubMetric *machineNetTx = new pm::SubMetric("Net/Rate/Tx",
12127 "Network transmit rate.");
12128 /* Create and register base metrics */
12129 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
12130 cpuLoadUser, cpuLoadKernel);
12131 aCollector->registerBaseMetric(cpuLoad);
12132 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
12133 ramUsageUsed);
12134 aCollector->registerBaseMetric(ramUsage);
12135 MediaList disks;
12136 i_getDiskList(disks);
12137 pm::BaseMetric *diskUsage = new pm::MachineDiskUsage(hal, aMachine, disks,
12138 diskUsageUsed);
12139 aCollector->registerBaseMetric(diskUsage);
12140
12141 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
12142 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12143 new pm::AggregateAvg()));
12144 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12145 new pm::AggregateMin()));
12146 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
12147 new pm::AggregateMax()));
12148 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
12149 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12150 new pm::AggregateAvg()));
12151 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12152 new pm::AggregateMin()));
12153 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
12154 new pm::AggregateMax()));
12155
12156 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
12157 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12158 new pm::AggregateAvg()));
12159 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12160 new pm::AggregateMin()));
12161 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
12162 new pm::AggregateMax()));
12163
12164 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed, 0));
12165 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12166 new pm::AggregateAvg()));
12167 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12168 new pm::AggregateMin()));
12169 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
12170 new pm::AggregateMax()));
12171
12172
12173 /* Guest metrics collector */
12174 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
12175 aCollector->registerGuest(mCollectorGuest);
12176 Log7(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n", this, __PRETTY_FUNCTION__, mCollectorGuest));
12177
12178 /* Create sub metrics */
12179 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
12180 "Percentage of processor time spent in user mode as seen by the guest.");
12181 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
12182 "Percentage of processor time spent in kernel mode as seen by the guest.");
12183 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
12184 "Percentage of processor time spent idling as seen by the guest.");
12185
12186 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
12187 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
12188 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
12189 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
12190 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
12191 pm::SubMetric *guestMemCache = new pm::SubMetric(
12192 "Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
12193
12194 pm::SubMetric *guestPagedTotal = new pm::SubMetric(
12195 "Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
12196
12197 /* Create and register base metrics */
12198 pm::BaseMetric *machineNetRate = new pm::MachineNetRate(mCollectorGuest, aMachine,
12199 machineNetRx, machineNetTx);
12200 aCollector->registerBaseMetric(machineNetRate);
12201
12202 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
12203 guestLoadUser, guestLoadKernel, guestLoadIdle);
12204 aCollector->registerBaseMetric(guestCpuLoad);
12205
12206 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
12207 guestMemTotal, guestMemFree,
12208 guestMemBalloon, guestMemShared,
12209 guestMemCache, guestPagedTotal);
12210 aCollector->registerBaseMetric(guestCpuMem);
12211
12212 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, 0));
12213 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateAvg()));
12214 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMin()));
12215 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMax()));
12216
12217 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, 0));
12218 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateAvg()));
12219 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMin()));
12220 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMax()));
12221
12222 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
12223 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
12224 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
12225 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
12226
12227 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
12228 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
12229 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
12230 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
12231
12232 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
12233 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
12234 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
12235 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
12236
12237 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
12238 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
12239 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
12240 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
12241
12242 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
12243 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
12244 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
12245 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
12246
12247 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
12248 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
12249 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
12250 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
12251
12252 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
12253 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
12254 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
12255 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
12256
12257 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
12258 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
12259 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
12260 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
12261
12262 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
12263 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
12264 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
12265 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
12266}
12267
12268void Machine::i_unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
12269{
12270 AssertReturnVoid(isWriteLockOnCurrentThread());
12271
12272 if (aCollector)
12273 {
12274 aCollector->unregisterMetricsFor(aMachine);
12275 aCollector->unregisterBaseMetricsFor(aMachine);
12276 }
12277}
12278
12279#endif /* VBOX_WITH_RESOURCE_USAGE_API */
12280
12281
12282////////////////////////////////////////////////////////////////////////////////
12283
12284DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
12285
12286HRESULT SessionMachine::FinalConstruct()
12287{
12288 LogFlowThisFunc(("\n"));
12289
12290 mClientToken = NULL;
12291
12292 return BaseFinalConstruct();
12293}
12294
12295void SessionMachine::FinalRelease()
12296{
12297 LogFlowThisFunc(("\n"));
12298
12299 Assert(!mClientToken);
12300 /* paranoia, should not hang around any more */
12301 if (mClientToken)
12302 {
12303 delete mClientToken;
12304 mClientToken = NULL;
12305 }
12306
12307 uninit(Uninit::Unexpected);
12308
12309 BaseFinalRelease();
12310}
12311
12312/**
12313 * @note Must be called only by Machine::LockMachine() from its own write lock.
12314 */
12315HRESULT SessionMachine::init(Machine *aMachine)
12316{
12317 LogFlowThisFuncEnter();
12318 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
12319
12320 AssertReturn(aMachine, E_INVALIDARG);
12321
12322 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
12323
12324 /* Enclose the state transition NotReady->InInit->Ready */
12325 AutoInitSpan autoInitSpan(this);
12326 AssertReturn(autoInitSpan.isOk(), E_FAIL);
12327
12328 HRESULT rc = S_OK;
12329
12330 /* create the machine client token */
12331 try
12332 {
12333 mClientToken = new ClientToken(aMachine, this);
12334 if (!mClientToken->isReady())
12335 {
12336 delete mClientToken;
12337 mClientToken = NULL;
12338 rc = E_FAIL;
12339 }
12340 }
12341 catch (std::bad_alloc &)
12342 {
12343 rc = E_OUTOFMEMORY;
12344 }
12345 if (FAILED(rc))
12346 return rc;
12347
12348 /* memorize the peer Machine */
12349 unconst(mPeer) = aMachine;
12350 /* share the parent pointer */
12351 unconst(mParent) = aMachine->mParent;
12352
12353 /* take the pointers to data to share */
12354 mData.share(aMachine->mData);
12355 mSSData.share(aMachine->mSSData);
12356
12357 mUserData.share(aMachine->mUserData);
12358 mHWData.share(aMachine->mHWData);
12359 mMediaData.share(aMachine->mMediaData);
12360
12361 mStorageControllers.allocate();
12362 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
12363 it != aMachine->mStorageControllers->end();
12364 ++it)
12365 {
12366 ComObjPtr<StorageController> ctl;
12367 ctl.createObject();
12368 ctl->init(this, *it);
12369 mStorageControllers->push_back(ctl);
12370 }
12371
12372 mUSBControllers.allocate();
12373 for (USBControllerList::const_iterator it = aMachine->mUSBControllers->begin();
12374 it != aMachine->mUSBControllers->end();
12375 ++it)
12376 {
12377 ComObjPtr<USBController> ctl;
12378 ctl.createObject();
12379 ctl->init(this, *it);
12380 mUSBControllers->push_back(ctl);
12381 }
12382
12383 unconst(mBIOSSettings).createObject();
12384 mBIOSSettings->init(this, aMachine->mBIOSSettings);
12385 /* create another VRDEServer object that will be mutable */
12386 unconst(mVRDEServer).createObject();
12387 mVRDEServer->init(this, aMachine->mVRDEServer);
12388 /* create another audio adapter object that will be mutable */
12389 unconst(mAudioAdapter).createObject();
12390 mAudioAdapter->init(this, aMachine->mAudioAdapter);
12391 /* create a list of serial ports that will be mutable */
12392 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
12393 {
12394 unconst(mSerialPorts[slot]).createObject();
12395 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
12396 }
12397 /* create a list of parallel ports that will be mutable */
12398 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); ++slot)
12399 {
12400 unconst(mParallelPorts[slot]).createObject();
12401 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
12402 }
12403
12404 /* create another USB device filters object that will be mutable */
12405 unconst(mUSBDeviceFilters).createObject();
12406 mUSBDeviceFilters->init(this, aMachine->mUSBDeviceFilters);
12407
12408 /* create a list of network adapters that will be mutable */
12409 mNetworkAdapters.resize(aMachine->mNetworkAdapters.size());
12410 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12411 {
12412 unconst(mNetworkAdapters[slot]).createObject();
12413 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
12414 }
12415
12416 /* create another bandwidth control object that will be mutable */
12417 unconst(mBandwidthControl).createObject();
12418 mBandwidthControl->init(this, aMachine->mBandwidthControl);
12419
12420 /* default is to delete saved state on Saved -> PoweredOff transition */
12421 mRemoveSavedState = true;
12422
12423 /* Confirm a successful initialization when it's the case */
12424 autoInitSpan.setSucceeded();
12425
12426 miNATNetworksStarted = 0;
12427
12428 LogFlowThisFuncLeave();
12429 return rc;
12430}
12431
12432/**
12433 * Uninitializes this session object. If the reason is other than
12434 * Uninit::Unexpected, then this method MUST be called from #checkForDeath()
12435 * or the client watcher code.
12436 *
12437 * @param aReason uninitialization reason
12438 *
12439 * @note Locks mParent + this object for writing.
12440 */
12441void SessionMachine::uninit(Uninit::Reason aReason)
12442{
12443 LogFlowThisFuncEnter();
12444 LogFlowThisFunc(("reason=%d\n", aReason));
12445
12446 /*
12447 * Strongly reference ourselves to prevent this object deletion after
12448 * mData->mSession.mMachine.setNull() below (which can release the last
12449 * reference and call the destructor). Important: this must be done before
12450 * accessing any members (and before AutoUninitSpan that does it as well).
12451 * This self reference will be released as the very last step on return.
12452 */
12453 ComObjPtr<SessionMachine> selfRef = this;
12454
12455 /* Enclose the state transition Ready->InUninit->NotReady */
12456 AutoUninitSpan autoUninitSpan(this);
12457 if (autoUninitSpan.uninitDone())
12458 {
12459 LogFlowThisFunc(("Already uninitialized\n"));
12460 LogFlowThisFuncLeave();
12461 return;
12462 }
12463
12464 if (autoUninitSpan.initFailed())
12465 {
12466 /* We've been called by init() because it's failed. It's not really
12467 * necessary (nor it's safe) to perform the regular uninit sequence
12468 * below, the following is enough.
12469 */
12470 LogFlowThisFunc(("Initialization failed.\n"));
12471 /* destroy the machine client token */
12472 if (mClientToken)
12473 {
12474 delete mClientToken;
12475 mClientToken = NULL;
12476 }
12477 uninitDataAndChildObjects();
12478 mData.free();
12479 unconst(mParent) = NULL;
12480 unconst(mPeer) = NULL;
12481 LogFlowThisFuncLeave();
12482 return;
12483 }
12484
12485 MachineState_T lastState;
12486 {
12487 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
12488 lastState = mData->mMachineState;
12489 }
12490 NOREF(lastState);
12491
12492#ifdef VBOX_WITH_USB
12493 // release all captured USB devices, but do this before requesting the locks below
12494 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
12495 {
12496 /* Console::captureUSBDevices() is called in the VM process only after
12497 * setting the machine state to Starting or Restoring.
12498 * Console::detachAllUSBDevices() will be called upon successful
12499 * termination. So, we need to release USB devices only if there was
12500 * an abnormal termination of a running VM.
12501 *
12502 * This is identical to SessionMachine::DetachAllUSBDevices except
12503 * for the aAbnormal argument. */
12504 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
12505 AssertComRC(rc);
12506 NOREF(rc);
12507
12508 USBProxyService *service = mParent->i_host()->i_usbProxyService();
12509 if (service)
12510 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
12511 }
12512#endif /* VBOX_WITH_USB */
12513
12514 // we need to lock this object in uninit() because the lock is shared
12515 // with mPeer (as well as data we modify below). mParent lock is needed
12516 // by several calls to it, and USB needs host lock.
12517 AutoMultiWriteLock3 multilock(mParent, mParent->i_host(), this COMMA_LOCKVAL_SRC_POS);
12518
12519#ifdef VBOX_WITH_RESOURCE_USAGE_API
12520 /*
12521 * It is safe to call Machine::i_unregisterMetrics() here because
12522 * PerformanceCollector::samplerCallback no longer accesses guest methods
12523 * holding the lock.
12524 */
12525 i_unregisterMetrics(mParent->i_performanceCollector(), mPeer);
12526 /* The guest must be unregistered after its metrics (@bugref{5949}). */
12527 Log7(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n", this, __PRETTY_FUNCTION__, mCollectorGuest));
12528 if (mCollectorGuest)
12529 {
12530 mParent->i_performanceCollector()->unregisterGuest(mCollectorGuest);
12531 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
12532 mCollectorGuest = NULL;
12533 }
12534#endif
12535
12536 if (aReason == Uninit::Abnormal)
12537 {
12538 Log1WarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n", Global::IsOnlineOrTransient(lastState)));
12539
12540 /* reset the state to Aborted */
12541 if (mData->mMachineState != MachineState_Aborted)
12542 i_setMachineState(MachineState_Aborted);
12543 }
12544
12545 // any machine settings modified?
12546 if (mData->flModifications)
12547 {
12548 Log1WarningThisFunc(("Discarding unsaved settings changes!\n"));
12549 i_rollback(false /* aNotify */);
12550 }
12551
12552 mData->mSession.mPID = NIL_RTPROCESS;
12553
12554 if (aReason == Uninit::Unexpected)
12555 {
12556 /* Uninitialization didn't come from #checkForDeath(), so tell the
12557 * client watcher thread to update the set of machines that have open
12558 * sessions. */
12559 mParent->i_updateClientWatcher();
12560 }
12561
12562 /* uninitialize all remote controls */
12563 if (mData->mSession.mRemoteControls.size())
12564 {
12565 LogFlowThisFunc(("Closing remote sessions (%d):\n",
12566 mData->mSession.mRemoteControls.size()));
12567
12568 Data::Session::RemoteControlList::iterator it =
12569 mData->mSession.mRemoteControls.begin();
12570 while (it != mData->mSession.mRemoteControls.end())
12571 {
12572 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
12573 HRESULT rc = (*it)->Uninitialize();
12574 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
12575 if (FAILED(rc))
12576 Log1WarningThisFunc(("Forgot to close the remote session?\n"));
12577 ++it;
12578 }
12579 mData->mSession.mRemoteControls.clear();
12580 }
12581
12582 /* Remove all references to the NAT network service. The service will stop
12583 * if all references (also from other VMs) are removed. */
12584 for (; miNATNetworksStarted > 0; miNATNetworksStarted--)
12585 {
12586 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12587 {
12588 NetworkAttachmentType_T type;
12589 HRESULT hrc;
12590
12591 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
12592 if ( SUCCEEDED(hrc)
12593 && type == NetworkAttachmentType_NATNetwork)
12594 {
12595 Bstr name;
12596 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
12597 if (SUCCEEDED(hrc))
12598 {
12599 multilock.release();
12600 LogRel(("VM '%s' stops using NAT network '%ls'\n",
12601 mUserData->s.strName.c_str(), name.raw()));
12602 mParent->i_natNetworkRefDec(name.raw());
12603 multilock.acquire();
12604 }
12605 }
12606 }
12607 }
12608
12609 /*
12610 * An expected uninitialization can come only from #checkForDeath().
12611 * Otherwise it means that something's gone really wrong (for example,
12612 * the Session implementation has released the VirtualBox reference
12613 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
12614 * etc). However, it's also possible, that the client releases the IPC
12615 * semaphore correctly (i.e. before it releases the VirtualBox reference),
12616 * but the VirtualBox release event comes first to the server process.
12617 * This case is practically possible, so we should not assert on an
12618 * unexpected uninit, just log a warning.
12619 */
12620
12621 if ((aReason == Uninit::Unexpected))
12622 Log1WarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
12623
12624 if (aReason != Uninit::Normal)
12625 {
12626 mData->mSession.mDirectControl.setNull();
12627 }
12628 else
12629 {
12630 /* this must be null here (see #OnSessionEnd()) */
12631 Assert(mData->mSession.mDirectControl.isNull());
12632 Assert(mData->mSession.mState == SessionState_Unlocking);
12633 Assert(!mData->mSession.mProgress.isNull());
12634 }
12635 if (mData->mSession.mProgress)
12636 {
12637 if (aReason == Uninit::Normal)
12638 mData->mSession.mProgress->i_notifyComplete(S_OK);
12639 else
12640 mData->mSession.mProgress->i_notifyComplete(E_FAIL,
12641 COM_IIDOF(ISession),
12642 getComponentName(),
12643 tr("The VM session was aborted"));
12644 mData->mSession.mProgress.setNull();
12645 }
12646
12647 /* remove the association between the peer machine and this session machine */
12648 Assert( (SessionMachine*)mData->mSession.mMachine == this
12649 || aReason == Uninit::Unexpected);
12650
12651 /* reset the rest of session data */
12652 mData->mSession.mLockType = LockType_Null;
12653 mData->mSession.mMachine.setNull();
12654 mData->mSession.mState = SessionState_Unlocked;
12655 mData->mSession.mName.setNull();
12656
12657 /* destroy the machine client token before leaving the exclusive lock */
12658 if (mClientToken)
12659 {
12660 delete mClientToken;
12661 mClientToken = NULL;
12662 }
12663
12664 /* fire an event */
12665 mParent->i_onSessionStateChange(mData->mUuid, SessionState_Unlocked);
12666
12667 uninitDataAndChildObjects();
12668
12669 /* free the essential data structure last */
12670 mData.free();
12671
12672 /* release the exclusive lock before setting the below two to NULL */
12673 multilock.release();
12674
12675 unconst(mParent) = NULL;
12676 unconst(mPeer) = NULL;
12677
12678 LogFlowThisFuncLeave();
12679}
12680
12681// util::Lockable interface
12682////////////////////////////////////////////////////////////////////////////////
12683
12684/**
12685 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
12686 * with the primary Machine instance (mPeer).
12687 */
12688RWLockHandle *SessionMachine::lockHandle() const
12689{
12690 AssertReturn(mPeer != NULL, NULL);
12691 return mPeer->lockHandle();
12692}
12693
12694// IInternalMachineControl methods
12695////////////////////////////////////////////////////////////////////////////////
12696
12697/**
12698 * Passes collected guest statistics to performance collector object
12699 */
12700HRESULT SessionMachine::reportVmStatistics(ULONG aValidStats, ULONG aCpuUser,
12701 ULONG aCpuKernel, ULONG aCpuIdle,
12702 ULONG aMemTotal, ULONG aMemFree,
12703 ULONG aMemBalloon, ULONG aMemShared,
12704 ULONG aMemCache, ULONG aPageTotal,
12705 ULONG aAllocVMM, ULONG aFreeVMM,
12706 ULONG aBalloonedVMM, ULONG aSharedVMM,
12707 ULONG aVmNetRx, ULONG aVmNetTx)
12708{
12709#ifdef VBOX_WITH_RESOURCE_USAGE_API
12710 if (mCollectorGuest)
12711 mCollectorGuest->updateStats(aValidStats, aCpuUser, aCpuKernel, aCpuIdle,
12712 aMemTotal, aMemFree, aMemBalloon, aMemShared,
12713 aMemCache, aPageTotal, aAllocVMM, aFreeVMM,
12714 aBalloonedVMM, aSharedVMM, aVmNetRx, aVmNetTx);
12715
12716 return S_OK;
12717#else
12718 NOREF(aValidStats);
12719 NOREF(aCpuUser);
12720 NOREF(aCpuKernel);
12721 NOREF(aCpuIdle);
12722 NOREF(aMemTotal);
12723 NOREF(aMemFree);
12724 NOREF(aMemBalloon);
12725 NOREF(aMemShared);
12726 NOREF(aMemCache);
12727 NOREF(aPageTotal);
12728 NOREF(aAllocVMM);
12729 NOREF(aFreeVMM);
12730 NOREF(aBalloonedVMM);
12731 NOREF(aSharedVMM);
12732 NOREF(aVmNetRx);
12733 NOREF(aVmNetTx);
12734 return E_NOTIMPL;
12735#endif
12736}
12737
12738////////////////////////////////////////////////////////////////////////////////
12739//
12740// SessionMachine task records
12741//
12742////////////////////////////////////////////////////////////////////////////////
12743
12744/**
12745 * Task record for saving the machine state.
12746 */
12747struct SessionMachine::SaveStateTask
12748 : public Machine::Task
12749{
12750 SaveStateTask(SessionMachine *m,
12751 Progress *p,
12752 const Utf8Str &t,
12753 Reason_T enmReason,
12754 const Utf8Str &strStateFilePath)
12755 : Task(m, p, t),
12756 m_enmReason(enmReason),
12757 m_strStateFilePath(strStateFilePath)
12758 {}
12759
12760 void handler()
12761 {
12762 ((SessionMachine *)(Machine *)m_pMachine)->i_saveStateHandler(*this);
12763 }
12764
12765 Reason_T m_enmReason;
12766 Utf8Str m_strStateFilePath;
12767};
12768
12769/**
12770 * Task thread implementation for SessionMachine::SaveState(), called from
12771 * SessionMachine::taskHandler().
12772 *
12773 * @note Locks this object for writing.
12774 *
12775 * @param task
12776 * @return
12777 */
12778void SessionMachine::i_saveStateHandler(SaveStateTask &task)
12779{
12780 LogFlowThisFuncEnter();
12781
12782 AutoCaller autoCaller(this);
12783 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
12784 if (FAILED(autoCaller.rc()))
12785 {
12786 /* we might have been uninitialized because the session was accidentally
12787 * closed by the client, so don't assert */
12788 HRESULT rc = setError(E_FAIL,
12789 tr("The session has been accidentally closed"));
12790 task.m_pProgress->i_notifyComplete(rc);
12791 LogFlowThisFuncLeave();
12792 return;
12793 }
12794
12795 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12796
12797 HRESULT rc = S_OK;
12798
12799 try
12800 {
12801 ComPtr<IInternalSessionControl> directControl;
12802 if (mData->mSession.mLockType == LockType_VM)
12803 directControl = mData->mSession.mDirectControl;
12804 if (directControl.isNull())
12805 throw setError(VBOX_E_INVALID_VM_STATE,
12806 tr("Trying to save state without a running VM"));
12807 alock.release();
12808 BOOL fSuspendedBySave;
12809 rc = directControl->SaveStateWithReason(task.m_enmReason, task.m_pProgress, Bstr(task.m_strStateFilePath).raw(), task.m_machineStateBackup != MachineState_Paused, &fSuspendedBySave);
12810 Assert(!fSuspendedBySave);
12811 alock.acquire();
12812
12813 AssertStmt( (SUCCEEDED(rc) && mData->mMachineState == MachineState_Saved)
12814 || (FAILED(rc) && mData->mMachineState == MachineState_Saving),
12815 throw E_FAIL);
12816
12817 if (SUCCEEDED(rc))
12818 {
12819 mSSData->strStateFilePath = task.m_strStateFilePath;
12820
12821 /* save all VM settings */
12822 rc = i_saveSettings(NULL);
12823 // no need to check whether VirtualBox.xml needs saving also since
12824 // we can't have a name change pending at this point
12825 }
12826 else
12827 {
12828 // On failure, set the state to the state we had at the beginning.
12829 i_setMachineState(task.m_machineStateBackup);
12830 i_updateMachineStateOnClient();
12831
12832 // Delete the saved state file (might have been already created).
12833 // No need to check whether this is shared with a snapshot here
12834 // because we certainly created a fresh saved state file here.
12835 RTFileDelete(task.m_strStateFilePath.c_str());
12836 }
12837 }
12838 catch (HRESULT aRC) { rc = aRC; }
12839
12840 task.m_pProgress->i_notifyComplete(rc);
12841
12842 LogFlowThisFuncLeave();
12843}
12844
12845/**
12846 * @note Locks this object for writing.
12847 */
12848HRESULT SessionMachine::saveState(ComPtr<IProgress> &aProgress)
12849{
12850 return i_saveStateWithReason(Reason_Unspecified, aProgress);
12851}
12852
12853HRESULT SessionMachine::i_saveStateWithReason(Reason_T aReason, ComPtr<IProgress> &aProgress)
12854{
12855 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12856
12857 HRESULT rc = i_checkStateDependency(MutableOrRunningStateDep);
12858 if (FAILED(rc)) return rc;
12859
12860 if ( mData->mMachineState != MachineState_Running
12861 && mData->mMachineState != MachineState_Paused
12862 )
12863 return setError(VBOX_E_INVALID_VM_STATE,
12864 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
12865 Global::stringifyMachineState(mData->mMachineState));
12866
12867 ComObjPtr<Progress> pProgress;
12868 pProgress.createObject();
12869 rc = pProgress->init(i_getVirtualBox(),
12870 static_cast<IMachine *>(this) /* aInitiator */,
12871 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
12872 FALSE /* aCancelable */);
12873 if (FAILED(rc))
12874 return rc;
12875
12876 Utf8Str strStateFilePath;
12877 i_composeSavedStateFilename(strStateFilePath);
12878
12879 /* create and start the task on a separate thread (note that it will not
12880 * start working until we release alock) */
12881 SaveStateTask *pTask = new SaveStateTask(this, pProgress, "SaveState", aReason, strStateFilePath);
12882 rc = pTask->createThread();
12883 if (FAILED(rc))
12884 return rc;
12885
12886 /* set the state to Saving (expected by Session::SaveStateWithReason()) */
12887 i_setMachineState(MachineState_Saving);
12888 i_updateMachineStateOnClient();
12889
12890 pProgress.queryInterfaceTo(aProgress.asOutParam());
12891
12892 return S_OK;
12893}
12894
12895/**
12896 * @note Locks this object for writing.
12897 */
12898HRESULT SessionMachine::adoptSavedState(const com::Utf8Str &aSavedStateFile)
12899{
12900 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12901
12902 HRESULT rc = i_checkStateDependency(MutableStateDep);
12903 if (FAILED(rc)) return rc;
12904
12905 if ( mData->mMachineState != MachineState_PoweredOff
12906 && mData->mMachineState != MachineState_Teleported
12907 && mData->mMachineState != MachineState_Aborted
12908 )
12909 return setError(VBOX_E_INVALID_VM_STATE,
12910 tr("Cannot adopt the saved machine state as the machine is not in Powered Off, Teleported or Aborted state (machine state: %s)"),
12911 Global::stringifyMachineState(mData->mMachineState));
12912
12913 com::Utf8Str stateFilePathFull;
12914 int vrc = i_calculateFullPath(aSavedStateFile, stateFilePathFull);
12915 if (RT_FAILURE(vrc))
12916 return setError(VBOX_E_FILE_ERROR,
12917 tr("Invalid saved state file path '%s' (%Rrc)"),
12918 aSavedStateFile.c_str(),
12919 vrc);
12920
12921 mSSData->strStateFilePath = stateFilePathFull;
12922
12923 /* The below i_setMachineState() will detect the state transition and will
12924 * update the settings file */
12925
12926 return i_setMachineState(MachineState_Saved);
12927}
12928
12929/**
12930 * @note Locks this object for writing.
12931 */
12932HRESULT SessionMachine::discardSavedState(BOOL aFRemoveFile)
12933{
12934 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12935
12936 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
12937 if (FAILED(rc)) return rc;
12938
12939 if (mData->mMachineState != MachineState_Saved)
12940 return setError(VBOX_E_INVALID_VM_STATE,
12941 tr("Cannot delete the machine state as the machine is not in the saved state (machine state: %s)"),
12942 Global::stringifyMachineState(mData->mMachineState));
12943
12944 mRemoveSavedState = RT_BOOL(aFRemoveFile);
12945
12946 /*
12947 * Saved -> PoweredOff transition will be detected in the SessionMachine
12948 * and properly handled.
12949 */
12950 rc = i_setMachineState(MachineState_PoweredOff);
12951 return rc;
12952}
12953
12954
12955/**
12956 * @note Locks the same as #i_setMachineState() does.
12957 */
12958HRESULT SessionMachine::updateState(MachineState_T aState)
12959{
12960 return i_setMachineState(aState);
12961}
12962
12963/**
12964 * @note Locks this object for writing.
12965 */
12966HRESULT SessionMachine::beginPowerUp(const ComPtr<IProgress> &aProgress)
12967{
12968 IProgress* pProgress(aProgress);
12969
12970 LogFlowThisFunc(("aProgress=%p\n", pProgress));
12971
12972 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12973
12974 if (mData->mSession.mState != SessionState_Locked)
12975 return VBOX_E_INVALID_OBJECT_STATE;
12976
12977 if (!mData->mSession.mProgress.isNull())
12978 mData->mSession.mProgress->setOtherProgressObject(pProgress);
12979
12980 /* If we didn't reference the NAT network service yet, add a reference to
12981 * force a start */
12982 if (miNATNetworksStarted < 1)
12983 {
12984 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
12985 {
12986 NetworkAttachmentType_T type;
12987 HRESULT hrc;
12988 hrc = mNetworkAdapters[slot]->COMGETTER(AttachmentType)(&type);
12989 if ( SUCCEEDED(hrc)
12990 && type == NetworkAttachmentType_NATNetwork)
12991 {
12992 Bstr name;
12993 hrc = mNetworkAdapters[slot]->COMGETTER(NATNetwork)(name.asOutParam());
12994 if (SUCCEEDED(hrc))
12995 {
12996 LogRel(("VM '%s' starts using NAT network '%ls'\n",
12997 mUserData->s.strName.c_str(), name.raw()));
12998 mPeer->lockHandle()->unlockWrite();
12999 mParent->i_natNetworkRefInc(name.raw());
13000#ifdef RT_LOCK_STRICT
13001 mPeer->lockHandle()->lockWrite(RT_SRC_POS);
13002#else
13003 mPeer->lockHandle()->lockWrite();
13004#endif
13005 }
13006 }
13007 }
13008 miNATNetworksStarted++;
13009 }
13010
13011 LogFlowThisFunc(("returns S_OK.\n"));
13012 return S_OK;
13013}
13014
13015/**
13016 * @note Locks this object for writing.
13017 */
13018HRESULT SessionMachine::endPowerUp(LONG aResult)
13019{
13020 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13021
13022 if (mData->mSession.mState != SessionState_Locked)
13023 return VBOX_E_INVALID_OBJECT_STATE;
13024
13025 /* Finalize the LaunchVMProcess progress object. */
13026 if (mData->mSession.mProgress)
13027 {
13028 mData->mSession.mProgress->notifyComplete((HRESULT)aResult);
13029 mData->mSession.mProgress.setNull();
13030 }
13031
13032 if (SUCCEEDED((HRESULT)aResult))
13033 {
13034#ifdef VBOX_WITH_RESOURCE_USAGE_API
13035 /* The VM has been powered up successfully, so it makes sense
13036 * now to offer the performance metrics for a running machine
13037 * object. Doing it earlier wouldn't be safe. */
13038 i_registerMetrics(mParent->i_performanceCollector(), mPeer,
13039 mData->mSession.mPID);
13040#endif /* VBOX_WITH_RESOURCE_USAGE_API */
13041 }
13042
13043 return S_OK;
13044}
13045
13046/**
13047 * @note Locks this object for writing.
13048 */
13049HRESULT SessionMachine::beginPoweringDown(ComPtr<IProgress> &aProgress)
13050{
13051 LogFlowThisFuncEnter();
13052
13053 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13054
13055 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
13056 E_FAIL);
13057
13058 /* create a progress object to track operation completion */
13059 ComObjPtr<Progress> pProgress;
13060 pProgress.createObject();
13061 pProgress->init(i_getVirtualBox(),
13062 static_cast<IMachine *>(this) /* aInitiator */,
13063 Bstr(tr("Stopping the virtual machine")).raw(),
13064 FALSE /* aCancelable */);
13065
13066 /* fill in the console task data */
13067 mConsoleTaskData.mLastState = mData->mMachineState;
13068 mConsoleTaskData.mProgress = pProgress;
13069
13070 /* set the state to Stopping (this is expected by Console::PowerDown()) */
13071 i_setMachineState(MachineState_Stopping);
13072
13073 pProgress.queryInterfaceTo(aProgress.asOutParam());
13074
13075 return S_OK;
13076}
13077
13078/**
13079 * @note Locks this object for writing.
13080 */
13081HRESULT SessionMachine::endPoweringDown(LONG aResult,
13082 const com::Utf8Str &aErrMsg)
13083{
13084 LogFlowThisFuncEnter();
13085
13086 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13087
13088 AssertReturn( ( (SUCCEEDED(aResult) && mData->mMachineState == MachineState_PoweredOff)
13089 || (FAILED(aResult) && mData->mMachineState == MachineState_Stopping))
13090 && mConsoleTaskData.mLastState != MachineState_Null,
13091 E_FAIL);
13092
13093 /*
13094 * On failure, set the state to the state we had when BeginPoweringDown()
13095 * was called (this is expected by Console::PowerDown() and the associated
13096 * task). On success the VM process already changed the state to
13097 * MachineState_PoweredOff, so no need to do anything.
13098 */
13099 if (FAILED(aResult))
13100 i_setMachineState(mConsoleTaskData.mLastState);
13101
13102 /* notify the progress object about operation completion */
13103 Assert(mConsoleTaskData.mProgress);
13104 if (SUCCEEDED(aResult))
13105 mConsoleTaskData.mProgress->i_notifyComplete(S_OK);
13106 else
13107 {
13108 if (aErrMsg.length())
13109 mConsoleTaskData.mProgress->i_notifyComplete(aResult,
13110 COM_IIDOF(ISession),
13111 getComponentName(),
13112 aErrMsg.c_str());
13113 else
13114 mConsoleTaskData.mProgress->i_notifyComplete(aResult);
13115 }
13116
13117 /* clear out the temporary saved state data */
13118 mConsoleTaskData.mLastState = MachineState_Null;
13119 mConsoleTaskData.mProgress.setNull();
13120
13121 LogFlowThisFuncLeave();
13122 return S_OK;
13123}
13124
13125
13126/**
13127 * Goes through the USB filters of the given machine to see if the given
13128 * device matches any filter or not.
13129 *
13130 * @note Locks the same as USBController::hasMatchingFilter() does.
13131 */
13132HRESULT SessionMachine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
13133 BOOL *aMatched,
13134 ULONG *aMaskedInterfaces)
13135{
13136 LogFlowThisFunc(("\n"));
13137
13138#ifdef VBOX_WITH_USB
13139 *aMatched = mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedInterfaces);
13140#else
13141 NOREF(aDevice);
13142 NOREF(aMaskedInterfaces);
13143 *aMatched = FALSE;
13144#endif
13145
13146 return S_OK;
13147}
13148
13149/**
13150 * @note Locks the same as Host::captureUSBDevice() does.
13151 */
13152HRESULT SessionMachine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
13153{
13154 LogFlowThisFunc(("\n"));
13155
13156#ifdef VBOX_WITH_USB
13157 /* if captureDeviceForVM() fails, it must have set extended error info */
13158 clearError();
13159 MultiResult rc = mParent->i_host()->i_checkUSBProxyService();
13160 if (FAILED(rc)) return rc;
13161
13162 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13163 AssertReturn(service, E_FAIL);
13164 return service->captureDeviceForVM(this, aId.ref(), aCaptureFilename);
13165#else
13166 NOREF(aId);
13167 return E_NOTIMPL;
13168#endif
13169}
13170
13171/**
13172 * @note Locks the same as Host::detachUSBDevice() does.
13173 */
13174HRESULT SessionMachine::detachUSBDevice(const com::Guid &aId,
13175 BOOL aDone)
13176{
13177 LogFlowThisFunc(("\n"));
13178
13179#ifdef VBOX_WITH_USB
13180 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13181 AssertReturn(service, E_FAIL);
13182 return service->detachDeviceFromVM(this, aId.ref(), !!aDone);
13183#else
13184 NOREF(aId);
13185 NOREF(aDone);
13186 return E_NOTIMPL;
13187#endif
13188}
13189
13190/**
13191 * Inserts all machine filters to the USB proxy service and then calls
13192 * Host::autoCaptureUSBDevices().
13193 *
13194 * Called by Console from the VM process upon VM startup.
13195 *
13196 * @note Locks what called methods lock.
13197 */
13198HRESULT SessionMachine::autoCaptureUSBDevices()
13199{
13200 LogFlowThisFunc(("\n"));
13201
13202#ifdef VBOX_WITH_USB
13203 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(true /* aInsertFilters */);
13204 AssertComRC(rc);
13205 NOREF(rc);
13206
13207 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13208 AssertReturn(service, E_FAIL);
13209 return service->autoCaptureDevicesForVM(this);
13210#else
13211 return S_OK;
13212#endif
13213}
13214
13215/**
13216 * Removes all machine filters from the USB proxy service and then calls
13217 * Host::detachAllUSBDevices().
13218 *
13219 * Called by Console from the VM process upon normal VM termination or by
13220 * SessionMachine::uninit() upon abnormal VM termination (from under the
13221 * Machine/SessionMachine lock).
13222 *
13223 * @note Locks what called methods lock.
13224 */
13225HRESULT SessionMachine::detachAllUSBDevices(BOOL aDone)
13226{
13227 LogFlowThisFunc(("\n"));
13228
13229#ifdef VBOX_WITH_USB
13230 HRESULT rc = mUSBDeviceFilters->i_notifyProxy(false /* aInsertFilters */);
13231 AssertComRC(rc);
13232 NOREF(rc);
13233
13234 USBProxyService *service = mParent->i_host()->i_usbProxyService();
13235 AssertReturn(service, E_FAIL);
13236 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
13237#else
13238 NOREF(aDone);
13239 return S_OK;
13240#endif
13241}
13242
13243/**
13244 * @note Locks this object for writing.
13245 */
13246HRESULT SessionMachine::onSessionEnd(const ComPtr<ISession> &aSession,
13247 ComPtr<IProgress> &aProgress)
13248{
13249 LogFlowThisFuncEnter();
13250
13251 LogFlowThisFunc(("callerstate=%d\n", getObjectState().getState()));
13252 /*
13253 * We don't assert below because it might happen that a non-direct session
13254 * informs us it is closed right after we've been uninitialized -- it's ok.
13255 */
13256
13257 /* get IInternalSessionControl interface */
13258 ComPtr<IInternalSessionControl> control(aSession);
13259
13260 ComAssertRet(!control.isNull(), E_INVALIDARG);
13261
13262 /* Creating a Progress object requires the VirtualBox lock, and
13263 * thus locking it here is required by the lock order rules. */
13264 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
13265
13266 if (control == mData->mSession.mDirectControl)
13267 {
13268 /* The direct session is being normally closed by the client process
13269 * ----------------------------------------------------------------- */
13270
13271 /* go to the closing state (essential for all open*Session() calls and
13272 * for #checkForDeath()) */
13273 Assert(mData->mSession.mState == SessionState_Locked);
13274 mData->mSession.mState = SessionState_Unlocking;
13275
13276 /* set direct control to NULL to release the remote instance */
13277 mData->mSession.mDirectControl.setNull();
13278 LogFlowThisFunc(("Direct control is set to NULL\n"));
13279
13280 if (mData->mSession.mProgress)
13281 {
13282 /* finalize the progress, someone might wait if a frontend
13283 * closes the session before powering on the VM. */
13284 mData->mSession.mProgress->notifyComplete(E_FAIL,
13285 COM_IIDOF(ISession),
13286 getComponentName(),
13287 tr("The VM session was closed before any attempt to power it on"));
13288 mData->mSession.mProgress.setNull();
13289 }
13290
13291 /* Create the progress object the client will use to wait until
13292 * #checkForDeath() is called to uninitialize this session object after
13293 * it releases the IPC semaphore.
13294 * Note! Because we're "reusing" mProgress here, this must be a proxy
13295 * object just like for LaunchVMProcess. */
13296 Assert(mData->mSession.mProgress.isNull());
13297 ComObjPtr<ProgressProxy> progress;
13298 progress.createObject();
13299 ComPtr<IUnknown> pPeer(mPeer);
13300 progress->init(mParent, pPeer,
13301 Bstr(tr("Closing session")).raw(),
13302 FALSE /* aCancelable */);
13303 progress.queryInterfaceTo(aProgress.asOutParam());
13304 mData->mSession.mProgress = progress;
13305 }
13306 else
13307 {
13308 /* the remote session is being normally closed */
13309 Data::Session::RemoteControlList::iterator it =
13310 mData->mSession.mRemoteControls.begin();
13311 while (it != mData->mSession.mRemoteControls.end())
13312 {
13313 if (control == *it)
13314 break;
13315 ++it;
13316 }
13317 BOOL found = it != mData->mSession.mRemoteControls.end();
13318 ComAssertMsgRet(found, ("The session is not found in the session list!"),
13319 E_INVALIDARG);
13320 // This MUST be erase(it), not remove(*it) as the latter triggers a
13321 // very nasty use after free due to the place where the value "lives".
13322 mData->mSession.mRemoteControls.erase(it);
13323 }
13324
13325 /* signal the client watcher thread, because the client is going away */
13326 mParent->i_updateClientWatcher();
13327
13328 LogFlowThisFuncLeave();
13329 return S_OK;
13330}
13331
13332HRESULT SessionMachine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
13333 std::vector<com::Utf8Str> &aValues,
13334 std::vector<LONG64> &aTimestamps,
13335 std::vector<com::Utf8Str> &aFlags)
13336{
13337 LogFlowThisFunc(("\n"));
13338
13339#ifdef VBOX_WITH_GUEST_PROPS
13340 using namespace guestProp;
13341
13342 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13343
13344 size_t cEntries = mHWData->mGuestProperties.size();
13345 aNames.resize(cEntries);
13346 aValues.resize(cEntries);
13347 aTimestamps.resize(cEntries);
13348 aFlags.resize(cEntries);
13349
13350 size_t i = 0;
13351 for (HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.begin();
13352 it != mHWData->mGuestProperties.end();
13353 ++it, ++i)
13354 {
13355 char szFlags[MAX_FLAGS_LEN + 1];
13356 aNames[i] = it->first;
13357 aValues[i] = it->second.strValue;
13358 aTimestamps[i] = it->second.mTimestamp;
13359
13360 /* If it is NULL, keep it NULL. */
13361 if (it->second.mFlags)
13362 {
13363 writeFlags(it->second.mFlags, szFlags);
13364 aFlags[i] = szFlags;
13365 }
13366 else
13367 aFlags[i] = "";
13368 }
13369 return S_OK;
13370#else
13371 ReturnComNotImplemented();
13372#endif
13373}
13374
13375HRESULT SessionMachine::pushGuestProperty(const com::Utf8Str &aName,
13376 const com::Utf8Str &aValue,
13377 LONG64 aTimestamp,
13378 const com::Utf8Str &aFlags)
13379{
13380 LogFlowThisFunc(("\n"));
13381
13382#ifdef VBOX_WITH_GUEST_PROPS
13383 using namespace guestProp;
13384
13385 try
13386 {
13387 /*
13388 * Convert input up front.
13389 */
13390 uint32_t fFlags = NILFLAG;
13391 if (aFlags.length())
13392 {
13393 int vrc = validateFlags(aFlags.c_str(), &fFlags);
13394 AssertRCReturn(vrc, E_INVALIDARG);
13395 }
13396
13397 /*
13398 * Now grab the object lock, validate the state and do the update.
13399 */
13400
13401 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13402
13403 if (!Global::IsOnline(mData->mMachineState))
13404 {
13405 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
13406 VBOX_E_INVALID_VM_STATE);
13407 }
13408
13409 i_setModified(IsModified_MachineData);
13410 mHWData.backup();
13411
13412 bool fDelete = !aValue.length();
13413 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(aName);
13414 if (it != mHWData->mGuestProperties.end())
13415 {
13416 if (!fDelete)
13417 {
13418 it->second.strValue = aValue;
13419 it->second.mTimestamp = aTimestamp;
13420 it->second.mFlags = fFlags;
13421 }
13422 else
13423 mHWData->mGuestProperties.erase(it);
13424
13425 mData->mGuestPropertiesModified = TRUE;
13426 }
13427 else if (!fDelete)
13428 {
13429 HWData::GuestProperty prop;
13430 prop.strValue = aValue;
13431 prop.mTimestamp = aTimestamp;
13432 prop.mFlags = fFlags;
13433
13434 mHWData->mGuestProperties[aName] = prop;
13435 mData->mGuestPropertiesModified = TRUE;
13436 }
13437
13438 alock.release();
13439
13440 mParent->i_onGuestPropertyChange(mData->mUuid,
13441 Bstr(aName).raw(),
13442 Bstr(aValue).raw(),
13443 Bstr(aFlags).raw());
13444 }
13445 catch (...)
13446 {
13447 return VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
13448 }
13449 return S_OK;
13450#else
13451 ReturnComNotImplemented();
13452#endif
13453}
13454
13455
13456HRESULT SessionMachine::lockMedia()
13457{
13458 AutoMultiWriteLock2 alock(this->lockHandle(),
13459 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13460
13461 AssertReturn( mData->mMachineState == MachineState_Starting
13462 || mData->mMachineState == MachineState_Restoring
13463 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
13464
13465 clearError();
13466 alock.release();
13467 return i_lockMedia();
13468}
13469
13470HRESULT SessionMachine::unlockMedia()
13471{
13472 HRESULT hrc = i_unlockMedia();
13473 return hrc;
13474}
13475
13476HRESULT SessionMachine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
13477 ComPtr<IMediumAttachment> &aNewAttachment)
13478{
13479 // request the host lock first, since might be calling Host methods for getting host drives;
13480 // next, protect the media tree all the while we're in here, as well as our member variables
13481 AutoMultiWriteLock3 multiLock(mParent->i_host()->lockHandle(),
13482 this->lockHandle(),
13483 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13484
13485 IMediumAttachment *iAttach = aAttachment;
13486 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(iAttach);
13487
13488 Bstr ctrlName;
13489 LONG lPort;
13490 LONG lDevice;
13491 bool fTempEject;
13492 {
13493 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13494
13495 /* Need to query the details first, as the IMediumAttachment reference
13496 * might be to the original settings, which we are going to change. */
13497 ctrlName = pAttach->i_getControllerName();
13498 lPort = pAttach->i_getPort();
13499 lDevice = pAttach->i_getDevice();
13500 fTempEject = pAttach->i_getTempEject();
13501 }
13502
13503 if (!fTempEject)
13504 {
13505 /* Remember previously mounted medium. The medium before taking the
13506 * backup is not necessarily the same thing. */
13507 ComObjPtr<Medium> oldmedium;
13508 oldmedium = pAttach->i_getMedium();
13509
13510 i_setModified(IsModified_Storage);
13511 mMediaData.backup();
13512
13513 // The backup operation makes the pAttach reference point to the
13514 // old settings. Re-get the correct reference.
13515 pAttach = i_findAttachment(mMediaData->mAttachments,
13516 ctrlName.raw(),
13517 lPort,
13518 lDevice);
13519
13520 {
13521 AutoCaller autoAttachCaller(this);
13522 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
13523
13524 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13525 if (!oldmedium.isNull())
13526 oldmedium->i_removeBackReference(mData->mUuid);
13527
13528 pAttach->i_updateMedium(NULL);
13529 pAttach->i_updateEjected();
13530 }
13531
13532 i_setModified(IsModified_Storage);
13533 }
13534 else
13535 {
13536 {
13537 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13538 pAttach->i_updateEjected();
13539 }
13540 }
13541
13542 pAttach.queryInterfaceTo(aNewAttachment.asOutParam());
13543
13544 return S_OK;
13545}
13546
13547// public methods only for internal purposes
13548/////////////////////////////////////////////////////////////////////////////
13549
13550#ifndef VBOX_WITH_GENERIC_SESSION_WATCHER
13551/**
13552 * Called from the client watcher thread to check for expected or unexpected
13553 * death of the client process that has a direct session to this machine.
13554 *
13555 * On Win32 and on OS/2, this method is called only when we've got the
13556 * mutex (i.e. the client has either died or terminated normally) so it always
13557 * returns @c true (the client is terminated, the session machine is
13558 * uninitialized).
13559 *
13560 * On other platforms, the method returns @c true if the client process has
13561 * terminated normally or abnormally and the session machine was uninitialized,
13562 * and @c false if the client process is still alive.
13563 *
13564 * @note Locks this object for writing.
13565 */
13566bool SessionMachine::i_checkForDeath()
13567{
13568 Uninit::Reason reason;
13569 bool terminated = false;
13570
13571 /* Enclose autoCaller with a block because calling uninit() from under it
13572 * will deadlock. */
13573 {
13574 AutoCaller autoCaller(this);
13575 if (!autoCaller.isOk())
13576 {
13577 /* return true if not ready, to cause the client watcher to exclude
13578 * the corresponding session from watching */
13579 LogFlowThisFunc(("Already uninitialized!\n"));
13580 return true;
13581 }
13582
13583 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13584
13585 /* Determine the reason of death: if the session state is Closing here,
13586 * everything is fine. Otherwise it means that the client did not call
13587 * OnSessionEnd() before it released the IPC semaphore. This may happen
13588 * either because the client process has abnormally terminated, or
13589 * because it simply forgot to call ISession::Close() before exiting. We
13590 * threat the latter also as an abnormal termination (see
13591 * Session::uninit() for details). */
13592 reason = mData->mSession.mState == SessionState_Unlocking ?
13593 Uninit::Normal :
13594 Uninit::Abnormal;
13595
13596 if (mClientToken)
13597 terminated = mClientToken->release();
13598 } /* AutoCaller block */
13599
13600 if (terminated)
13601 uninit(reason);
13602
13603 return terminated;
13604}
13605
13606void SessionMachine::i_getTokenId(Utf8Str &strTokenId)
13607{
13608 LogFlowThisFunc(("\n"));
13609
13610 strTokenId.setNull();
13611
13612 AutoCaller autoCaller(this);
13613 AssertComRCReturnVoid(autoCaller.rc());
13614
13615 Assert(mClientToken);
13616 if (mClientToken)
13617 mClientToken->getId(strTokenId);
13618}
13619#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
13620IToken *SessionMachine::i_getToken()
13621{
13622 LogFlowThisFunc(("\n"));
13623
13624 AutoCaller autoCaller(this);
13625 AssertComRCReturn(autoCaller.rc(), NULL);
13626
13627 Assert(mClientToken);
13628 if (mClientToken)
13629 return mClientToken->getToken();
13630 else
13631 return NULL;
13632}
13633#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
13634
13635Machine::ClientToken *SessionMachine::i_getClientToken()
13636{
13637 LogFlowThisFunc(("\n"));
13638
13639 AutoCaller autoCaller(this);
13640 AssertComRCReturn(autoCaller.rc(), NULL);
13641
13642 return mClientToken;
13643}
13644
13645
13646/**
13647 * @note Locks this object for reading.
13648 */
13649HRESULT SessionMachine::i_onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
13650{
13651 LogFlowThisFunc(("\n"));
13652
13653 AutoCaller autoCaller(this);
13654 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13655
13656 ComPtr<IInternalSessionControl> directControl;
13657 {
13658 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13659 if (mData->mSession.mLockType == LockType_VM)
13660 directControl = mData->mSession.mDirectControl;
13661 }
13662
13663 /* ignore notifications sent after #OnSessionEnd() is called */
13664 if (!directControl)
13665 return S_OK;
13666
13667 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
13668}
13669
13670/**
13671 * @note Locks this object for reading.
13672 */
13673HRESULT SessionMachine::i_onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
13674 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort,
13675 IN_BSTR aGuestIp, LONG aGuestPort)
13676{
13677 LogFlowThisFunc(("\n"));
13678
13679 AutoCaller autoCaller(this);
13680 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13681
13682 ComPtr<IInternalSessionControl> directControl;
13683 {
13684 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13685 if (mData->mSession.mLockType == LockType_VM)
13686 directControl = mData->mSession.mDirectControl;
13687 }
13688
13689 /* ignore notifications sent after #OnSessionEnd() is called */
13690 if (!directControl)
13691 return S_OK;
13692 /*
13693 * instead acting like callback we ask IVirtualBox deliver corresponding event
13694 */
13695
13696 mParent->i_onNatRedirectChange(i_getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp,
13697 (uint16_t)aHostPort, aGuestIp, (uint16_t)aGuestPort);
13698 return S_OK;
13699}
13700
13701/**
13702 * @note Locks this object for reading.
13703 */
13704HRESULT SessionMachine::i_onSerialPortChange(ISerialPort *serialPort)
13705{
13706 LogFlowThisFunc(("\n"));
13707
13708 AutoCaller autoCaller(this);
13709 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13710
13711 ComPtr<IInternalSessionControl> directControl;
13712 {
13713 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13714 if (mData->mSession.mLockType == LockType_VM)
13715 directControl = mData->mSession.mDirectControl;
13716 }
13717
13718 /* ignore notifications sent after #OnSessionEnd() is called */
13719 if (!directControl)
13720 return S_OK;
13721
13722 return directControl->OnSerialPortChange(serialPort);
13723}
13724
13725/**
13726 * @note Locks this object for reading.
13727 */
13728HRESULT SessionMachine::i_onParallelPortChange(IParallelPort *parallelPort)
13729{
13730 LogFlowThisFunc(("\n"));
13731
13732 AutoCaller autoCaller(this);
13733 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13734
13735 ComPtr<IInternalSessionControl> directControl;
13736 {
13737 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13738 if (mData->mSession.mLockType == LockType_VM)
13739 directControl = mData->mSession.mDirectControl;
13740 }
13741
13742 /* ignore notifications sent after #OnSessionEnd() is called */
13743 if (!directControl)
13744 return S_OK;
13745
13746 return directControl->OnParallelPortChange(parallelPort);
13747}
13748
13749/**
13750 * @note Locks this object for reading.
13751 */
13752HRESULT SessionMachine::i_onStorageControllerChange()
13753{
13754 LogFlowThisFunc(("\n"));
13755
13756 AutoCaller autoCaller(this);
13757 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13758
13759 ComPtr<IInternalSessionControl> directControl;
13760 {
13761 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13762 if (mData->mSession.mLockType == LockType_VM)
13763 directControl = mData->mSession.mDirectControl;
13764 }
13765
13766 /* ignore notifications sent after #OnSessionEnd() is called */
13767 if (!directControl)
13768 return S_OK;
13769
13770 return directControl->OnStorageControllerChange();
13771}
13772
13773/**
13774 * @note Locks this object for reading.
13775 */
13776HRESULT SessionMachine::i_onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
13777{
13778 LogFlowThisFunc(("\n"));
13779
13780 AutoCaller autoCaller(this);
13781 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13782
13783 ComPtr<IInternalSessionControl> directControl;
13784 {
13785 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13786 if (mData->mSession.mLockType == LockType_VM)
13787 directControl = mData->mSession.mDirectControl;
13788 }
13789
13790 /* ignore notifications sent after #OnSessionEnd() is called */
13791 if (!directControl)
13792 return S_OK;
13793
13794 return directControl->OnMediumChange(aAttachment, aForce);
13795}
13796
13797/**
13798 * @note Locks this object for reading.
13799 */
13800HRESULT SessionMachine::i_onCPUChange(ULONG aCPU, BOOL aRemove)
13801{
13802 LogFlowThisFunc(("\n"));
13803
13804 AutoCaller autoCaller(this);
13805 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13806
13807 ComPtr<IInternalSessionControl> directControl;
13808 {
13809 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13810 if (mData->mSession.mLockType == LockType_VM)
13811 directControl = mData->mSession.mDirectControl;
13812 }
13813
13814 /* ignore notifications sent after #OnSessionEnd() is called */
13815 if (!directControl)
13816 return S_OK;
13817
13818 return directControl->OnCPUChange(aCPU, aRemove);
13819}
13820
13821HRESULT SessionMachine::i_onCPUExecutionCapChange(ULONG aExecutionCap)
13822{
13823 LogFlowThisFunc(("\n"));
13824
13825 AutoCaller autoCaller(this);
13826 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13827
13828 ComPtr<IInternalSessionControl> directControl;
13829 {
13830 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13831 if (mData->mSession.mLockType == LockType_VM)
13832 directControl = mData->mSession.mDirectControl;
13833 }
13834
13835 /* ignore notifications sent after #OnSessionEnd() is called */
13836 if (!directControl)
13837 return S_OK;
13838
13839 return directControl->OnCPUExecutionCapChange(aExecutionCap);
13840}
13841
13842/**
13843 * @note Locks this object for reading.
13844 */
13845HRESULT SessionMachine::i_onVRDEServerChange(BOOL aRestart)
13846{
13847 LogFlowThisFunc(("\n"));
13848
13849 AutoCaller autoCaller(this);
13850 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13851
13852 ComPtr<IInternalSessionControl> directControl;
13853 {
13854 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13855 if (mData->mSession.mLockType == LockType_VM)
13856 directControl = mData->mSession.mDirectControl;
13857 }
13858
13859 /* ignore notifications sent after #OnSessionEnd() is called */
13860 if (!directControl)
13861 return S_OK;
13862
13863 return directControl->OnVRDEServerChange(aRestart);
13864}
13865
13866/**
13867 * @note Locks this object for reading.
13868 */
13869HRESULT SessionMachine::i_onVideoCaptureChange()
13870{
13871 LogFlowThisFunc(("\n"));
13872
13873 AutoCaller autoCaller(this);
13874 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13875
13876 ComPtr<IInternalSessionControl> directControl;
13877 {
13878 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13879 if (mData->mSession.mLockType == LockType_VM)
13880 directControl = mData->mSession.mDirectControl;
13881 }
13882
13883 /* ignore notifications sent after #OnSessionEnd() is called */
13884 if (!directControl)
13885 return S_OK;
13886
13887 return directControl->OnVideoCaptureChange();
13888}
13889
13890/**
13891 * @note Locks this object for reading.
13892 */
13893HRESULT SessionMachine::i_onUSBControllerChange()
13894{
13895 LogFlowThisFunc(("\n"));
13896
13897 AutoCaller autoCaller(this);
13898 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13899
13900 ComPtr<IInternalSessionControl> directControl;
13901 {
13902 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13903 if (mData->mSession.mLockType == LockType_VM)
13904 directControl = mData->mSession.mDirectControl;
13905 }
13906
13907 /* ignore notifications sent after #OnSessionEnd() is called */
13908 if (!directControl)
13909 return S_OK;
13910
13911 return directControl->OnUSBControllerChange();
13912}
13913
13914/**
13915 * @note Locks this object for reading.
13916 */
13917HRESULT SessionMachine::i_onSharedFolderChange()
13918{
13919 LogFlowThisFunc(("\n"));
13920
13921 AutoCaller autoCaller(this);
13922 AssertComRCReturnRC(autoCaller.rc());
13923
13924 ComPtr<IInternalSessionControl> directControl;
13925 {
13926 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13927 if (mData->mSession.mLockType == LockType_VM)
13928 directControl = mData->mSession.mDirectControl;
13929 }
13930
13931 /* ignore notifications sent after #OnSessionEnd() is called */
13932 if (!directControl)
13933 return S_OK;
13934
13935 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
13936}
13937
13938/**
13939 * @note Locks this object for reading.
13940 */
13941HRESULT SessionMachine::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
13942{
13943 LogFlowThisFunc(("\n"));
13944
13945 AutoCaller autoCaller(this);
13946 AssertComRCReturnRC(autoCaller.rc());
13947
13948 ComPtr<IInternalSessionControl> directControl;
13949 {
13950 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13951 if (mData->mSession.mLockType == LockType_VM)
13952 directControl = mData->mSession.mDirectControl;
13953 }
13954
13955 /* ignore notifications sent after #OnSessionEnd() is called */
13956 if (!directControl)
13957 return S_OK;
13958
13959 return directControl->OnClipboardModeChange(aClipboardMode);
13960}
13961
13962/**
13963 * @note Locks this object for reading.
13964 */
13965HRESULT SessionMachine::i_onDnDModeChange(DnDMode_T aDnDMode)
13966{
13967 LogFlowThisFunc(("\n"));
13968
13969 AutoCaller autoCaller(this);
13970 AssertComRCReturnRC(autoCaller.rc());
13971
13972 ComPtr<IInternalSessionControl> directControl;
13973 {
13974 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13975 if (mData->mSession.mLockType == LockType_VM)
13976 directControl = mData->mSession.mDirectControl;
13977 }
13978
13979 /* ignore notifications sent after #OnSessionEnd() is called */
13980 if (!directControl)
13981 return S_OK;
13982
13983 return directControl->OnDnDModeChange(aDnDMode);
13984}
13985
13986/**
13987 * @note Locks this object for reading.
13988 */
13989HRESULT SessionMachine::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
13990{
13991 LogFlowThisFunc(("\n"));
13992
13993 AutoCaller autoCaller(this);
13994 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13995
13996 ComPtr<IInternalSessionControl> directControl;
13997 {
13998 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13999 if (mData->mSession.mLockType == LockType_VM)
14000 directControl = mData->mSession.mDirectControl;
14001 }
14002
14003 /* ignore notifications sent after #OnSessionEnd() is called */
14004 if (!directControl)
14005 return S_OK;
14006
14007 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
14008}
14009
14010/**
14011 * @note Locks this object for reading.
14012 */
14013HRESULT SessionMachine::i_onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove, BOOL aSilent)
14014{
14015 LogFlowThisFunc(("\n"));
14016
14017 AutoCaller autoCaller(this);
14018 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14019
14020 ComPtr<IInternalSessionControl> directControl;
14021 {
14022 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14023 if (mData->mSession.mLockType == LockType_VM)
14024 directControl = mData->mSession.mDirectControl;
14025 }
14026
14027 /* ignore notifications sent after #OnSessionEnd() is called */
14028 if (!directControl)
14029 return S_OK;
14030
14031 return directControl->OnStorageDeviceChange(aAttachment, aRemove, aSilent);
14032}
14033
14034/**
14035 * Returns @c true if this machine's USB controller reports it has a matching
14036 * filter for the given USB device and @c false otherwise.
14037 *
14038 * @note locks this object for reading.
14039 */
14040bool SessionMachine::i_hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
14041{
14042 AutoCaller autoCaller(this);
14043 /* silently return if not ready -- this method may be called after the
14044 * direct machine session has been called */
14045 if (!autoCaller.isOk())
14046 return false;
14047
14048#ifdef VBOX_WITH_USB
14049 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14050
14051 switch (mData->mMachineState)
14052 {
14053 case MachineState_Starting:
14054 case MachineState_Restoring:
14055 case MachineState_TeleportingIn:
14056 case MachineState_Paused:
14057 case MachineState_Running:
14058 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
14059 * elsewhere... */
14060 alock.release();
14061 return mUSBDeviceFilters->i_hasMatchingFilter(aDevice, aMaskedIfs);
14062 default: break;
14063 }
14064#else
14065 NOREF(aDevice);
14066 NOREF(aMaskedIfs);
14067#endif
14068 return false;
14069}
14070
14071/**
14072 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14073 */
14074HRESULT SessionMachine::i_onUSBDeviceAttach(IUSBDevice *aDevice,
14075 IVirtualBoxErrorInfo *aError,
14076 ULONG aMaskedIfs,
14077 const com::Utf8Str &aCaptureFilename)
14078{
14079 LogFlowThisFunc(("\n"));
14080
14081 AutoCaller autoCaller(this);
14082
14083 /* This notification may happen after the machine object has been
14084 * uninitialized (the session was closed), so don't assert. */
14085 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14086
14087 ComPtr<IInternalSessionControl> directControl;
14088 {
14089 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14090 if (mData->mSession.mLockType == LockType_VM)
14091 directControl = mData->mSession.mDirectControl;
14092 }
14093
14094 /* fail on notifications sent after #OnSessionEnd() is called, it is
14095 * expected by the caller */
14096 if (!directControl)
14097 return E_FAIL;
14098
14099 /* No locks should be held at this point. */
14100 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14101 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14102
14103 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs, Bstr(aCaptureFilename).raw());
14104}
14105
14106/**
14107 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
14108 */
14109HRESULT SessionMachine::i_onUSBDeviceDetach(IN_BSTR aId,
14110 IVirtualBoxErrorInfo *aError)
14111{
14112 LogFlowThisFunc(("\n"));
14113
14114 AutoCaller autoCaller(this);
14115
14116 /* This notification may happen after the machine object has been
14117 * uninitialized (the session was closed), so don't assert. */
14118 if (FAILED(autoCaller.rc())) return autoCaller.rc();
14119
14120 ComPtr<IInternalSessionControl> directControl;
14121 {
14122 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14123 if (mData->mSession.mLockType == LockType_VM)
14124 directControl = mData->mSession.mDirectControl;
14125 }
14126
14127 /* fail on notifications sent after #OnSessionEnd() is called, it is
14128 * expected by the caller */
14129 if (!directControl)
14130 return E_FAIL;
14131
14132 /* No locks should be held at this point. */
14133 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
14134 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
14135
14136 return directControl->OnUSBDeviceDetach(aId, aError);
14137}
14138
14139// protected methods
14140/////////////////////////////////////////////////////////////////////////////
14141
14142/**
14143 * Deletes the given file if it is no longer in use by either the current machine state
14144 * (if the machine is "saved") or any of the machine's snapshots.
14145 *
14146 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
14147 * but is different for each SnapshotMachine. When calling this, the order of calling this
14148 * function on the one hand and changing that variable OR the snapshots tree on the other hand
14149 * is therefore critical. I know, it's all rather messy.
14150 *
14151 * @param strStateFile
14152 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in
14153 * the test for whether the saved state file is in use.
14154 */
14155void SessionMachine::i_releaseSavedStateFile(const Utf8Str &strStateFile,
14156 Snapshot *pSnapshotToIgnore)
14157{
14158 // it is safe to delete this saved state file if it is not currently in use by the machine ...
14159 if ( (strStateFile.isNotEmpty())
14160 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
14161 )
14162 // ... and it must also not be shared with other snapshots
14163 if ( !mData->mFirstSnapshot
14164 || !mData->mFirstSnapshot->i_sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
14165 // this checks the SnapshotMachine's state file paths
14166 )
14167 RTFileDelete(strStateFile.c_str());
14168}
14169
14170/**
14171 * Locks the attached media.
14172 *
14173 * All attached hard disks are locked for writing and DVD/floppy are locked for
14174 * reading. Parents of attached hard disks (if any) are locked for reading.
14175 *
14176 * This method also performs accessibility check of all media it locks: if some
14177 * media is inaccessible, the method will return a failure and a bunch of
14178 * extended error info objects per each inaccessible medium.
14179 *
14180 * Note that this method is atomic: if it returns a success, all media are
14181 * locked as described above; on failure no media is locked at all (all
14182 * succeeded individual locks will be undone).
14183 *
14184 * The caller is responsible for doing the necessary state sanity checks.
14185 *
14186 * The locks made by this method must be undone by calling #unlockMedia() when
14187 * no more needed.
14188 */
14189HRESULT SessionMachine::i_lockMedia()
14190{
14191 AutoCaller autoCaller(this);
14192 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14193
14194 AutoMultiWriteLock2 alock(this->lockHandle(),
14195 &mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
14196
14197 /* bail out if trying to lock things with already set up locking */
14198 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
14199
14200 MultiResult mrc(S_OK);
14201
14202 /* Collect locking information for all medium objects attached to the VM. */
14203 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
14204 it != mMediaData->mAttachments.end();
14205 ++it)
14206 {
14207 MediumAttachment* pAtt = *it;
14208 DeviceType_T devType = pAtt->i_getType();
14209 Medium *pMedium = pAtt->i_getMedium();
14210
14211 MediumLockList *pMediumLockList(new MediumLockList());
14212 // There can be attachments without a medium (floppy/dvd), and thus
14213 // it's impossible to create a medium lock list. It still makes sense
14214 // to have the empty medium lock list in the map in case a medium is
14215 // attached later.
14216 if (pMedium != NULL)
14217 {
14218 MediumType_T mediumType = pMedium->i_getType();
14219 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
14220 || mediumType == MediumType_Shareable;
14221 bool fIsVitalImage = (devType == DeviceType_HardDisk);
14222
14223 alock.release();
14224 mrc = pMedium->i_createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
14225 !fIsReadOnlyLock /* fMediumLockWrite */,
14226 false /* fMediumLockWriteAll */,
14227 NULL,
14228 *pMediumLockList);
14229 alock.acquire();
14230 if (FAILED(mrc))
14231 {
14232 delete pMediumLockList;
14233 mData->mSession.mLockedMedia.Clear();
14234 break;
14235 }
14236 }
14237
14238 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
14239 if (FAILED(rc))
14240 {
14241 mData->mSession.mLockedMedia.Clear();
14242 mrc = setError(rc,
14243 tr("Collecting locking information for all attached media failed"));
14244 break;
14245 }
14246 }
14247
14248 if (SUCCEEDED(mrc))
14249 {
14250 /* Now lock all media. If this fails, nothing is locked. */
14251 alock.release();
14252 HRESULT rc = mData->mSession.mLockedMedia.Lock();
14253 alock.acquire();
14254 if (FAILED(rc))
14255 {
14256 mrc = setError(rc,
14257 tr("Locking of attached media failed. A possible reason is that one of the media is attached to a running VM"));
14258 }
14259 }
14260
14261 return mrc;
14262}
14263
14264/**
14265 * Undoes the locks made by by #lockMedia().
14266 */
14267HRESULT SessionMachine::i_unlockMedia()
14268{
14269 AutoCaller autoCaller(this);
14270 AssertComRCReturn(autoCaller.rc(),autoCaller.rc());
14271
14272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14273
14274 /* we may be holding important error info on the current thread;
14275 * preserve it */
14276 ErrorInfoKeeper eik;
14277
14278 HRESULT rc = mData->mSession.mLockedMedia.Clear();
14279 AssertComRC(rc);
14280 return rc;
14281}
14282
14283/**
14284 * Helper to change the machine state (reimplementation).
14285 *
14286 * @note Locks this object for writing.
14287 * @note This method must not call i_saveSettings or SaveSettings, otherwise
14288 * it can cause crashes in random places due to unexpectedly committing
14289 * the current settings. The caller is responsible for that. The call
14290 * to saveStateSettings is fine, because this method does not commit.
14291 */
14292HRESULT SessionMachine::i_setMachineState(MachineState_T aMachineState)
14293{
14294 LogFlowThisFuncEnter();
14295 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
14296
14297 AutoCaller autoCaller(this);
14298 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14299
14300 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14301
14302 MachineState_T oldMachineState = mData->mMachineState;
14303
14304 AssertMsgReturn(oldMachineState != aMachineState,
14305 ("oldMachineState=%s, aMachineState=%s\n",
14306 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
14307 E_FAIL);
14308
14309 HRESULT rc = S_OK;
14310
14311 int stsFlags = 0;
14312 bool deleteSavedState = false;
14313
14314 /* detect some state transitions */
14315
14316 if ( ( oldMachineState == MachineState_Saved
14317 && aMachineState == MachineState_Restoring)
14318 || ( ( oldMachineState == MachineState_PoweredOff
14319 || oldMachineState == MachineState_Teleported
14320 || oldMachineState == MachineState_Aborted
14321 )
14322 && ( aMachineState == MachineState_TeleportingIn
14323 || aMachineState == MachineState_Starting
14324 )
14325 )
14326 )
14327 {
14328 /* The EMT thread is about to start */
14329
14330 /* Nothing to do here for now... */
14331
14332 /// @todo NEWMEDIA don't let mDVDDrive and other children
14333 /// change anything when in the Starting/Restoring state
14334 }
14335 else if ( ( oldMachineState == MachineState_Running
14336 || oldMachineState == MachineState_Paused
14337 || oldMachineState == MachineState_Teleporting
14338 || oldMachineState == MachineState_OnlineSnapshotting
14339 || oldMachineState == MachineState_LiveSnapshotting
14340 || oldMachineState == MachineState_Stuck
14341 || oldMachineState == MachineState_Starting
14342 || oldMachineState == MachineState_Stopping
14343 || oldMachineState == MachineState_Saving
14344 || oldMachineState == MachineState_Restoring
14345 || oldMachineState == MachineState_TeleportingPausedVM
14346 || oldMachineState == MachineState_TeleportingIn
14347 )
14348 && ( aMachineState == MachineState_PoweredOff
14349 || aMachineState == MachineState_Saved
14350 || aMachineState == MachineState_Teleported
14351 || aMachineState == MachineState_Aborted
14352 )
14353 )
14354 {
14355 /* The EMT thread has just stopped, unlock attached media. Note that as
14356 * opposed to locking that is done from Console, we do unlocking here
14357 * because the VM process may have aborted before having a chance to
14358 * properly unlock all media it locked. */
14359
14360 unlockMedia();
14361 }
14362
14363 if (oldMachineState == MachineState_Restoring)
14364 {
14365 if (aMachineState != MachineState_Saved)
14366 {
14367 /*
14368 * delete the saved state file once the machine has finished
14369 * restoring from it (note that Console sets the state from
14370 * Restoring to Saved if the VM couldn't restore successfully,
14371 * to give the user an ability to fix an error and retry --
14372 * we keep the saved state file in this case)
14373 */
14374 deleteSavedState = true;
14375 }
14376 }
14377 else if ( oldMachineState == MachineState_Saved
14378 && ( aMachineState == MachineState_PoweredOff
14379 || aMachineState == MachineState_Aborted
14380 || aMachineState == MachineState_Teleported
14381 )
14382 )
14383 {
14384 /*
14385 * delete the saved state after SessionMachine::ForgetSavedState() is called
14386 * or if the VM process (owning a direct VM session) crashed while the
14387 * VM was Saved
14388 */
14389
14390 /// @todo (dmik)
14391 // Not sure that deleting the saved state file just because of the
14392 // client death before it attempted to restore the VM is a good
14393 // thing. But when it crashes we need to go to the Aborted state
14394 // which cannot have the saved state file associated... The only
14395 // way to fix this is to make the Aborted condition not a VM state
14396 // but a bool flag: i.e., when a crash occurs, set it to true and
14397 // change the state to PoweredOff or Saved depending on the
14398 // saved state presence.
14399
14400 deleteSavedState = true;
14401 mData->mCurrentStateModified = TRUE;
14402 stsFlags |= SaveSTS_CurStateModified;
14403 }
14404
14405 if ( aMachineState == MachineState_Starting
14406 || aMachineState == MachineState_Restoring
14407 || aMachineState == MachineState_TeleportingIn
14408 )
14409 {
14410 /* set the current state modified flag to indicate that the current
14411 * state is no more identical to the state in the
14412 * current snapshot */
14413 if (!mData->mCurrentSnapshot.isNull())
14414 {
14415 mData->mCurrentStateModified = TRUE;
14416 stsFlags |= SaveSTS_CurStateModified;
14417 }
14418 }
14419
14420 if (deleteSavedState)
14421 {
14422 if (mRemoveSavedState)
14423 {
14424 Assert(!mSSData->strStateFilePath.isEmpty());
14425
14426 // it is safe to delete the saved state file if ...
14427 if ( !mData->mFirstSnapshot // ... we have no snapshots or
14428 || !mData->mFirstSnapshot->i_sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
14429 // ... none of the snapshots share the saved state file
14430 )
14431 RTFileDelete(mSSData->strStateFilePath.c_str());
14432 }
14433
14434 mSSData->strStateFilePath.setNull();
14435 stsFlags |= SaveSTS_StateFilePath;
14436 }
14437
14438 /* redirect to the underlying peer machine */
14439 mPeer->i_setMachineState(aMachineState);
14440
14441 if ( oldMachineState != MachineState_RestoringSnapshot
14442 && ( aMachineState == MachineState_PoweredOff
14443 || aMachineState == MachineState_Teleported
14444 || aMachineState == MachineState_Aborted
14445 || aMachineState == MachineState_Saved))
14446 {
14447 /* the machine has stopped execution
14448 * (or the saved state file was adopted) */
14449 stsFlags |= SaveSTS_StateTimeStamp;
14450 }
14451
14452 if ( ( oldMachineState == MachineState_PoweredOff
14453 || oldMachineState == MachineState_Aborted
14454 || oldMachineState == MachineState_Teleported
14455 )
14456 && aMachineState == MachineState_Saved)
14457 {
14458 /* the saved state file was adopted */
14459 Assert(!mSSData->strStateFilePath.isEmpty());
14460 stsFlags |= SaveSTS_StateFilePath;
14461 }
14462
14463#ifdef VBOX_WITH_GUEST_PROPS
14464 if ( aMachineState == MachineState_PoweredOff
14465 || aMachineState == MachineState_Aborted
14466 || aMachineState == MachineState_Teleported)
14467 {
14468 /* Make sure any transient guest properties get removed from the
14469 * property store on shutdown. */
14470 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
14471
14472 /* remove it from the settings representation */
14473 settings::GuestPropertiesList &llGuestProperties = mData->pMachineConfigFile->hardwareMachine.llGuestProperties;
14474 for (settings::GuestPropertiesList::iterator it = llGuestProperties.begin();
14475 it != llGuestProperties.end();
14476 /*nothing*/)
14477 {
14478 const settings::GuestProperty &prop = *it;
14479 if ( prop.strFlags.contains("TRANSRESET", Utf8Str::CaseInsensitive)
14480 || prop.strFlags.contains("TRANSIENT", Utf8Str::CaseInsensitive))
14481 {
14482 it = llGuestProperties.erase(it);
14483 fNeedsSaving = true;
14484 }
14485 else
14486 {
14487 ++it;
14488 }
14489 }
14490
14491 /* Additionally remove it from the HWData representation. Required to
14492 * keep everything in sync, as this is what the API keeps using. */
14493 HWData::GuestPropertyMap &llHWGuestProperties = mHWData->mGuestProperties;
14494 for (HWData::GuestPropertyMap::iterator it = llHWGuestProperties.begin();
14495 it != llHWGuestProperties.end();
14496 /*nothing*/)
14497 {
14498 uint32_t fFlags = it->second.mFlags;
14499 if ( fFlags & guestProp::TRANSIENT
14500 || fFlags & guestProp::TRANSRESET)
14501 {
14502 /* iterator where we need to continue after the erase call
14503 * (C++03 is a fact still, and it doesn't return the iterator
14504 * which would allow continuing) */
14505 HWData::GuestPropertyMap::iterator it2 = it;
14506 ++it2;
14507 llHWGuestProperties.erase(it);
14508 it = it2;
14509 fNeedsSaving = true;
14510 }
14511 else
14512 {
14513 ++it;
14514 }
14515 }
14516
14517 if (fNeedsSaving)
14518 {
14519 mData->mCurrentStateModified = TRUE;
14520 stsFlags |= SaveSTS_CurStateModified;
14521 }
14522 }
14523#endif /* VBOX_WITH_GUEST_PROPS */
14524
14525 rc = i_saveStateSettings(stsFlags);
14526
14527 if ( ( oldMachineState != MachineState_PoweredOff
14528 && oldMachineState != MachineState_Aborted
14529 && oldMachineState != MachineState_Teleported
14530 )
14531 && ( aMachineState == MachineState_PoweredOff
14532 || aMachineState == MachineState_Aborted
14533 || aMachineState == MachineState_Teleported
14534 )
14535 )
14536 {
14537 /* we've been shut down for any reason */
14538 /* no special action so far */
14539 }
14540
14541 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
14542 LogFlowThisFuncLeave();
14543 return rc;
14544}
14545
14546/**
14547 * Sends the current machine state value to the VM process.
14548 *
14549 * @note Locks this object for reading, then calls a client process.
14550 */
14551HRESULT SessionMachine::i_updateMachineStateOnClient()
14552{
14553 AutoCaller autoCaller(this);
14554 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14555
14556 ComPtr<IInternalSessionControl> directControl;
14557 {
14558 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14559 AssertReturn(!!mData, E_FAIL);
14560 if (mData->mSession.mLockType == LockType_VM)
14561 directControl = mData->mSession.mDirectControl;
14562
14563 /* directControl may be already set to NULL here in #OnSessionEnd()
14564 * called too early by the direct session process while there is still
14565 * some operation (like deleting the snapshot) in progress. The client
14566 * process in this case is waiting inside Session::close() for the
14567 * "end session" process object to complete, while #uninit() called by
14568 * #checkForDeath() on the Watcher thread is waiting for the pending
14569 * operation to complete. For now, we accept this inconsistent behavior
14570 * and simply do nothing here. */
14571
14572 if (mData->mSession.mState == SessionState_Unlocking)
14573 return S_OK;
14574 }
14575
14576 /* ignore notifications sent after #OnSessionEnd() is called */
14577 if (!directControl)
14578 return S_OK;
14579
14580 return directControl->UpdateMachineState(mData->mMachineState);
14581}
14582
14583
14584/**
14585 * Static Machine method that can get passed to RTThreadCreate to
14586 * have a thread started for a Task. See Machine::Task.
14587 */
14588/* static */ DECLCALLBACK(int) Machine::taskHandler(RTTHREAD /* thread */, void *pvUser)
14589{
14590 AssertReturn(pvUser, VERR_INVALID_POINTER);
14591
14592 Task *pTask = static_cast<Task *>(pvUser);
14593 pTask->handler();
14594 /** @todo r=klaus it would be safer to update the progress object here,
14595 * as it avoids possible races due to scoping issues/tricks in the handler */
14596 // it's our responsibility to delete the task
14597 delete pTask;
14598
14599 return 0;
14600}
14601
14602/*static*/
14603HRESULT Machine::i_setErrorStatic(HRESULT aResultCode, const char *pcszMsg, ...)
14604{
14605 va_list args;
14606 va_start(args, pcszMsg);
14607 HRESULT rc = setErrorInternal(aResultCode,
14608 getStaticClassIID(),
14609 getStaticComponentName(),
14610 Utf8Str(pcszMsg, args),
14611 false /* aWarning */,
14612 true /* aLogIt */);
14613 va_end(args);
14614 return rc;
14615}
14616
14617
14618HRESULT Machine::updateState(MachineState_T aState)
14619{
14620 NOREF(aState);
14621 ReturnComNotImplemented();
14622}
14623
14624HRESULT Machine::beginPowerUp(const ComPtr<IProgress> &aProgress)
14625{
14626 NOREF(aProgress);
14627 ReturnComNotImplemented();
14628}
14629
14630HRESULT Machine::endPowerUp(LONG aResult)
14631{
14632 NOREF(aResult);
14633 ReturnComNotImplemented();
14634}
14635
14636HRESULT Machine::beginPoweringDown(ComPtr<IProgress> &aProgress)
14637{
14638 NOREF(aProgress);
14639 ReturnComNotImplemented();
14640}
14641
14642HRESULT Machine::endPoweringDown(LONG aResult,
14643 const com::Utf8Str &aErrMsg)
14644{
14645 NOREF(aResult);
14646 NOREF(aErrMsg);
14647 ReturnComNotImplemented();
14648}
14649
14650HRESULT Machine::runUSBDeviceFilters(const ComPtr<IUSBDevice> &aDevice,
14651 BOOL *aMatched,
14652 ULONG *aMaskedInterfaces)
14653{
14654 NOREF(aDevice);
14655 NOREF(aMatched);
14656 NOREF(aMaskedInterfaces);
14657 ReturnComNotImplemented();
14658
14659}
14660
14661HRESULT Machine::captureUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
14662{
14663 NOREF(aId); NOREF(aCaptureFilename);
14664 ReturnComNotImplemented();
14665}
14666
14667HRESULT Machine::detachUSBDevice(const com::Guid &aId,
14668 BOOL aDone)
14669{
14670 NOREF(aId);
14671 NOREF(aDone);
14672 ReturnComNotImplemented();
14673}
14674
14675HRESULT Machine::autoCaptureUSBDevices()
14676{
14677 ReturnComNotImplemented();
14678}
14679
14680HRESULT Machine::detachAllUSBDevices(BOOL aDone)
14681{
14682 NOREF(aDone);
14683 ReturnComNotImplemented();
14684}
14685
14686HRESULT Machine::onSessionEnd(const ComPtr<ISession> &aSession,
14687 ComPtr<IProgress> &aProgress)
14688{
14689 NOREF(aSession);
14690 NOREF(aProgress);
14691 ReturnComNotImplemented();
14692}
14693
14694HRESULT Machine::finishOnlineMergeMedium()
14695{
14696 ReturnComNotImplemented();
14697}
14698
14699HRESULT Machine::pullGuestProperties(std::vector<com::Utf8Str> &aNames,
14700 std::vector<com::Utf8Str> &aValues,
14701 std::vector<LONG64> &aTimestamps,
14702 std::vector<com::Utf8Str> &aFlags)
14703{
14704 NOREF(aNames);
14705 NOREF(aValues);
14706 NOREF(aTimestamps);
14707 NOREF(aFlags);
14708 ReturnComNotImplemented();
14709}
14710
14711HRESULT Machine::pushGuestProperty(const com::Utf8Str &aName,
14712 const com::Utf8Str &aValue,
14713 LONG64 aTimestamp,
14714 const com::Utf8Str &aFlags)
14715{
14716 NOREF(aName);
14717 NOREF(aValue);
14718 NOREF(aTimestamp);
14719 NOREF(aFlags);
14720 ReturnComNotImplemented();
14721}
14722
14723HRESULT Machine::lockMedia()
14724{
14725 ReturnComNotImplemented();
14726}
14727
14728HRESULT Machine::unlockMedia()
14729{
14730 ReturnComNotImplemented();
14731}
14732
14733HRESULT Machine::ejectMedium(const ComPtr<IMediumAttachment> &aAttachment,
14734 ComPtr<IMediumAttachment> &aNewAttachment)
14735{
14736 NOREF(aAttachment);
14737 NOREF(aNewAttachment);
14738 ReturnComNotImplemented();
14739}
14740
14741HRESULT Machine::reportVmStatistics(ULONG aValidStats,
14742 ULONG aCpuUser,
14743 ULONG aCpuKernel,
14744 ULONG aCpuIdle,
14745 ULONG aMemTotal,
14746 ULONG aMemFree,
14747 ULONG aMemBalloon,
14748 ULONG aMemShared,
14749 ULONG aMemCache,
14750 ULONG aPagedTotal,
14751 ULONG aMemAllocTotal,
14752 ULONG aMemFreeTotal,
14753 ULONG aMemBalloonTotal,
14754 ULONG aMemSharedTotal,
14755 ULONG aVmNetRx,
14756 ULONG aVmNetTx)
14757{
14758 NOREF(aValidStats);
14759 NOREF(aCpuUser);
14760 NOREF(aCpuKernel);
14761 NOREF(aCpuIdle);
14762 NOREF(aMemTotal);
14763 NOREF(aMemFree);
14764 NOREF(aMemBalloon);
14765 NOREF(aMemShared);
14766 NOREF(aMemCache);
14767 NOREF(aPagedTotal);
14768 NOREF(aMemAllocTotal);
14769 NOREF(aMemFreeTotal);
14770 NOREF(aMemBalloonTotal);
14771 NOREF(aMemSharedTotal);
14772 NOREF(aVmNetRx);
14773 NOREF(aVmNetTx);
14774 ReturnComNotImplemented();
14775}
14776
14777HRESULT Machine::applyDefaults(const com::Utf8Str &aFlags)
14778{
14779 NOREF(aFlags);
14780 ReturnComNotImplemented();
14781}
14782
14783/* This isn't handled entirely by the wrapper generator yet. */
14784#ifdef VBOX_WITH_XPCOM
14785NS_DECL_CLASSINFO(SessionMachine)
14786NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
14787
14788NS_DECL_CLASSINFO(SnapshotMachine)
14789NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
14790#endif
Note: See TracBrowser for help on using the repository browser.

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