VirtualBox

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

Last change on this file since 45706 was 45706, checked in by vboxsync, 12 years ago

more temporary debugging

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 478.4 KB
Line 
1/* $Id: MachineImpl.cpp 45706 2013-04-24 14:42:02Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2004-2013 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#ifdef VBOX_WITH_SYS_V_IPC_SESSION_WATCHER
27# include <errno.h>
28# include <sys/types.h>
29# include <sys/stat.h>
30# include <sys/ipc.h>
31# include <sys/sem.h>
32#endif
33
34#include "Logging.h"
35#include "VirtualBoxImpl.h"
36#include "MachineImpl.h"
37#include "ProgressImpl.h"
38#include "ProgressProxyImpl.h"
39#include "MediumAttachmentImpl.h"
40#include "MediumImpl.h"
41#include "MediumLock.h"
42#include "USBControllerImpl.h"
43#include "HostImpl.h"
44#include "SharedFolderImpl.h"
45#include "GuestOSTypeImpl.h"
46#include "VirtualBoxErrorInfoImpl.h"
47#include "GuestImpl.h"
48#include "StorageControllerImpl.h"
49#include "DisplayImpl.h"
50#include "DisplayUtils.h"
51#include "BandwidthControlImpl.h"
52#include "MachineImplCloneVM.h"
53#include "AutostartDb.h"
54
55// generated header
56#include "VBoxEvents.h"
57
58#ifdef VBOX_WITH_USB
59# include "USBProxyService.h"
60#endif
61
62#include "AutoCaller.h"
63#include "HashedPw.h"
64#include "Performance.h"
65
66#include <iprt/asm.h>
67#include <iprt/path.h>
68#include <iprt/dir.h>
69#include <iprt/env.h>
70#include <iprt/lockvalidator.h>
71#include <iprt/process.h>
72#include <iprt/cpp/utils.h>
73#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
74#include <iprt/sha.h>
75#include <iprt/string.h>
76
77#include <VBox/com/array.h>
78#include <VBox/com/list.h>
79
80#include <VBox/err.h>
81#include <VBox/param.h>
82#include <VBox/settings.h>
83#include <VBox/vmm/ssm.h>
84
85#ifdef VBOX_WITH_GUEST_PROPS
86# include <VBox/HostServices/GuestPropertySvc.h>
87# include <VBox/com/array.h>
88#endif
89
90#include "VBox/com/MultiResult.h"
91
92#include <algorithm>
93
94#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
95# define HOSTSUFF_EXE ".exe"
96#else /* !RT_OS_WINDOWS */
97# define HOSTSUFF_EXE ""
98#endif /* !RT_OS_WINDOWS */
99
100// defines / prototypes
101/////////////////////////////////////////////////////////////////////////////
102
103/////////////////////////////////////////////////////////////////////////////
104// Machine::Data structure
105/////////////////////////////////////////////////////////////////////////////
106
107Machine::Data::Data()
108{
109 mRegistered = FALSE;
110 pMachineConfigFile = NULL;
111 /* Contains hints on what has changed when the user is using the VM (config
112 * changes, running the VM, ...). This is used to decide if a config needs
113 * to be written to disk. */
114 flModifications = 0;
115 /* VM modification usually also trigger setting the current state to
116 * "Modified". Although this is not always the case. An e.g. is the VM
117 * initialization phase or when snapshot related data is changed. The
118 * actually behavior is controlled by the following flag. */
119 m_fAllowStateModification = false;
120 mAccessible = FALSE;
121 /* mUuid is initialized in Machine::init() */
122
123 mMachineState = MachineState_PoweredOff;
124 RTTimeNow(&mLastStateChange);
125
126 mMachineStateDeps = 0;
127 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
128 mMachineStateChangePending = 0;
129
130 mCurrentStateModified = TRUE;
131 mGuestPropertiesModified = FALSE;
132
133 mSession.mPID = NIL_RTPROCESS;
134 mSession.mState = SessionState_Unlocked;
135}
136
137Machine::Data::~Data()
138{
139 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
140 {
141 RTSemEventMultiDestroy(mMachineStateDepsSem);
142 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
143 }
144 if (pMachineConfigFile)
145 {
146 delete pMachineConfigFile;
147 pMachineConfigFile = NULL;
148 }
149}
150
151/////////////////////////////////////////////////////////////////////////////
152// Machine::HWData structure
153/////////////////////////////////////////////////////////////////////////////
154
155Machine::HWData::HWData()
156{
157 /* default values for a newly created machine */
158 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
159 mMemorySize = 128;
160 mCPUCount = 1;
161 mCPUHotPlugEnabled = false;
162 mMemoryBalloonSize = 0;
163 mPageFusionEnabled = false;
164 mGraphicsControllerType = GraphicsControllerType_VBoxVGA;
165 mVRAMSize = 8;
166 mAccelerate3DEnabled = false;
167 mAccelerate2DVideoEnabled = false;
168 mMonitorCount = 1;
169 mVideoCaptureFile = "Test.webm";
170 mVideoCaptureWidth = 640;
171 mVideoCaptureHeight = 480;
172 mVideoCaptureEnabled = false;
173
174 mHWVirtExEnabled = true;
175 mHWVirtExNestedPagingEnabled = true;
176#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
177 mHWVirtExLargePagesEnabled = true;
178#else
179 /* Not supported on 32 bits hosts. */
180 mHWVirtExLargePagesEnabled = false;
181#endif
182 mHWVirtExVPIDEnabled = true;
183 mHWVirtExForceEnabled = false;
184#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
185 mHWVirtExExclusive = false;
186#else
187 mHWVirtExExclusive = true;
188#endif
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 mSyntheticCpu = false;
196 mHPETEnabled = false;
197
198 /* default boot order: floppy - DVD - HDD */
199 mBootOrder[0] = DeviceType_Floppy;
200 mBootOrder[1] = DeviceType_DVD;
201 mBootOrder[2] = DeviceType_HardDisk;
202 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
203 mBootOrder[i] = DeviceType_Null;
204
205 mClipboardMode = ClipboardMode_Disabled;
206 mDragAndDropMode = DragAndDropMode_Disabled;
207 mGuestPropertyNotificationPatterns = "";
208
209 mFirmwareType = FirmwareType_BIOS;
210 mKeyboardHIDType = KeyboardHIDType_PS2Keyboard;
211 mPointingHIDType = PointingHIDType_PS2Mouse;
212 mChipsetType = ChipsetType_PIIX3;
213 mEmulatedUSBWebcamEnabled = FALSE;
214 mEmulatedUSBCardReaderEnabled = FALSE;
215
216 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); i++)
217 mCPUAttached[i] = false;
218
219 mIOCacheEnabled = true;
220 mIOCacheSize = 5; /* 5MB */
221
222 /* Maximum CPU execution cap by default. */
223 mCpuExecutionCap = 100;
224}
225
226Machine::HWData::~HWData()
227{
228}
229
230/////////////////////////////////////////////////////////////////////////////
231// Machine::HDData structure
232/////////////////////////////////////////////////////////////////////////////
233
234Machine::MediaData::MediaData()
235{
236}
237
238Machine::MediaData::~MediaData()
239{
240}
241
242/////////////////////////////////////////////////////////////////////////////
243// Machine class
244/////////////////////////////////////////////////////////////////////////////
245
246// constructor / destructor
247/////////////////////////////////////////////////////////////////////////////
248
249Machine::Machine()
250 : mCollectorGuest(NULL),
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 = 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 = 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->id();
344
345 /* Apply BIOS defaults */
346 mBIOSSettings->applyDefaults(aOsType);
347
348 /* Apply network adapters defaults */
349 for (ULONG slot = 0; slot < mNetworkAdapters.size(); ++slot)
350 mNetworkAdapters[slot]->applyDefaults(aOsType);
351
352 /* Apply serial port defaults */
353 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
354 mSerialPorts[slot]->applyDefaults(aOsType);
355
356 /* Let the OS type select 64-bit ness. */
357 mHWData->mLongMode = aOsType->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 allowStateModification();
364
365 /* commit all changes made during the initialization */
366 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 = 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->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 = 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 allowStateModification();
466
467 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->unregisterMachineMedia(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->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 = 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 = 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 allowStateModification();
565
566 /* commit all changes made during the initialization */
567 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 autoInitSpan.setLimited();
579
580 // uninit media from this machine's media registry, or else
581 // reloading the settings will fail
582 mParent->unregisterMachineMedia(getId());
583 }
584 }
585
586 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
587 "rc=%08X\n",
588 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
589 mData->mRegistered, mData->mAccessible, rc));
590
591 LogFlowThisFuncLeave();
592
593 return rc;
594}
595
596/**
597 * Shared code between the various init() implementations.
598 * @param aParent
599 * @return
600 */
601HRESULT Machine::initImpl(VirtualBox *aParent,
602 const Utf8Str &strConfigFile)
603{
604 LogFlowThisFuncEnter();
605
606 AssertReturn(aParent, E_INVALIDARG);
607 AssertReturn(!strConfigFile.isEmpty(), E_INVALIDARG);
608
609 HRESULT rc = S_OK;
610
611 /* share the parent weakly */
612 unconst(mParent) = aParent;
613
614 /* allocate the essential machine data structure (the rest will be
615 * allocated later by initDataAndChildObjects() */
616 mData.allocate();
617
618 /* memorize the config file name (as provided) */
619 mData->m_strConfigFile = strConfigFile;
620
621 /* get the full file name */
622 int vrc1 = mParent->calculateFullPath(strConfigFile, mData->m_strConfigFileFull);
623 if (RT_FAILURE(vrc1))
624 return setError(VBOX_E_FILE_ERROR,
625 tr("Invalid machine settings file name '%s' (%Rrc)"),
626 strConfigFile.c_str(),
627 vrc1);
628
629 LogFlowThisFuncLeave();
630
631 return rc;
632}
633
634/**
635 * Tries to create a machine settings file in the path stored in the machine
636 * instance data. Used when a new machine is created to fail gracefully if
637 * the settings file could not be written (e.g. because machine dir is read-only).
638 * @return
639 */
640HRESULT Machine::tryCreateMachineConfigFile(bool fForceOverwrite)
641{
642 HRESULT rc = S_OK;
643
644 // when we create a new machine, we must be able to create the settings file
645 RTFILE f = NIL_RTFILE;
646 int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
647 if ( RT_SUCCESS(vrc)
648 || vrc == VERR_SHARING_VIOLATION
649 )
650 {
651 if (RT_SUCCESS(vrc))
652 RTFileClose(f);
653 if (!fForceOverwrite)
654 rc = setError(VBOX_E_FILE_ERROR,
655 tr("Machine settings file '%s' already exists"),
656 mData->m_strConfigFileFull.c_str());
657 else
658 {
659 /* try to delete the config file, as otherwise the creation
660 * of a new settings file will fail. */
661 int vrc2 = RTFileDelete(mData->m_strConfigFileFull.c_str());
662 if (RT_FAILURE(vrc2))
663 rc = setError(VBOX_E_FILE_ERROR,
664 tr("Could not delete the existing settings file '%s' (%Rrc)"),
665 mData->m_strConfigFileFull.c_str(), vrc2);
666 }
667 }
668 else if ( vrc != VERR_FILE_NOT_FOUND
669 && vrc != VERR_PATH_NOT_FOUND
670 )
671 rc = setError(VBOX_E_FILE_ERROR,
672 tr("Invalid machine settings file name '%s' (%Rrc)"),
673 mData->m_strConfigFileFull.c_str(),
674 vrc);
675 return rc;
676}
677
678/**
679 * Initializes the registered machine by loading the settings file.
680 * This method is separated from #init() in order to make it possible to
681 * retry the operation after VirtualBox startup instead of refusing to
682 * startup the whole VirtualBox server in case if the settings file of some
683 * registered VM is invalid or inaccessible.
684 *
685 * @note Must be always called from this object's write lock
686 * (unless called from #init() that doesn't need any locking).
687 * @note Locks the mUSBController method for writing.
688 * @note Subclasses must not call this method.
689 */
690HRESULT Machine::registeredInit()
691{
692 AssertReturn(!isSessionMachine(), E_FAIL);
693 AssertReturn(!isSnapshotMachine(), E_FAIL);
694 AssertReturn(mData->mUuid.isValid(), E_FAIL);
695 AssertReturn(!mData->mAccessible, E_FAIL);
696
697 HRESULT rc = initDataAndChildObjects();
698
699 if (SUCCEEDED(rc))
700 {
701 /* Temporarily reset the registered flag in order to let setters
702 * potentially called from loadSettings() succeed (isMutable() used in
703 * all setters will return FALSE for a Machine instance if mRegistered
704 * is TRUE). */
705 mData->mRegistered = FALSE;
706
707 try
708 {
709 // load and parse machine XML; this will throw on XML or logic errors
710 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
711
712 if (mData->mUuid != mData->pMachineConfigFile->uuid)
713 throw setError(E_FAIL,
714 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
715 mData->pMachineConfigFile->uuid.raw(),
716 mData->m_strConfigFileFull.c_str(),
717 mData->mUuid.toString().c_str(),
718 mParent->settingsFilePath().c_str());
719
720 rc = loadMachineDataFromSettings(*mData->pMachineConfigFile,
721 NULL /* const Guid *puuidRegistry */);
722 if (FAILED(rc)) throw rc;
723 }
724 catch (HRESULT err)
725 {
726 /* we assume that error info is set by the thrower */
727 rc = err;
728 }
729 catch (...)
730 {
731 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
732 }
733
734 /* Restore the registered flag (even on failure) */
735 mData->mRegistered = TRUE;
736 }
737
738 if (SUCCEEDED(rc))
739 {
740 /* Set mAccessible to TRUE only if we successfully locked and loaded
741 * the settings file */
742 mData->mAccessible = TRUE;
743
744 /* commit all changes made during loading the settings file */
745 commit(); // @todo r=dj why do we need a commit during init?!? this is very expensive
746 /// @todo r=klaus for some reason the settings loading logic backs up
747 // the settings, and therefore a commit is needed. Should probably be changed.
748 }
749 else
750 {
751 /* If the machine is registered, then, instead of returning a
752 * failure, we mark it as inaccessible and set the result to
753 * success to give it a try later */
754
755 /* fetch the current error info */
756 mData->mAccessError = com::ErrorInfo();
757 LogWarning(("Machine {%RTuuid} is inaccessible! [%ls]\n",
758 mData->mUuid.raw(),
759 mData->mAccessError.getText().raw()));
760
761 /* rollback all changes */
762 rollback(false /* aNotify */);
763
764 // uninit media from this machine's media registry, or else
765 // reloading the settings will fail
766 mParent->unregisterMachineMedia(getId());
767
768 /* uninitialize the common part to make sure all data is reset to
769 * default (null) values */
770 uninitDataAndChildObjects();
771
772 rc = S_OK;
773 }
774
775 return rc;
776}
777
778/**
779 * Uninitializes the instance.
780 * Called either from FinalRelease() or by the parent when it gets destroyed.
781 *
782 * @note The caller of this method must make sure that this object
783 * a) doesn't have active callers on the current thread and b) is not locked
784 * by the current thread; otherwise uninit() will hang either a) due to
785 * AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
786 * a dead-lock caused by this thread waiting for all callers on the other
787 * threads are done but preventing them from doing so by holding a lock.
788 */
789void Machine::uninit()
790{
791 LogFlowThisFuncEnter();
792
793 Assert(!isWriteLockOnCurrentThread());
794
795 Assert(!uRegistryNeedsSaving);
796 if (uRegistryNeedsSaving)
797 {
798 AutoCaller autoCaller(this);
799 if (SUCCEEDED(autoCaller.rc()))
800 {
801 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
802 saveSettings(NULL, Machine::SaveS_Force);
803 }
804 }
805
806 /* Enclose the state transition Ready->InUninit->NotReady */
807 AutoUninitSpan autoUninitSpan(this);
808 if (autoUninitSpan.uninitDone())
809 return;
810
811 Assert(!isSnapshotMachine());
812 Assert(!isSessionMachine());
813 Assert(!!mData);
814
815 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
816 LogFlowThisFunc(("mRegistered=%d\n", mData->mRegistered));
817
818 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
819
820 if (!mData->mSession.mMachine.isNull())
821 {
822 /* Theoretically, this can only happen if the VirtualBox server has been
823 * terminated while there were clients running that owned open direct
824 * sessions. Since in this case we are definitely called by
825 * VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
826 * won't happen on the client watcher thread (because it does
827 * VirtualBox::addCaller() for the duration of the
828 * SessionMachine::checkForDeath() call, so that VirtualBox::uninit()
829 * cannot happen until the VirtualBox caller is released). This is
830 * important, because SessionMachine::uninit() cannot correctly operate
831 * after we return from this method (it expects the Machine instance is
832 * still valid). We'll call it ourselves below.
833 */
834 LogWarningThisFunc(("Session machine is not NULL (%p), the direct session is still open!\n",
835 (SessionMachine*)mData->mSession.mMachine));
836
837 if (Global::IsOnlineOrTransient(mData->mMachineState))
838 {
839 LogWarningThisFunc(("Setting state to Aborted!\n"));
840 /* set machine state using SessionMachine reimplementation */
841 static_cast<Machine*>(mData->mSession.mMachine)->setMachineState(MachineState_Aborted);
842 }
843
844 /*
845 * Uninitialize SessionMachine using public uninit() to indicate
846 * an unexpected uninitialization.
847 */
848 mData->mSession.mMachine->uninit();
849 /* SessionMachine::uninit() must set mSession.mMachine to null */
850 Assert(mData->mSession.mMachine.isNull());
851 }
852
853 // uninit media from this machine's media registry, if they're still there
854 Guid uuidMachine(getId());
855
856 /* the lock is no more necessary (SessionMachine is uninitialized) */
857 alock.release();
858
859 /* XXX This will fail with
860 * "cannot be closed because it is still attached to 1 virtual machines"
861 * because at this point we did not call uninitDataAndChildObjects() yet
862 * and therefore also removeBackReference() for all these mediums was not called! */
863
864 if (uuidMachine.isValid() && !uuidMachine.isZero()) // can be empty if we're called from a failure of Machine::init
865 mParent->unregisterMachineMedia(uuidMachine);
866
867 // has machine been modified?
868 if (mData->flModifications)
869 {
870 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
871 rollback(false /* aNotify */);
872 }
873
874 if (mData->mAccessible)
875 uninitDataAndChildObjects();
876
877 /* free the essential data structure last */
878 mData.free();
879
880 LogFlowThisFuncLeave();
881}
882
883// IMachine properties
884/////////////////////////////////////////////////////////////////////////////
885
886STDMETHODIMP Machine::COMGETTER(Parent)(IVirtualBox **aParent)
887{
888 CheckComArgOutPointerValid(aParent);
889
890 AutoLimitedCaller autoCaller(this);
891 if (FAILED(autoCaller.rc())) return autoCaller.rc();
892
893 /* mParent is constant during life time, no need to lock */
894 ComObjPtr<VirtualBox> pVirtualBox(mParent);
895 pVirtualBox.queryInterfaceTo(aParent);
896
897 return S_OK;
898}
899
900STDMETHODIMP Machine::COMGETTER(Accessible)(BOOL *aAccessible)
901{
902 CheckComArgOutPointerValid(aAccessible);
903
904 AutoLimitedCaller autoCaller(this);
905 if (FAILED(autoCaller.rc())) return autoCaller.rc();
906
907 LogFlowThisFunc(("ENTER\n"));
908
909 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
910
911 HRESULT rc = S_OK;
912
913 if (!mData->mAccessible)
914 {
915 /* try to initialize the VM once more if not accessible */
916
917 AutoReinitSpan autoReinitSpan(this);
918 AssertReturn(autoReinitSpan.isOk(), E_FAIL);
919
920#ifdef DEBUG
921 LogFlowThisFunc(("Dumping media backreferences\n"));
922 mParent->dumpAllBackRefs();
923#endif
924
925 if (mData->pMachineConfigFile)
926 {
927 // reset the XML file to force loadSettings() (called from registeredInit())
928 // to parse it again; the file might have changed
929 delete mData->pMachineConfigFile;
930 mData->pMachineConfigFile = NULL;
931 }
932
933 rc = registeredInit();
934
935 if (SUCCEEDED(rc) && mData->mAccessible)
936 {
937 autoReinitSpan.setSucceeded();
938
939 /* make sure interesting parties will notice the accessibility
940 * state change */
941 mParent->onMachineStateChange(mData->mUuid, mData->mMachineState);
942 mParent->onMachineDataChange(mData->mUuid);
943 }
944 }
945
946 if (SUCCEEDED(rc))
947 *aAccessible = mData->mAccessible;
948
949 LogFlowThisFuncLeave();
950
951 return rc;
952}
953
954STDMETHODIMP Machine::COMGETTER(AccessError)(IVirtualBoxErrorInfo **aAccessError)
955{
956 CheckComArgOutPointerValid(aAccessError);
957
958 AutoLimitedCaller autoCaller(this);
959 if (FAILED(autoCaller.rc())) return autoCaller.rc();
960
961 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
962
963 if (mData->mAccessible || !mData->mAccessError.isBasicAvailable())
964 {
965 /* return shortly */
966 aAccessError = NULL;
967 return S_OK;
968 }
969
970 HRESULT rc = S_OK;
971
972 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
973 rc = errorInfo.createObject();
974 if (SUCCEEDED(rc))
975 {
976 errorInfo->init(mData->mAccessError.getResultCode(),
977 mData->mAccessError.getInterfaceID().ref(),
978 Utf8Str(mData->mAccessError.getComponent()).c_str(),
979 Utf8Str(mData->mAccessError.getText()));
980 rc = errorInfo.queryInterfaceTo(aAccessError);
981 }
982
983 return rc;
984}
985
986STDMETHODIMP Machine::COMGETTER(Name)(BSTR *aName)
987{
988 CheckComArgOutPointerValid(aName);
989
990 AutoCaller autoCaller(this);
991 if (FAILED(autoCaller.rc())) return autoCaller.rc();
992
993 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
994
995 mUserData->s.strName.cloneTo(aName);
996
997 return S_OK;
998}
999
1000STDMETHODIMP Machine::COMSETTER(Name)(IN_BSTR aName)
1001{
1002 CheckComArgStrNotEmptyOrNull(aName);
1003
1004 AutoCaller autoCaller(this);
1005 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1006
1007 // prohibit setting a UUID only as the machine name, or else it can
1008 // never be found by findMachine()
1009 Guid test(aName);
1010
1011 if (test.isValid())
1012 return setError(E_INVALIDARG, tr("A machine cannot have a UUID as its name"));
1013
1014 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1015
1016 HRESULT rc = checkStateDependency(MutableStateDep);
1017 if (FAILED(rc)) return rc;
1018
1019 setModified(IsModified_MachineData);
1020 mUserData.backup();
1021 mUserData->s.strName = aName;
1022
1023 return S_OK;
1024}
1025
1026STDMETHODIMP Machine::COMGETTER(Description)(BSTR *aDescription)
1027{
1028 CheckComArgOutPointerValid(aDescription);
1029
1030 AutoCaller autoCaller(this);
1031 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1032
1033 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1034
1035 mUserData->s.strDescription.cloneTo(aDescription);
1036
1037 return S_OK;
1038}
1039
1040STDMETHODIMP Machine::COMSETTER(Description)(IN_BSTR aDescription)
1041{
1042 AutoCaller autoCaller(this);
1043 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1044
1045 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1046
1047 // this can be done in principle in any state as it doesn't affect the VM
1048 // significantly, but play safe by not messing around while complex
1049 // activities are going on
1050 HRESULT rc = checkStateDependency(MutableOrSavedStateDep);
1051 if (FAILED(rc)) return rc;
1052
1053 setModified(IsModified_MachineData);
1054 mUserData.backup();
1055 mUserData->s.strDescription = aDescription;
1056
1057 return S_OK;
1058}
1059
1060STDMETHODIMP Machine::COMGETTER(Id)(BSTR *aId)
1061{
1062 CheckComArgOutPointerValid(aId);
1063
1064 AutoLimitedCaller autoCaller(this);
1065 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1066
1067 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1068
1069 mData->mUuid.toUtf16().cloneTo(aId);
1070
1071 return S_OK;
1072}
1073
1074STDMETHODIMP Machine::COMGETTER(Groups)(ComSafeArrayOut(BSTR, aGroups))
1075{
1076 CheckComArgOutSafeArrayPointerValid(aGroups);
1077
1078 AutoCaller autoCaller(this);
1079 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1080
1081 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1082 SafeArray<BSTR> groups(mUserData->s.llGroups.size());
1083 size_t i = 0;
1084 for (StringsList::const_iterator it = mUserData->s.llGroups.begin();
1085 it != mUserData->s.llGroups.end();
1086 ++it, i++)
1087 {
1088 Bstr tmp = *it;
1089 tmp.cloneTo(&groups[i]);
1090 }
1091 groups.detachTo(ComSafeArrayOutArg(aGroups));
1092
1093 return S_OK;
1094}
1095
1096STDMETHODIMP Machine::COMSETTER(Groups)(ComSafeArrayIn(IN_BSTR, aGroups))
1097{
1098 AutoCaller autoCaller(this);
1099 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1100
1101 StringsList llGroups;
1102 HRESULT rc = mParent->convertMachineGroups(ComSafeArrayInArg(aGroups), &llGroups);
1103 if (FAILED(rc))
1104 return rc;
1105
1106 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1107
1108 // changing machine groups is possible while the VM is offline
1109 rc = checkStateDependency(OfflineStateDep);
1110 if (FAILED(rc)) return rc;
1111
1112 setModified(IsModified_MachineData);
1113 mUserData.backup();
1114 mUserData->s.llGroups = llGroups;
1115
1116 return S_OK;
1117}
1118
1119STDMETHODIMP Machine::COMGETTER(OSTypeId)(BSTR *aOSTypeId)
1120{
1121 CheckComArgOutPointerValid(aOSTypeId);
1122
1123 AutoCaller autoCaller(this);
1124 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1125
1126 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1127
1128 mUserData->s.strOsType.cloneTo(aOSTypeId);
1129
1130 return S_OK;
1131}
1132
1133STDMETHODIMP Machine::COMSETTER(OSTypeId)(IN_BSTR aOSTypeId)
1134{
1135 CheckComArgStrNotEmptyOrNull(aOSTypeId);
1136
1137 AutoCaller autoCaller(this);
1138 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1139
1140 /* look up the object by Id to check it is valid */
1141 ComPtr<IGuestOSType> guestOSType;
1142 HRESULT rc = mParent->GetGuestOSType(aOSTypeId, guestOSType.asOutParam());
1143 if (FAILED(rc)) return rc;
1144
1145 /* when setting, always use the "etalon" value for consistency -- lookup
1146 * by ID is case-insensitive and the input value may have different case */
1147 Bstr osTypeId;
1148 rc = guestOSType->COMGETTER(Id)(osTypeId.asOutParam());
1149 if (FAILED(rc)) return rc;
1150
1151 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1152
1153 rc = checkStateDependency(MutableStateDep);
1154 if (FAILED(rc)) return rc;
1155
1156 setModified(IsModified_MachineData);
1157 mUserData.backup();
1158 mUserData->s.strOsType = osTypeId;
1159
1160 return S_OK;
1161}
1162
1163
1164STDMETHODIMP Machine::COMGETTER(FirmwareType)(FirmwareType_T *aFirmwareType)
1165{
1166 CheckComArgOutPointerValid(aFirmwareType);
1167
1168 AutoCaller autoCaller(this);
1169 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1170
1171 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1172
1173 *aFirmwareType = mHWData->mFirmwareType;
1174
1175 return S_OK;
1176}
1177
1178STDMETHODIMP Machine::COMSETTER(FirmwareType)(FirmwareType_T aFirmwareType)
1179{
1180 AutoCaller autoCaller(this);
1181 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1182 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1183
1184 HRESULT rc = checkStateDependency(MutableStateDep);
1185 if (FAILED(rc)) return rc;
1186
1187 setModified(IsModified_MachineData);
1188 mHWData.backup();
1189 mHWData->mFirmwareType = aFirmwareType;
1190
1191 return S_OK;
1192}
1193
1194STDMETHODIMP Machine::COMGETTER(KeyboardHIDType)(KeyboardHIDType_T *aKeyboardHIDType)
1195{
1196 CheckComArgOutPointerValid(aKeyboardHIDType);
1197
1198 AutoCaller autoCaller(this);
1199 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1200
1201 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1202
1203 *aKeyboardHIDType = mHWData->mKeyboardHIDType;
1204
1205 return S_OK;
1206}
1207
1208STDMETHODIMP Machine::COMSETTER(KeyboardHIDType)(KeyboardHIDType_T aKeyboardHIDType)
1209{
1210 AutoCaller autoCaller(this);
1211 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1212 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1213
1214 HRESULT rc = checkStateDependency(MutableStateDep);
1215 if (FAILED(rc)) return rc;
1216
1217 setModified(IsModified_MachineData);
1218 mHWData.backup();
1219 mHWData->mKeyboardHIDType = aKeyboardHIDType;
1220
1221 return S_OK;
1222}
1223
1224STDMETHODIMP Machine::COMGETTER(PointingHIDType)(PointingHIDType_T *aPointingHIDType)
1225{
1226 CheckComArgOutPointerValid(aPointingHIDType);
1227
1228 AutoCaller autoCaller(this);
1229 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1230
1231 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1232
1233 *aPointingHIDType = mHWData->mPointingHIDType;
1234
1235 return S_OK;
1236}
1237
1238STDMETHODIMP Machine::COMSETTER(PointingHIDType)(PointingHIDType_T aPointingHIDType)
1239{
1240 AutoCaller autoCaller(this);
1241 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1242 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1243
1244 HRESULT rc = checkStateDependency(MutableStateDep);
1245 if (FAILED(rc)) return rc;
1246
1247 setModified(IsModified_MachineData);
1248 mHWData.backup();
1249 mHWData->mPointingHIDType = aPointingHIDType;
1250
1251 return S_OK;
1252}
1253
1254STDMETHODIMP Machine::COMGETTER(ChipsetType)(ChipsetType_T *aChipsetType)
1255{
1256 CheckComArgOutPointerValid(aChipsetType);
1257
1258 AutoCaller autoCaller(this);
1259 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1260
1261 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1262
1263 *aChipsetType = mHWData->mChipsetType;
1264
1265 return S_OK;
1266}
1267
1268STDMETHODIMP Machine::COMSETTER(ChipsetType)(ChipsetType_T aChipsetType)
1269{
1270 AutoCaller autoCaller(this);
1271 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1273
1274 HRESULT rc = checkStateDependency(MutableStateDep);
1275 if (FAILED(rc)) return rc;
1276
1277 if (aChipsetType != mHWData->mChipsetType)
1278 {
1279 setModified(IsModified_MachineData);
1280 mHWData.backup();
1281 mHWData->mChipsetType = aChipsetType;
1282
1283 // Resize network adapter array, to be finalized on commit/rollback.
1284 // We must not throw away entries yet, otherwise settings are lost
1285 // without a way to roll back.
1286 uint32_t newCount = Global::getMaxNetworkAdapters(aChipsetType);
1287 uint32_t oldCount = mNetworkAdapters.size();
1288 if (newCount > oldCount)
1289 {
1290 mNetworkAdapters.resize(newCount);
1291 for (ULONG slot = oldCount; slot < mNetworkAdapters.size(); slot++)
1292 {
1293 unconst(mNetworkAdapters[slot]).createObject();
1294 mNetworkAdapters[slot]->init(this, slot);
1295 }
1296 }
1297 }
1298
1299 return S_OK;
1300}
1301
1302STDMETHODIMP Machine::COMGETTER(HardwareVersion)(BSTR *aHWVersion)
1303{
1304 CheckComArgOutPointerValid(aHWVersion);
1305
1306 AutoCaller autoCaller(this);
1307 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1308
1309 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1310
1311 mHWData->mHWVersion.cloneTo(aHWVersion);
1312
1313 return S_OK;
1314}
1315
1316STDMETHODIMP Machine::COMSETTER(HardwareVersion)(IN_BSTR aHWVersion)
1317{
1318 /* check known version */
1319 Utf8Str hwVersion = aHWVersion;
1320 if ( hwVersion.compare("1") != 0
1321 && hwVersion.compare("2") != 0)
1322 return setError(E_INVALIDARG,
1323 tr("Invalid hardware version: %ls\n"), aHWVersion);
1324
1325 AutoCaller autoCaller(this);
1326 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1327
1328 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1329
1330 HRESULT rc = checkStateDependency(MutableStateDep);
1331 if (FAILED(rc)) return rc;
1332
1333 setModified(IsModified_MachineData);
1334 mHWData.backup();
1335 mHWData->mHWVersion = hwVersion;
1336
1337 return S_OK;
1338}
1339
1340STDMETHODIMP Machine::COMGETTER(HardwareUUID)(BSTR *aUUID)
1341{
1342 CheckComArgOutPointerValid(aUUID);
1343
1344 AutoCaller autoCaller(this);
1345 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1346
1347 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1348
1349 if (mHWData->mHardwareUUID.isValid())
1350 mHWData->mHardwareUUID.toUtf16().cloneTo(aUUID);
1351 else
1352 mData->mUuid.toUtf16().cloneTo(aUUID);
1353
1354 return S_OK;
1355}
1356
1357STDMETHODIMP Machine::COMSETTER(HardwareUUID)(IN_BSTR aUUID)
1358{
1359 Guid hardwareUUID(aUUID);
1360 if (!hardwareUUID.isValid())
1361 return E_INVALIDARG;
1362
1363 AutoCaller autoCaller(this);
1364 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1365
1366 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1367
1368 HRESULT rc = checkStateDependency(MutableStateDep);
1369 if (FAILED(rc)) return rc;
1370
1371 setModified(IsModified_MachineData);
1372 mHWData.backup();
1373 if (hardwareUUID == mData->mUuid)
1374 mHWData->mHardwareUUID.clear();
1375 else
1376 mHWData->mHardwareUUID = hardwareUUID;
1377
1378 return S_OK;
1379}
1380
1381STDMETHODIMP Machine::COMGETTER(MemorySize)(ULONG *memorySize)
1382{
1383 CheckComArgOutPointerValid(memorySize);
1384
1385 AutoCaller autoCaller(this);
1386 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1387
1388 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1389
1390 *memorySize = mHWData->mMemorySize;
1391
1392 return S_OK;
1393}
1394
1395STDMETHODIMP Machine::COMSETTER(MemorySize)(ULONG memorySize)
1396{
1397 /* check RAM limits */
1398 if ( memorySize < MM_RAM_MIN_IN_MB
1399 || memorySize > MM_RAM_MAX_IN_MB
1400 )
1401 return setError(E_INVALIDARG,
1402 tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1403 memorySize, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
1404
1405 AutoCaller autoCaller(this);
1406 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1407
1408 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1409
1410 HRESULT rc = checkStateDependency(MutableStateDep);
1411 if (FAILED(rc)) return rc;
1412
1413 setModified(IsModified_MachineData);
1414 mHWData.backup();
1415 mHWData->mMemorySize = memorySize;
1416
1417 return S_OK;
1418}
1419
1420STDMETHODIMP Machine::COMGETTER(CPUCount)(ULONG *CPUCount)
1421{
1422 CheckComArgOutPointerValid(CPUCount);
1423
1424 AutoCaller autoCaller(this);
1425 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1426
1427 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1428
1429 *CPUCount = mHWData->mCPUCount;
1430
1431 return S_OK;
1432}
1433
1434STDMETHODIMP Machine::COMSETTER(CPUCount)(ULONG CPUCount)
1435{
1436 /* check CPU limits */
1437 if ( CPUCount < SchemaDefs::MinCPUCount
1438 || CPUCount > SchemaDefs::MaxCPUCount
1439 )
1440 return setError(E_INVALIDARG,
1441 tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
1442 CPUCount, SchemaDefs::MinCPUCount, SchemaDefs::MaxCPUCount);
1443
1444 AutoCaller autoCaller(this);
1445 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1446
1447 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1448
1449 /* We cant go below the current number of CPUs attached if hotplug is enabled*/
1450 if (mHWData->mCPUHotPlugEnabled)
1451 {
1452 for (unsigned idx = CPUCount; idx < SchemaDefs::MaxCPUCount; idx++)
1453 {
1454 if (mHWData->mCPUAttached[idx])
1455 return setError(E_INVALIDARG,
1456 tr("There is still a CPU attached to socket %lu."
1457 "Detach the CPU before removing the socket"),
1458 CPUCount, idx+1);
1459 }
1460 }
1461
1462 HRESULT rc = checkStateDependency(MutableStateDep);
1463 if (FAILED(rc)) return rc;
1464
1465 setModified(IsModified_MachineData);
1466 mHWData.backup();
1467 mHWData->mCPUCount = CPUCount;
1468
1469 return S_OK;
1470}
1471
1472STDMETHODIMP Machine::COMGETTER(CPUExecutionCap)(ULONG *aExecutionCap)
1473{
1474 CheckComArgOutPointerValid(aExecutionCap);
1475
1476 AutoCaller autoCaller(this);
1477 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1478
1479 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1480
1481 *aExecutionCap = mHWData->mCpuExecutionCap;
1482
1483 return S_OK;
1484}
1485
1486STDMETHODIMP Machine::COMSETTER(CPUExecutionCap)(ULONG aExecutionCap)
1487{
1488 HRESULT rc = S_OK;
1489
1490 /* check throttle limits */
1491 if ( aExecutionCap < 1
1492 || aExecutionCap > 100
1493 )
1494 return setError(E_INVALIDARG,
1495 tr("Invalid CPU execution cap value: %lu (must be in range [%lu, %lu])"),
1496 aExecutionCap, 1, 100);
1497
1498 AutoCaller autoCaller(this);
1499 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1500
1501 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1502
1503 alock.release();
1504 rc = onCPUExecutionCapChange(aExecutionCap);
1505 alock.acquire();
1506 if (FAILED(rc)) return rc;
1507
1508 setModified(IsModified_MachineData);
1509 mHWData.backup();
1510 mHWData->mCpuExecutionCap = aExecutionCap;
1511
1512 /* Save settings if online - todo why is this required?? */
1513 if (Global::IsOnline(mData->mMachineState))
1514 saveSettings(NULL);
1515
1516 return S_OK;
1517}
1518
1519
1520STDMETHODIMP Machine::COMGETTER(CPUHotPlugEnabled)(BOOL *enabled)
1521{
1522 CheckComArgOutPointerValid(enabled);
1523
1524 AutoCaller autoCaller(this);
1525 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1526
1527 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1528
1529 *enabled = mHWData->mCPUHotPlugEnabled;
1530
1531 return S_OK;
1532}
1533
1534STDMETHODIMP Machine::COMSETTER(CPUHotPlugEnabled)(BOOL enabled)
1535{
1536 HRESULT rc = S_OK;
1537
1538 AutoCaller autoCaller(this);
1539 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1540
1541 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1542
1543 rc = checkStateDependency(MutableStateDep);
1544 if (FAILED(rc)) return rc;
1545
1546 if (mHWData->mCPUHotPlugEnabled != enabled)
1547 {
1548 if (enabled)
1549 {
1550 setModified(IsModified_MachineData);
1551 mHWData.backup();
1552
1553 /* Add the amount of CPUs currently attached */
1554 for (unsigned i = 0; i < mHWData->mCPUCount; i++)
1555 {
1556 mHWData->mCPUAttached[i] = true;
1557 }
1558 }
1559 else
1560 {
1561 /*
1562 * We can disable hotplug only if the amount of maximum CPUs is equal
1563 * to the amount of attached CPUs
1564 */
1565 unsigned cCpusAttached = 0;
1566 unsigned iHighestId = 0;
1567
1568 for (unsigned i = 0; i < SchemaDefs::MaxCPUCount; i++)
1569 {
1570 if (mHWData->mCPUAttached[i])
1571 {
1572 cCpusAttached++;
1573 iHighestId = i;
1574 }
1575 }
1576
1577 if ( (cCpusAttached != mHWData->mCPUCount)
1578 || (iHighestId >= mHWData->mCPUCount))
1579 return setError(E_INVALIDARG,
1580 tr("CPU hotplugging can't be disabled because the maximum number of CPUs is not equal to the amount of CPUs attached"));
1581
1582 setModified(IsModified_MachineData);
1583 mHWData.backup();
1584 }
1585 }
1586
1587 mHWData->mCPUHotPlugEnabled = enabled;
1588
1589 return rc;
1590}
1591
1592STDMETHODIMP Machine::COMGETTER(EmulatedUSBCardReaderEnabled)(BOOL *enabled)
1593{
1594#ifdef VBOX_WITH_USB_CARDREADER
1595 CheckComArgOutPointerValid(enabled);
1596
1597 AutoCaller autoCaller(this);
1598 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1599
1600 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1601
1602 *enabled = mHWData->mEmulatedUSBCardReaderEnabled;
1603
1604 return S_OK;
1605#else
1606 NOREF(enabled);
1607 return E_NOTIMPL;
1608#endif
1609}
1610
1611STDMETHODIMP Machine::COMSETTER(EmulatedUSBCardReaderEnabled)(BOOL enabled)
1612{
1613#ifdef VBOX_WITH_USB_CARDREADER
1614 AutoCaller autoCaller(this);
1615 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1616 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1617
1618 HRESULT rc = checkStateDependency(MutableStateDep);
1619 if (FAILED(rc)) return rc;
1620
1621 setModified(IsModified_MachineData);
1622 mHWData.backup();
1623 mHWData->mEmulatedUSBCardReaderEnabled = enabled;
1624
1625 return S_OK;
1626#else
1627 NOREF(enabled);
1628 return E_NOTIMPL;
1629#endif
1630}
1631
1632STDMETHODIMP Machine::COMGETTER(EmulatedUSBWebcameraEnabled)(BOOL *enabled)
1633{
1634#ifdef VBOX_WITH_USB_VIDEO
1635 CheckComArgOutPointerValid(enabled);
1636
1637 AutoCaller autoCaller(this);
1638 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1639
1640 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1641
1642 *enabled = mHWData->mEmulatedUSBWebcamEnabled;
1643
1644 return S_OK;
1645#else
1646 NOREF(enabled);
1647 return E_NOTIMPL;
1648#endif
1649}
1650
1651STDMETHODIMP Machine::COMSETTER(EmulatedUSBWebcameraEnabled)(BOOL enabled)
1652{
1653#ifdef VBOX_WITH_USB_VIDEO
1654 AutoCaller autoCaller(this);
1655 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1656 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1657
1658 HRESULT rc = checkStateDependency(MutableStateDep);
1659 if (FAILED(rc)) return rc;
1660
1661 setModified(IsModified_MachineData);
1662 mHWData.backup();
1663 mHWData->mEmulatedUSBWebcamEnabled = enabled;
1664
1665 return S_OK;
1666#else
1667 NOREF(enabled);
1668 return E_NOTIMPL;
1669#endif
1670}
1671
1672STDMETHODIMP Machine::COMGETTER(HPETEnabled)(BOOL *enabled)
1673{
1674 CheckComArgOutPointerValid(enabled);
1675
1676 AutoCaller autoCaller(this);
1677 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1678 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1679
1680 *enabled = mHWData->mHPETEnabled;
1681
1682 return S_OK;
1683}
1684
1685STDMETHODIMP Machine::COMSETTER(HPETEnabled)(BOOL enabled)
1686{
1687 HRESULT rc = S_OK;
1688
1689 AutoCaller autoCaller(this);
1690 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1691 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1692
1693 rc = checkStateDependency(MutableStateDep);
1694 if (FAILED(rc)) return rc;
1695
1696 setModified(IsModified_MachineData);
1697 mHWData.backup();
1698
1699 mHWData->mHPETEnabled = enabled;
1700
1701 return rc;
1702}
1703
1704STDMETHODIMP Machine::COMGETTER(VideoCaptureEnabled)(BOOL *fEnabled)
1705{
1706 AutoCaller autoCaller(this);
1707 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1708
1709 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1710
1711 *fEnabled = mHWData->mVideoCaptureEnabled;
1712 return S_OK;
1713}
1714
1715STDMETHODIMP Machine::COMSETTER(VideoCaptureEnabled)(BOOL fEnabled)
1716{
1717 AutoCaller autoCaller(this);
1718 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1719
1720 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1721 mHWData->mVideoCaptureEnabled = fEnabled;
1722 return S_OK;
1723}
1724
1725STDMETHODIMP Machine::COMGETTER(VideoCaptureFile)(BSTR * apFile)
1726{
1727 AutoCaller autoCaller(this);
1728 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1729
1730 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1731 mHWData->mVideoCaptureFile.cloneTo(apFile);
1732 return S_OK;
1733}
1734
1735STDMETHODIMP Machine::COMSETTER(VideoCaptureFile)(IN_BSTR aFile)
1736{
1737 Utf8Str strFile(aFile);
1738 AutoCaller autoCaller(this);
1739 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1740
1741 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1742 if (strFile.isEmpty())
1743 strFile = "VideoCap.webm";
1744 mHWData->mVideoCaptureFile = strFile;
1745 return S_OK;
1746}
1747
1748
1749STDMETHODIMP Machine::COMGETTER(VideoCaptureWidth)(ULONG *ulHorzRes)
1750{
1751 AutoCaller autoCaller(this);
1752 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1753
1754 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1755 *ulHorzRes = mHWData->mVideoCaptureWidth;
1756 return S_OK;
1757}
1758
1759STDMETHODIMP Machine::COMSETTER(VideoCaptureWidth)(ULONG ulHorzRes)
1760{
1761 AutoCaller autoCaller(this);
1762 if (FAILED(autoCaller.rc()))
1763 {
1764 LogFlow(("Autolocked failed\n"));
1765 return autoCaller.rc();
1766 }
1767
1768 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1769 mHWData->mVideoCaptureWidth = ulHorzRes;
1770 return S_OK;
1771}
1772
1773STDMETHODIMP Machine::COMGETTER(VideoCaptureHeight)(ULONG *ulVertRes)
1774{
1775 AutoCaller autoCaller(this);
1776 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1777
1778 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1779 *ulVertRes = mHWData->mVideoCaptureHeight;
1780 return S_OK;
1781}
1782
1783STDMETHODIMP Machine::COMSETTER(VideoCaptureHeight)(ULONG ulVertRes)
1784{
1785 AutoCaller autoCaller(this);
1786 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1787
1788 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1789 mHWData->mVideoCaptureHeight = ulVertRes;
1790 return S_OK;
1791}
1792
1793STDMETHODIMP Machine::COMGETTER(GraphicsControllerType)(GraphicsControllerType_T *aGraphicsControllerType)
1794{
1795 CheckComArgOutPointerValid(aGraphicsControllerType);
1796
1797 AutoCaller autoCaller(this);
1798 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1799
1800 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1801
1802 *aGraphicsControllerType = mHWData->mGraphicsControllerType;
1803
1804 return S_OK;
1805}
1806
1807STDMETHODIMP Machine::COMSETTER(GraphicsControllerType)(GraphicsControllerType_T aGraphicsControllerType)
1808{
1809 switch (aGraphicsControllerType)
1810 {
1811 case GraphicsControllerType_Null:
1812 case GraphicsControllerType_VBoxVGA:
1813 break;
1814 default:
1815 return setError(E_INVALIDARG, tr("The graphics controller type (%d) is invalid"), aGraphicsControllerType);
1816 }
1817
1818 AutoCaller autoCaller(this);
1819 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1820
1821 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1822
1823 HRESULT rc = checkStateDependency(MutableStateDep);
1824 if (FAILED(rc)) return rc;
1825
1826 setModified(IsModified_MachineData);
1827 mHWData.backup();
1828 mHWData->mGraphicsControllerType = aGraphicsControllerType;
1829
1830 return S_OK;
1831}
1832
1833STDMETHODIMP Machine::COMGETTER(VRAMSize)(ULONG *memorySize)
1834{
1835 CheckComArgOutPointerValid(memorySize);
1836
1837 AutoCaller autoCaller(this);
1838 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1839
1840 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1841
1842 *memorySize = mHWData->mVRAMSize;
1843
1844 return S_OK;
1845}
1846
1847STDMETHODIMP Machine::COMSETTER(VRAMSize)(ULONG memorySize)
1848{
1849 /* check VRAM limits */
1850 if (memorySize < SchemaDefs::MinGuestVRAM ||
1851 memorySize > SchemaDefs::MaxGuestVRAM)
1852 return setError(E_INVALIDARG,
1853 tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1854 memorySize, SchemaDefs::MinGuestVRAM, SchemaDefs::MaxGuestVRAM);
1855
1856 AutoCaller autoCaller(this);
1857 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1858
1859 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1860
1861 HRESULT rc = checkStateDependency(MutableStateDep);
1862 if (FAILED(rc)) return rc;
1863
1864 setModified(IsModified_MachineData);
1865 mHWData.backup();
1866 mHWData->mVRAMSize = memorySize;
1867
1868 return S_OK;
1869}
1870
1871/** @todo this method should not be public */
1872STDMETHODIMP Machine::COMGETTER(MemoryBalloonSize)(ULONG *memoryBalloonSize)
1873{
1874 CheckComArgOutPointerValid(memoryBalloonSize);
1875
1876 AutoCaller autoCaller(this);
1877 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1878
1879 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1880
1881 *memoryBalloonSize = mHWData->mMemoryBalloonSize;
1882
1883 return S_OK;
1884}
1885
1886/**
1887 * Set the memory balloon size.
1888 *
1889 * This method is also called from IGuest::COMSETTER(MemoryBalloonSize) so
1890 * we have to make sure that we never call IGuest from here.
1891 */
1892STDMETHODIMP Machine::COMSETTER(MemoryBalloonSize)(ULONG memoryBalloonSize)
1893{
1894 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
1895#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
1896 /* check limits */
1897 if (memoryBalloonSize >= VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize))
1898 return setError(E_INVALIDARG,
1899 tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
1900 memoryBalloonSize, 0, VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize));
1901
1902 AutoCaller autoCaller(this);
1903 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1904
1905 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1906
1907 setModified(IsModified_MachineData);
1908 mHWData.backup();
1909 mHWData->mMemoryBalloonSize = memoryBalloonSize;
1910
1911 return S_OK;
1912#else
1913 NOREF(memoryBalloonSize);
1914 return setError(E_NOTIMPL, tr("Memory ballooning is only supported on 64-bit hosts"));
1915#endif
1916}
1917
1918STDMETHODIMP Machine::COMGETTER(PageFusionEnabled) (BOOL *enabled)
1919{
1920 CheckComArgOutPointerValid(enabled);
1921
1922 AutoCaller autoCaller(this);
1923 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1924
1925 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1926
1927 *enabled = mHWData->mPageFusionEnabled;
1928 return S_OK;
1929}
1930
1931STDMETHODIMP Machine::COMSETTER(PageFusionEnabled) (BOOL enabled)
1932{
1933#ifdef VBOX_WITH_PAGE_SHARING
1934 AutoCaller autoCaller(this);
1935 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1936
1937 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1938
1939 /** @todo must support changes for running vms and keep this in sync with IGuest. */
1940 setModified(IsModified_MachineData);
1941 mHWData.backup();
1942 mHWData->mPageFusionEnabled = enabled;
1943 return S_OK;
1944#else
1945 NOREF(enabled);
1946 return setError(E_NOTIMPL, tr("Page fusion is only supported on 64-bit hosts"));
1947#endif
1948}
1949
1950STDMETHODIMP Machine::COMGETTER(Accelerate3DEnabled)(BOOL *enabled)
1951{
1952 CheckComArgOutPointerValid(enabled);
1953
1954 AutoCaller autoCaller(this);
1955 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1956
1957 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1958
1959 *enabled = mHWData->mAccelerate3DEnabled;
1960
1961 return S_OK;
1962}
1963
1964STDMETHODIMP Machine::COMSETTER(Accelerate3DEnabled)(BOOL enable)
1965{
1966 AutoCaller autoCaller(this);
1967 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1968
1969 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1970
1971 HRESULT rc = checkStateDependency(MutableStateDep);
1972 if (FAILED(rc)) return rc;
1973
1974 /** @todo check validity! */
1975
1976 setModified(IsModified_MachineData);
1977 mHWData.backup();
1978 mHWData->mAccelerate3DEnabled = enable;
1979
1980 return S_OK;
1981}
1982
1983
1984STDMETHODIMP Machine::COMGETTER(Accelerate2DVideoEnabled)(BOOL *enabled)
1985{
1986 CheckComArgOutPointerValid(enabled);
1987
1988 AutoCaller autoCaller(this);
1989 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1990
1991 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1992
1993 *enabled = mHWData->mAccelerate2DVideoEnabled;
1994
1995 return S_OK;
1996}
1997
1998STDMETHODIMP Machine::COMSETTER(Accelerate2DVideoEnabled)(BOOL enable)
1999{
2000 AutoCaller autoCaller(this);
2001 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2002
2003 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2004
2005 HRESULT rc = checkStateDependency(MutableStateDep);
2006 if (FAILED(rc)) return rc;
2007
2008 /** @todo check validity! */
2009
2010 setModified(IsModified_MachineData);
2011 mHWData.backup();
2012 mHWData->mAccelerate2DVideoEnabled = enable;
2013
2014 return S_OK;
2015}
2016
2017STDMETHODIMP Machine::COMGETTER(MonitorCount)(ULONG *monitorCount)
2018{
2019 CheckComArgOutPointerValid(monitorCount);
2020
2021 AutoCaller autoCaller(this);
2022 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2023
2024 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2025
2026 *monitorCount = mHWData->mMonitorCount;
2027
2028 return S_OK;
2029}
2030
2031STDMETHODIMP Machine::COMSETTER(MonitorCount)(ULONG monitorCount)
2032{
2033 /* make sure monitor count is a sensible number */
2034 if (monitorCount < 1 || monitorCount > SchemaDefs::MaxGuestMonitors)
2035 return setError(E_INVALIDARG,
2036 tr("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
2037 monitorCount, 1, SchemaDefs::MaxGuestMonitors);
2038
2039 AutoCaller autoCaller(this);
2040 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2041
2042 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2043
2044 HRESULT rc = checkStateDependency(MutableStateDep);
2045 if (FAILED(rc)) return rc;
2046
2047 setModified(IsModified_MachineData);
2048 mHWData.backup();
2049 mHWData->mMonitorCount = monitorCount;
2050
2051 return S_OK;
2052}
2053
2054STDMETHODIMP Machine::COMGETTER(BIOSSettings)(IBIOSSettings **biosSettings)
2055{
2056 CheckComArgOutPointerValid(biosSettings);
2057
2058 AutoCaller autoCaller(this);
2059 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2060
2061 /* mBIOSSettings is constant during life time, no need to lock */
2062 mBIOSSettings.queryInterfaceTo(biosSettings);
2063
2064 return S_OK;
2065}
2066
2067STDMETHODIMP Machine::GetCPUProperty(CPUPropertyType_T property, BOOL *aVal)
2068{
2069 CheckComArgOutPointerValid(aVal);
2070
2071 AutoCaller autoCaller(this);
2072 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2073
2074 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2075
2076 switch (property)
2077 {
2078 case CPUPropertyType_PAE:
2079 *aVal = mHWData->mPAEEnabled;
2080 break;
2081
2082 case CPUPropertyType_Synthetic:
2083 *aVal = mHWData->mSyntheticCpu;
2084 break;
2085
2086 case CPUPropertyType_LongMode:
2087 if (mHWData->mLongMode == settings::Hardware::LongMode_Enabled)
2088 *aVal = TRUE;
2089 else if (mHWData->mLongMode == settings::Hardware::LongMode_Disabled)
2090 *aVal = FALSE;
2091#if HC_ARCH_BITS == 64
2092 else
2093 *aVal = TRUE;
2094#else
2095 else
2096 {
2097 *aVal = FALSE;
2098
2099 ComPtr<IGuestOSType> ptrGuestOSType;
2100 HRESULT hrc2 = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(), ptrGuestOSType.asOutParam());
2101 if (SUCCEEDED(hrc2))
2102 {
2103 BOOL fIs64Bit = FALSE;
2104 hrc2 = ptrGuestOSType->COMGETTER(Is64Bit)(&fIs64Bit); AssertComRC(hrc2);
2105 if (SUCCEEDED(hrc2) && fIs64Bit)
2106 {
2107 ComObjPtr<Host> ptrHost = mParent->host();
2108 alock.release();
2109
2110 hrc2 = ptrHost->GetProcessorFeature(ProcessorFeature_LongMode, aVal); AssertComRC(hrc2);
2111 if (FAILED(hrc2))
2112 *aVal = FALSE;
2113 }
2114 }
2115 }
2116#endif
2117 break;
2118
2119 default:
2120 return E_INVALIDARG;
2121 }
2122 return S_OK;
2123}
2124
2125STDMETHODIMP Machine::SetCPUProperty(CPUPropertyType_T property, BOOL aVal)
2126{
2127 AutoCaller autoCaller(this);
2128 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2129
2130 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2131
2132 HRESULT rc = checkStateDependency(MutableStateDep);
2133 if (FAILED(rc)) return rc;
2134
2135 switch (property)
2136 {
2137 case CPUPropertyType_PAE:
2138 setModified(IsModified_MachineData);
2139 mHWData.backup();
2140 mHWData->mPAEEnabled = !!aVal;
2141 break;
2142
2143 case CPUPropertyType_Synthetic:
2144 setModified(IsModified_MachineData);
2145 mHWData.backup();
2146 mHWData->mSyntheticCpu = !!aVal;
2147 break;
2148
2149 case CPUPropertyType_LongMode:
2150 setModified(IsModified_MachineData);
2151 mHWData.backup();
2152 mHWData->mLongMode = !aVal ? settings::Hardware::LongMode_Disabled : settings::Hardware::LongMode_Enabled;
2153 break;
2154
2155 default:
2156 return E_INVALIDARG;
2157 }
2158 return S_OK;
2159}
2160
2161STDMETHODIMP Machine::GetCPUIDLeaf(ULONG aId, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx)
2162{
2163 CheckComArgOutPointerValid(aValEax);
2164 CheckComArgOutPointerValid(aValEbx);
2165 CheckComArgOutPointerValid(aValEcx);
2166 CheckComArgOutPointerValid(aValEdx);
2167
2168 AutoCaller autoCaller(this);
2169 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2170
2171 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2172
2173 switch(aId)
2174 {
2175 case 0x0:
2176 case 0x1:
2177 case 0x2:
2178 case 0x3:
2179 case 0x4:
2180 case 0x5:
2181 case 0x6:
2182 case 0x7:
2183 case 0x8:
2184 case 0x9:
2185 case 0xA:
2186 if (mHWData->mCpuIdStdLeafs[aId].ulId != aId)
2187 return E_INVALIDARG;
2188
2189 *aValEax = mHWData->mCpuIdStdLeafs[aId].ulEax;
2190 *aValEbx = mHWData->mCpuIdStdLeafs[aId].ulEbx;
2191 *aValEcx = mHWData->mCpuIdStdLeafs[aId].ulEcx;
2192 *aValEdx = mHWData->mCpuIdStdLeafs[aId].ulEdx;
2193 break;
2194
2195 case 0x80000000:
2196 case 0x80000001:
2197 case 0x80000002:
2198 case 0x80000003:
2199 case 0x80000004:
2200 case 0x80000005:
2201 case 0x80000006:
2202 case 0x80000007:
2203 case 0x80000008:
2204 case 0x80000009:
2205 case 0x8000000A:
2206 if (mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId != aId)
2207 return E_INVALIDARG;
2208
2209 *aValEax = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax;
2210 *aValEbx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx;
2211 *aValEcx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx;
2212 *aValEdx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx;
2213 break;
2214
2215 default:
2216 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2217 }
2218 return S_OK;
2219}
2220
2221STDMETHODIMP Machine::SetCPUIDLeaf(ULONG aId, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx)
2222{
2223 AutoCaller autoCaller(this);
2224 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2225
2226 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2227
2228 HRESULT rc = checkStateDependency(MutableStateDep);
2229 if (FAILED(rc)) return rc;
2230
2231 switch(aId)
2232 {
2233 case 0x0:
2234 case 0x1:
2235 case 0x2:
2236 case 0x3:
2237 case 0x4:
2238 case 0x5:
2239 case 0x6:
2240 case 0x7:
2241 case 0x8:
2242 case 0x9:
2243 case 0xA:
2244 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2245 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2246 setModified(IsModified_MachineData);
2247 mHWData.backup();
2248 mHWData->mCpuIdStdLeafs[aId].ulId = aId;
2249 mHWData->mCpuIdStdLeafs[aId].ulEax = aValEax;
2250 mHWData->mCpuIdStdLeafs[aId].ulEbx = aValEbx;
2251 mHWData->mCpuIdStdLeafs[aId].ulEcx = aValEcx;
2252 mHWData->mCpuIdStdLeafs[aId].ulEdx = aValEdx;
2253 break;
2254
2255 case 0x80000000:
2256 case 0x80000001:
2257 case 0x80000002:
2258 case 0x80000003:
2259 case 0x80000004:
2260 case 0x80000005:
2261 case 0x80000006:
2262 case 0x80000007:
2263 case 0x80000008:
2264 case 0x80000009:
2265 case 0x8000000A:
2266 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2267 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2268 setModified(IsModified_MachineData);
2269 mHWData.backup();
2270 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = aId;
2271 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax = aValEax;
2272 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx = aValEbx;
2273 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx = aValEcx;
2274 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx = aValEdx;
2275 break;
2276
2277 default:
2278 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2279 }
2280 return S_OK;
2281}
2282
2283STDMETHODIMP Machine::RemoveCPUIDLeaf(ULONG aId)
2284{
2285 AutoCaller autoCaller(this);
2286 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2287
2288 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2289
2290 HRESULT rc = checkStateDependency(MutableStateDep);
2291 if (FAILED(rc)) return rc;
2292
2293 switch(aId)
2294 {
2295 case 0x0:
2296 case 0x1:
2297 case 0x2:
2298 case 0x3:
2299 case 0x4:
2300 case 0x5:
2301 case 0x6:
2302 case 0x7:
2303 case 0x8:
2304 case 0x9:
2305 case 0xA:
2306 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xB);
2307 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
2308 setModified(IsModified_MachineData);
2309 mHWData.backup();
2310 /* Invalidate leaf. */
2311 mHWData->mCpuIdStdLeafs[aId].ulId = UINT32_MAX;
2312 break;
2313
2314 case 0x80000000:
2315 case 0x80000001:
2316 case 0x80000002:
2317 case 0x80000003:
2318 case 0x80000004:
2319 case 0x80000005:
2320 case 0x80000006:
2321 case 0x80000007:
2322 case 0x80000008:
2323 case 0x80000009:
2324 case 0x8000000A:
2325 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xB);
2326 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
2327 setModified(IsModified_MachineData);
2328 mHWData.backup();
2329 /* Invalidate leaf. */
2330 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = UINT32_MAX;
2331 break;
2332
2333 default:
2334 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
2335 }
2336 return S_OK;
2337}
2338
2339STDMETHODIMP Machine::RemoveAllCPUIDLeaves()
2340{
2341 AutoCaller autoCaller(this);
2342 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2343
2344 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2345
2346 HRESULT rc = checkStateDependency(MutableStateDep);
2347 if (FAILED(rc)) return rc;
2348
2349 setModified(IsModified_MachineData);
2350 mHWData.backup();
2351
2352 /* Invalidate all standard leafs. */
2353 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); i++)
2354 mHWData->mCpuIdStdLeafs[i].ulId = UINT32_MAX;
2355
2356 /* Invalidate all extended leafs. */
2357 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); i++)
2358 mHWData->mCpuIdExtLeafs[i].ulId = UINT32_MAX;
2359
2360 return S_OK;
2361}
2362
2363STDMETHODIMP Machine::GetHWVirtExProperty(HWVirtExPropertyType_T property, BOOL *aVal)
2364{
2365 CheckComArgOutPointerValid(aVal);
2366
2367 AutoCaller autoCaller(this);
2368 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2369
2370 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2371
2372 switch(property)
2373 {
2374 case HWVirtExPropertyType_Enabled:
2375 *aVal = mHWData->mHWVirtExEnabled;
2376 break;
2377
2378 case HWVirtExPropertyType_Exclusive:
2379 *aVal = mHWData->mHWVirtExExclusive;
2380 break;
2381
2382 case HWVirtExPropertyType_VPID:
2383 *aVal = mHWData->mHWVirtExVPIDEnabled;
2384 break;
2385
2386 case HWVirtExPropertyType_NestedPaging:
2387 *aVal = mHWData->mHWVirtExNestedPagingEnabled;
2388 break;
2389
2390 case HWVirtExPropertyType_LargePages:
2391 *aVal = mHWData->mHWVirtExLargePagesEnabled;
2392#if defined(DEBUG_bird) && defined(RT_OS_LINUX) /* This feature is deadly here */
2393 *aVal = FALSE;
2394#endif
2395 break;
2396
2397 case HWVirtExPropertyType_Force:
2398 *aVal = mHWData->mHWVirtExForceEnabled;
2399 break;
2400
2401 default:
2402 return E_INVALIDARG;
2403 }
2404 return S_OK;
2405}
2406
2407STDMETHODIMP Machine::SetHWVirtExProperty(HWVirtExPropertyType_T property, BOOL aVal)
2408{
2409 AutoCaller autoCaller(this);
2410 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2411
2412 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2413
2414 HRESULT rc = checkStateDependency(MutableStateDep);
2415 if (FAILED(rc)) return rc;
2416
2417 switch(property)
2418 {
2419 case HWVirtExPropertyType_Enabled:
2420 setModified(IsModified_MachineData);
2421 mHWData.backup();
2422 mHWData->mHWVirtExEnabled = !!aVal;
2423 break;
2424
2425 case HWVirtExPropertyType_Exclusive:
2426 setModified(IsModified_MachineData);
2427 mHWData.backup();
2428 mHWData->mHWVirtExExclusive = !!aVal;
2429 break;
2430
2431 case HWVirtExPropertyType_VPID:
2432 setModified(IsModified_MachineData);
2433 mHWData.backup();
2434 mHWData->mHWVirtExVPIDEnabled = !!aVal;
2435 break;
2436
2437 case HWVirtExPropertyType_NestedPaging:
2438 setModified(IsModified_MachineData);
2439 mHWData.backup();
2440 mHWData->mHWVirtExNestedPagingEnabled = !!aVal;
2441 break;
2442
2443 case HWVirtExPropertyType_LargePages:
2444 setModified(IsModified_MachineData);
2445 mHWData.backup();
2446 mHWData->mHWVirtExLargePagesEnabled = !!aVal;
2447 break;
2448
2449 case HWVirtExPropertyType_Force:
2450 setModified(IsModified_MachineData);
2451 mHWData.backup();
2452 mHWData->mHWVirtExForceEnabled = !!aVal;
2453 break;
2454
2455 default:
2456 return E_INVALIDARG;
2457 }
2458
2459 return S_OK;
2460}
2461
2462STDMETHODIMP Machine::COMGETTER(SnapshotFolder)(BSTR *aSnapshotFolder)
2463{
2464 CheckComArgOutPointerValid(aSnapshotFolder);
2465
2466 AutoCaller autoCaller(this);
2467 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2468
2469 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2470
2471 Utf8Str strFullSnapshotFolder;
2472 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
2473 strFullSnapshotFolder.cloneTo(aSnapshotFolder);
2474
2475 return S_OK;
2476}
2477
2478STDMETHODIMP Machine::COMSETTER(SnapshotFolder)(IN_BSTR aSnapshotFolder)
2479{
2480 /* @todo (r=dmik):
2481 * 1. Allow to change the name of the snapshot folder containing snapshots
2482 * 2. Rename the folder on disk instead of just changing the property
2483 * value (to be smart and not to leave garbage). Note that it cannot be
2484 * done here because the change may be rolled back. Thus, the right
2485 * place is #saveSettings().
2486 */
2487
2488 AutoCaller autoCaller(this);
2489 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2490
2491 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2492
2493 HRESULT rc = checkStateDependency(MutableStateDep);
2494 if (FAILED(rc)) return rc;
2495
2496 if (!mData->mCurrentSnapshot.isNull())
2497 return setError(E_FAIL,
2498 tr("The snapshot folder of a machine with snapshots cannot be changed (please delete all snapshots first)"));
2499
2500 Utf8Str strSnapshotFolder0(aSnapshotFolder); // keep original
2501
2502 Utf8Str strSnapshotFolder(strSnapshotFolder0);
2503 if (strSnapshotFolder.isEmpty())
2504 strSnapshotFolder = "Snapshots";
2505 int vrc = calculateFullPath(strSnapshotFolder,
2506 strSnapshotFolder);
2507 if (RT_FAILURE(vrc))
2508 return setError(E_FAIL,
2509 tr("Invalid snapshot folder '%ls' (%Rrc)"),
2510 aSnapshotFolder, vrc);
2511
2512 setModified(IsModified_MachineData);
2513 mUserData.backup();
2514
2515 copyPathRelativeToMachine(strSnapshotFolder, mUserData->s.strSnapshotFolder);
2516
2517 return S_OK;
2518}
2519
2520STDMETHODIMP Machine::COMGETTER(MediumAttachments)(ComSafeArrayOut(IMediumAttachment*, aAttachments))
2521{
2522 CheckComArgOutSafeArrayPointerValid(aAttachments);
2523
2524 AutoCaller autoCaller(this);
2525 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2526
2527 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2528
2529 SafeIfaceArray<IMediumAttachment> attachments(mMediaData->mAttachments);
2530 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
2531
2532 return S_OK;
2533}
2534
2535STDMETHODIMP Machine::COMGETTER(VRDEServer)(IVRDEServer **vrdeServer)
2536{
2537 CheckComArgOutPointerValid(vrdeServer);
2538
2539 AutoCaller autoCaller(this);
2540 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2541
2542 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2543
2544 Assert(!!mVRDEServer);
2545 mVRDEServer.queryInterfaceTo(vrdeServer);
2546
2547 return S_OK;
2548}
2549
2550STDMETHODIMP Machine::COMGETTER(AudioAdapter)(IAudioAdapter **audioAdapter)
2551{
2552 CheckComArgOutPointerValid(audioAdapter);
2553
2554 AutoCaller autoCaller(this);
2555 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2556
2557 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2558
2559 mAudioAdapter.queryInterfaceTo(audioAdapter);
2560 return S_OK;
2561}
2562
2563STDMETHODIMP Machine::COMGETTER(USBController)(IUSBController **aUSBController)
2564{
2565#ifdef VBOX_WITH_VUSB
2566 CheckComArgOutPointerValid(aUSBController);
2567
2568 AutoCaller autoCaller(this);
2569 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2570
2571 clearError();
2572 MultiResult rc(S_OK);
2573
2574# ifdef VBOX_WITH_USB
2575 rc = mParent->host()->checkUSBProxyService();
2576 if (FAILED(rc)) return rc;
2577# endif
2578
2579 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2580
2581 return rc = mUSBController.queryInterfaceTo(aUSBController);
2582#else
2583 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2584 * extended error info to indicate that USB is simply not available
2585 * (w/o treating it as a failure), for example, as in OSE */
2586 NOREF(aUSBController);
2587 ReturnComNotImplemented();
2588#endif /* VBOX_WITH_VUSB */
2589}
2590
2591STDMETHODIMP Machine::COMGETTER(SettingsFilePath)(BSTR *aFilePath)
2592{
2593 CheckComArgOutPointerValid(aFilePath);
2594
2595 AutoLimitedCaller autoCaller(this);
2596 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2597
2598 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2599
2600 mData->m_strConfigFileFull.cloneTo(aFilePath);
2601 return S_OK;
2602}
2603
2604STDMETHODIMP Machine::COMGETTER(SettingsModified)(BOOL *aModified)
2605{
2606 CheckComArgOutPointerValid(aModified);
2607
2608 AutoCaller autoCaller(this);
2609 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2610
2611 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2612
2613 HRESULT rc = checkStateDependency(MutableStateDep);
2614 if (FAILED(rc)) return rc;
2615
2616 if (!mData->pMachineConfigFile->fileExists())
2617 // this is a new machine, and no config file exists yet:
2618 *aModified = TRUE;
2619 else
2620 *aModified = (mData->flModifications != 0);
2621
2622 return S_OK;
2623}
2624
2625STDMETHODIMP Machine::COMGETTER(SessionState)(SessionState_T *aSessionState)
2626{
2627 CheckComArgOutPointerValid(aSessionState);
2628
2629 AutoCaller autoCaller(this);
2630 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2631
2632 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2633
2634 *aSessionState = mData->mSession.mState;
2635
2636 return S_OK;
2637}
2638
2639STDMETHODIMP Machine::COMGETTER(SessionType)(BSTR *aSessionType)
2640{
2641 CheckComArgOutPointerValid(aSessionType);
2642
2643 AutoCaller autoCaller(this);
2644 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2645
2646 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2647
2648 mData->mSession.mType.cloneTo(aSessionType);
2649
2650 return S_OK;
2651}
2652
2653STDMETHODIMP Machine::COMGETTER(SessionPID)(ULONG *aSessionPID)
2654{
2655 CheckComArgOutPointerValid(aSessionPID);
2656
2657 AutoCaller autoCaller(this);
2658 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2659
2660 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2661
2662 *aSessionPID = mData->mSession.mPID;
2663
2664 return S_OK;
2665}
2666
2667STDMETHODIMP Machine::COMGETTER(State)(MachineState_T *machineState)
2668{
2669 CheckComArgOutPointerValid(machineState);
2670
2671 AutoCaller autoCaller(this);
2672 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2673
2674 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2675
2676 *machineState = mData->mMachineState;
2677
2678 return S_OK;
2679}
2680
2681STDMETHODIMP Machine::COMGETTER(LastStateChange)(LONG64 *aLastStateChange)
2682{
2683 CheckComArgOutPointerValid(aLastStateChange);
2684
2685 AutoCaller autoCaller(this);
2686 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2687
2688 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2689
2690 *aLastStateChange = RTTimeSpecGetMilli(&mData->mLastStateChange);
2691
2692 return S_OK;
2693}
2694
2695STDMETHODIMP Machine::COMGETTER(StateFilePath)(BSTR *aStateFilePath)
2696{
2697 CheckComArgOutPointerValid(aStateFilePath);
2698
2699 AutoCaller autoCaller(this);
2700 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2701
2702 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2703
2704 mSSData->strStateFilePath.cloneTo(aStateFilePath);
2705
2706 return S_OK;
2707}
2708
2709STDMETHODIMP Machine::COMGETTER(LogFolder)(BSTR *aLogFolder)
2710{
2711 CheckComArgOutPointerValid(aLogFolder);
2712
2713 AutoCaller autoCaller(this);
2714 AssertComRCReturnRC(autoCaller.rc());
2715
2716 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2717
2718 Utf8Str logFolder;
2719 getLogFolder(logFolder);
2720 logFolder.cloneTo(aLogFolder);
2721
2722 return S_OK;
2723}
2724
2725STDMETHODIMP Machine::COMGETTER(CurrentSnapshot) (ISnapshot **aCurrentSnapshot)
2726{
2727 CheckComArgOutPointerValid(aCurrentSnapshot);
2728
2729 AutoCaller autoCaller(this);
2730 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2731
2732 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2733
2734 mData->mCurrentSnapshot.queryInterfaceTo(aCurrentSnapshot);
2735
2736 return S_OK;
2737}
2738
2739STDMETHODIMP Machine::COMGETTER(SnapshotCount)(ULONG *aSnapshotCount)
2740{
2741 CheckComArgOutPointerValid(aSnapshotCount);
2742
2743 AutoCaller autoCaller(this);
2744 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2745
2746 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2747
2748 *aSnapshotCount = mData->mFirstSnapshot.isNull()
2749 ? 0
2750 : mData->mFirstSnapshot->getAllChildrenCount() + 1;
2751
2752 return S_OK;
2753}
2754
2755STDMETHODIMP Machine::COMGETTER(CurrentStateModified)(BOOL *aCurrentStateModified)
2756{
2757 CheckComArgOutPointerValid(aCurrentStateModified);
2758
2759 AutoCaller autoCaller(this);
2760 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2761
2762 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2763
2764 /* Note: for machines with no snapshots, we always return FALSE
2765 * (mData->mCurrentStateModified will be TRUE in this case, for historical
2766 * reasons :) */
2767
2768 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
2769 ? FALSE
2770 : mData->mCurrentStateModified;
2771
2772 return S_OK;
2773}
2774
2775STDMETHODIMP Machine::COMGETTER(SharedFolders)(ComSafeArrayOut(ISharedFolder *, aSharedFolders))
2776{
2777 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
2778
2779 AutoCaller autoCaller(this);
2780 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2781
2782 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2783
2784 SafeIfaceArray<ISharedFolder> folders(mHWData->mSharedFolders);
2785 folders.detachTo(ComSafeArrayOutArg(aSharedFolders));
2786
2787 return S_OK;
2788}
2789
2790STDMETHODIMP Machine::COMGETTER(ClipboardMode)(ClipboardMode_T *aClipboardMode)
2791{
2792 CheckComArgOutPointerValid(aClipboardMode);
2793
2794 AutoCaller autoCaller(this);
2795 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2796
2797 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2798
2799 *aClipboardMode = mHWData->mClipboardMode;
2800
2801 return S_OK;
2802}
2803
2804STDMETHODIMP
2805Machine::COMSETTER(ClipboardMode)(ClipboardMode_T aClipboardMode)
2806{
2807 HRESULT rc = S_OK;
2808
2809 AutoCaller autoCaller(this);
2810 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2811
2812 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2813
2814 alock.release();
2815 rc = onClipboardModeChange(aClipboardMode);
2816 alock.acquire();
2817 if (FAILED(rc)) return rc;
2818
2819 setModified(IsModified_MachineData);
2820 mHWData.backup();
2821 mHWData->mClipboardMode = aClipboardMode;
2822
2823 /* Save settings if online - todo why is this required?? */
2824 if (Global::IsOnline(mData->mMachineState))
2825 saveSettings(NULL);
2826
2827 return S_OK;
2828}
2829
2830STDMETHODIMP Machine::COMGETTER(DragAndDropMode)(DragAndDropMode_T *aDragAndDropMode)
2831{
2832 CheckComArgOutPointerValid(aDragAndDropMode);
2833
2834 AutoCaller autoCaller(this);
2835 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2836
2837 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2838
2839 *aDragAndDropMode = mHWData->mDragAndDropMode;
2840
2841 return S_OK;
2842}
2843
2844STDMETHODIMP
2845Machine::COMSETTER(DragAndDropMode)(DragAndDropMode_T aDragAndDropMode)
2846{
2847 HRESULT rc = S_OK;
2848
2849 AutoCaller autoCaller(this);
2850 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2851
2852 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2853
2854 alock.release();
2855 rc = onDragAndDropModeChange(aDragAndDropMode);
2856 alock.acquire();
2857 if (FAILED(rc)) return rc;
2858
2859 setModified(IsModified_MachineData);
2860 mHWData.backup();
2861 mHWData->mDragAndDropMode = aDragAndDropMode;
2862
2863 /* Save settings if online - todo why is this required?? */
2864 if (Global::IsOnline(mData->mMachineState))
2865 saveSettings(NULL);
2866
2867 return S_OK;
2868}
2869
2870STDMETHODIMP
2871Machine::COMGETTER(GuestPropertyNotificationPatterns)(BSTR *aPatterns)
2872{
2873 CheckComArgOutPointerValid(aPatterns);
2874
2875 AutoCaller autoCaller(this);
2876 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2877
2878 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2879
2880 try
2881 {
2882 mHWData->mGuestPropertyNotificationPatterns.cloneTo(aPatterns);
2883 }
2884 catch (...)
2885 {
2886 return VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
2887 }
2888
2889 return S_OK;
2890}
2891
2892STDMETHODIMP
2893Machine::COMSETTER(GuestPropertyNotificationPatterns)(IN_BSTR aPatterns)
2894{
2895 AutoCaller autoCaller(this);
2896 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2897
2898 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2899
2900 HRESULT rc = checkStateDependency(MutableStateDep);
2901 if (FAILED(rc)) return rc;
2902
2903 setModified(IsModified_MachineData);
2904 mHWData.backup();
2905 mHWData->mGuestPropertyNotificationPatterns = aPatterns;
2906 return rc;
2907}
2908
2909STDMETHODIMP
2910Machine::COMGETTER(StorageControllers)(ComSafeArrayOut(IStorageController *, aStorageControllers))
2911{
2912 CheckComArgOutSafeArrayPointerValid(aStorageControllers);
2913
2914 AutoCaller autoCaller(this);
2915 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2916
2917 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2918
2919 SafeIfaceArray<IStorageController> ctrls(*mStorageControllers.data());
2920 ctrls.detachTo(ComSafeArrayOutArg(aStorageControllers));
2921
2922 return S_OK;
2923}
2924
2925STDMETHODIMP
2926Machine::COMGETTER(TeleporterEnabled)(BOOL *aEnabled)
2927{
2928 CheckComArgOutPointerValid(aEnabled);
2929
2930 AutoCaller autoCaller(this);
2931 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2932
2933 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2934
2935 *aEnabled = mUserData->s.fTeleporterEnabled;
2936
2937 return S_OK;
2938}
2939
2940STDMETHODIMP Machine::COMSETTER(TeleporterEnabled)(BOOL aEnabled)
2941{
2942 AutoCaller autoCaller(this);
2943 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2944
2945 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2946
2947 /* Only allow it to be set to true when PoweredOff or Aborted.
2948 (Clearing it is always permitted.) */
2949 if ( aEnabled
2950 && mData->mRegistered
2951 && ( !isSessionMachine()
2952 || ( mData->mMachineState != MachineState_PoweredOff
2953 && mData->mMachineState != MachineState_Teleported
2954 && mData->mMachineState != MachineState_Aborted
2955 )
2956 )
2957 )
2958 return setError(VBOX_E_INVALID_VM_STATE,
2959 tr("The machine is not powered off (state is %s)"),
2960 Global::stringifyMachineState(mData->mMachineState));
2961
2962 setModified(IsModified_MachineData);
2963 mUserData.backup();
2964 mUserData->s.fTeleporterEnabled = !!aEnabled;
2965
2966 return S_OK;
2967}
2968
2969STDMETHODIMP Machine::COMGETTER(TeleporterPort)(ULONG *aPort)
2970{
2971 CheckComArgOutPointerValid(aPort);
2972
2973 AutoCaller autoCaller(this);
2974 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2975
2976 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2977
2978 *aPort = (ULONG)mUserData->s.uTeleporterPort;
2979
2980 return S_OK;
2981}
2982
2983STDMETHODIMP Machine::COMSETTER(TeleporterPort)(ULONG aPort)
2984{
2985 if (aPort >= _64K)
2986 return setError(E_INVALIDARG, tr("Invalid port number %d"), aPort);
2987
2988 AutoCaller autoCaller(this);
2989 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2990
2991 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2992
2993 HRESULT rc = checkStateDependency(MutableStateDep);
2994 if (FAILED(rc)) return rc;
2995
2996 setModified(IsModified_MachineData);
2997 mUserData.backup();
2998 mUserData->s.uTeleporterPort = (uint32_t)aPort;
2999
3000 return S_OK;
3001}
3002
3003STDMETHODIMP Machine::COMGETTER(TeleporterAddress)(BSTR *aAddress)
3004{
3005 CheckComArgOutPointerValid(aAddress);
3006
3007 AutoCaller autoCaller(this);
3008 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3009
3010 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3011
3012 mUserData->s.strTeleporterAddress.cloneTo(aAddress);
3013
3014 return S_OK;
3015}
3016
3017STDMETHODIMP Machine::COMSETTER(TeleporterAddress)(IN_BSTR aAddress)
3018{
3019 AutoCaller autoCaller(this);
3020 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3021
3022 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3023
3024 HRESULT rc = checkStateDependency(MutableStateDep);
3025 if (FAILED(rc)) return rc;
3026
3027 setModified(IsModified_MachineData);
3028 mUserData.backup();
3029 mUserData->s.strTeleporterAddress = aAddress;
3030
3031 return S_OK;
3032}
3033
3034STDMETHODIMP Machine::COMGETTER(TeleporterPassword)(BSTR *aPassword)
3035{
3036 CheckComArgOutPointerValid(aPassword);
3037
3038 AutoCaller autoCaller(this);
3039 HRESULT hrc = autoCaller.rc();
3040 if (SUCCEEDED(hrc))
3041 {
3042 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3043 mUserData->s.strTeleporterPassword.cloneTo(aPassword);
3044 }
3045
3046 return hrc;
3047}
3048
3049STDMETHODIMP Machine::COMSETTER(TeleporterPassword)(IN_BSTR aPassword)
3050{
3051 /*
3052 * Hash the password first.
3053 */
3054 Utf8Str strPassword(aPassword);
3055 if (!strPassword.isEmpty())
3056 {
3057 if (VBoxIsPasswordHashed(&strPassword))
3058 return setError(E_INVALIDARG, tr("Cannot set an already hashed password, only plain text password please"));
3059 VBoxHashPassword(&strPassword);
3060 }
3061
3062 /*
3063 * Do the update.
3064 */
3065 AutoCaller autoCaller(this);
3066 HRESULT hrc = autoCaller.rc();
3067 if (SUCCEEDED(hrc))
3068 {
3069 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3070 hrc = checkStateDependency(MutableStateDep);
3071 if (SUCCEEDED(hrc))
3072 {
3073 setModified(IsModified_MachineData);
3074 mUserData.backup();
3075 mUserData->s.strTeleporterPassword = strPassword;
3076 }
3077 }
3078
3079 return hrc;
3080}
3081
3082STDMETHODIMP Machine::COMGETTER(FaultToleranceState)(FaultToleranceState_T *aState)
3083{
3084 CheckComArgOutPointerValid(aState);
3085
3086 AutoCaller autoCaller(this);
3087 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3088
3089 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3090
3091 *aState = mUserData->s.enmFaultToleranceState;
3092 return S_OK;
3093}
3094
3095STDMETHODIMP Machine::COMSETTER(FaultToleranceState)(FaultToleranceState_T aState)
3096{
3097 AutoCaller autoCaller(this);
3098 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3099
3100 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3101
3102 /* @todo deal with running state change. */
3103 HRESULT rc = checkStateDependency(MutableStateDep);
3104 if (FAILED(rc)) return rc;
3105
3106 setModified(IsModified_MachineData);
3107 mUserData.backup();
3108 mUserData->s.enmFaultToleranceState = aState;
3109 return S_OK;
3110}
3111
3112STDMETHODIMP Machine::COMGETTER(FaultToleranceAddress)(BSTR *aAddress)
3113{
3114 CheckComArgOutPointerValid(aAddress);
3115
3116 AutoCaller autoCaller(this);
3117 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3118
3119 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3120
3121 mUserData->s.strFaultToleranceAddress.cloneTo(aAddress);
3122 return S_OK;
3123}
3124
3125STDMETHODIMP Machine::COMSETTER(FaultToleranceAddress)(IN_BSTR aAddress)
3126{
3127 AutoCaller autoCaller(this);
3128 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3129
3130 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3131
3132 /* @todo deal with running state change. */
3133 HRESULT rc = checkStateDependency(MutableStateDep);
3134 if (FAILED(rc)) return rc;
3135
3136 setModified(IsModified_MachineData);
3137 mUserData.backup();
3138 mUserData->s.strFaultToleranceAddress = aAddress;
3139 return S_OK;
3140}
3141
3142STDMETHODIMP Machine::COMGETTER(FaultTolerancePort)(ULONG *aPort)
3143{
3144 CheckComArgOutPointerValid(aPort);
3145
3146 AutoCaller autoCaller(this);
3147 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3148
3149 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3150
3151 *aPort = mUserData->s.uFaultTolerancePort;
3152 return S_OK;
3153}
3154
3155STDMETHODIMP Machine::COMSETTER(FaultTolerancePort)(ULONG aPort)
3156{
3157 AutoCaller autoCaller(this);
3158 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3159
3160 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3161
3162 /* @todo deal with running state change. */
3163 HRESULT rc = checkStateDependency(MutableStateDep);
3164 if (FAILED(rc)) return rc;
3165
3166 setModified(IsModified_MachineData);
3167 mUserData.backup();
3168 mUserData->s.uFaultTolerancePort = aPort;
3169 return S_OK;
3170}
3171
3172STDMETHODIMP Machine::COMGETTER(FaultTolerancePassword)(BSTR *aPassword)
3173{
3174 CheckComArgOutPointerValid(aPassword);
3175
3176 AutoCaller autoCaller(this);
3177 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3178
3179 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3180
3181 mUserData->s.strFaultTolerancePassword.cloneTo(aPassword);
3182
3183 return S_OK;
3184}
3185
3186STDMETHODIMP Machine::COMSETTER(FaultTolerancePassword)(IN_BSTR aPassword)
3187{
3188 AutoCaller autoCaller(this);
3189 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3190
3191 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3192
3193 /* @todo deal with running state change. */
3194 HRESULT rc = checkStateDependency(MutableStateDep);
3195 if (FAILED(rc)) return rc;
3196
3197 setModified(IsModified_MachineData);
3198 mUserData.backup();
3199 mUserData->s.strFaultTolerancePassword = aPassword;
3200
3201 return S_OK;
3202}
3203
3204STDMETHODIMP Machine::COMGETTER(FaultToleranceSyncInterval)(ULONG *aInterval)
3205{
3206 CheckComArgOutPointerValid(aInterval);
3207
3208 AutoCaller autoCaller(this);
3209 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3210
3211 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3212
3213 *aInterval = mUserData->s.uFaultToleranceInterval;
3214 return S_OK;
3215}
3216
3217STDMETHODIMP Machine::COMSETTER(FaultToleranceSyncInterval)(ULONG aInterval)
3218{
3219 AutoCaller autoCaller(this);
3220 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3221
3222 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3223
3224 /* @todo deal with running state change. */
3225 HRESULT rc = checkStateDependency(MutableStateDep);
3226 if (FAILED(rc)) return rc;
3227
3228 setModified(IsModified_MachineData);
3229 mUserData.backup();
3230 mUserData->s.uFaultToleranceInterval = aInterval;
3231 return S_OK;
3232}
3233
3234STDMETHODIMP Machine::COMGETTER(RTCUseUTC)(BOOL *aEnabled)
3235{
3236 CheckComArgOutPointerValid(aEnabled);
3237
3238 AutoCaller autoCaller(this);
3239 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3240
3241 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3242
3243 *aEnabled = mUserData->s.fRTCUseUTC;
3244
3245 return S_OK;
3246}
3247
3248STDMETHODIMP Machine::COMSETTER(RTCUseUTC)(BOOL aEnabled)
3249{
3250 AutoCaller autoCaller(this);
3251 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3252
3253 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3254
3255 /* Only allow it to be set to true when PoweredOff or Aborted.
3256 (Clearing it is always permitted.) */
3257 if ( aEnabled
3258 && mData->mRegistered
3259 && ( !isSessionMachine()
3260 || ( mData->mMachineState != MachineState_PoweredOff
3261 && mData->mMachineState != MachineState_Teleported
3262 && mData->mMachineState != MachineState_Aborted
3263 )
3264 )
3265 )
3266 return setError(VBOX_E_INVALID_VM_STATE,
3267 tr("The machine is not powered off (state is %s)"),
3268 Global::stringifyMachineState(mData->mMachineState));
3269
3270 setModified(IsModified_MachineData);
3271 mUserData.backup();
3272 mUserData->s.fRTCUseUTC = !!aEnabled;
3273
3274 return S_OK;
3275}
3276
3277STDMETHODIMP Machine::COMGETTER(IOCacheEnabled)(BOOL *aEnabled)
3278{
3279 CheckComArgOutPointerValid(aEnabled);
3280
3281 AutoCaller autoCaller(this);
3282 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3283
3284 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3285
3286 *aEnabled = mHWData->mIOCacheEnabled;
3287
3288 return S_OK;
3289}
3290
3291STDMETHODIMP Machine::COMSETTER(IOCacheEnabled)(BOOL aEnabled)
3292{
3293 AutoCaller autoCaller(this);
3294 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3295
3296 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3297
3298 HRESULT rc = checkStateDependency(MutableStateDep);
3299 if (FAILED(rc)) return rc;
3300
3301 setModified(IsModified_MachineData);
3302 mHWData.backup();
3303 mHWData->mIOCacheEnabled = aEnabled;
3304
3305 return S_OK;
3306}
3307
3308STDMETHODIMP Machine::COMGETTER(IOCacheSize)(ULONG *aIOCacheSize)
3309{
3310 CheckComArgOutPointerValid(aIOCacheSize);
3311
3312 AutoCaller autoCaller(this);
3313 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3314
3315 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3316
3317 *aIOCacheSize = mHWData->mIOCacheSize;
3318
3319 return S_OK;
3320}
3321
3322STDMETHODIMP Machine::COMSETTER(IOCacheSize)(ULONG aIOCacheSize)
3323{
3324 AutoCaller autoCaller(this);
3325 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3326
3327 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3328
3329 HRESULT rc = checkStateDependency(MutableStateDep);
3330 if (FAILED(rc)) return rc;
3331
3332 setModified(IsModified_MachineData);
3333 mHWData.backup();
3334 mHWData->mIOCacheSize = aIOCacheSize;
3335
3336 return S_OK;
3337}
3338
3339
3340/**
3341 * @note Locks objects!
3342 */
3343STDMETHODIMP Machine::LockMachine(ISession *aSession,
3344 LockType_T lockType)
3345{
3346 CheckComArgNotNull(aSession);
3347
3348 AutoCaller autoCaller(this);
3349 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3350
3351 /* check the session state */
3352 SessionState_T state;
3353 HRESULT rc = aSession->COMGETTER(State)(&state);
3354 if (FAILED(rc)) return rc;
3355
3356 if (state != SessionState_Unlocked)
3357 return setError(VBOX_E_INVALID_OBJECT_STATE,
3358 tr("The given session is busy"));
3359
3360 // get the client's IInternalSessionControl interface
3361 ComPtr<IInternalSessionControl> pSessionControl = aSession;
3362 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
3363 E_INVALIDARG);
3364
3365 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3366
3367 if (!mData->mRegistered)
3368 return setError(E_UNEXPECTED,
3369 tr("The machine '%s' is not registered"),
3370 mUserData->s.strName.c_str());
3371
3372 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3373
3374 SessionState_T oldState = mData->mSession.mState;
3375 /* Hack: in case the session is closing and there is a progress object
3376 * which allows waiting for the session to be closed, take the opportunity
3377 * and do a limited wait (max. 1 second). This helps a lot when the system
3378 * is busy and thus session closing can take a little while. */
3379 if ( mData->mSession.mState == SessionState_Unlocking
3380 && mData->mSession.mProgress)
3381 {
3382 alock.release();
3383 mData->mSession.mProgress->WaitForCompletion(1000);
3384 alock.acquire();
3385 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
3386 }
3387
3388 // try again now
3389 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already (i.e. session machine exists)
3390 && (lockType == LockType_Shared) // caller wants a shared link to the existing session that holds the write lock:
3391 )
3392 {
3393 // OK, share the session... we are now dealing with three processes:
3394 // 1) VBoxSVC (where this code runs);
3395 // 2) process C: the caller's client process (who wants a shared session);
3396 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
3397
3398 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
3399 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
3400 ComAssertRet(!pSessionW.isNull(), E_FAIL);
3401 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
3402 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
3403
3404 /*
3405 * Release the lock before calling the client process. It's safe here
3406 * since the only thing to do after we get the lock again is to add
3407 * the remote control to the list (which doesn't directly influence
3408 * anything).
3409 */
3410 alock.release();
3411
3412 // get the console of the session holding the write lock (this is a remote call)
3413 ComPtr<IConsole> pConsoleW;
3414 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
3415 rc = pSessionW->GetRemoteConsole(pConsoleW.asOutParam());
3416 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
3417 if (FAILED(rc))
3418 // the failure may occur w/o any error info (from RPC), so provide one
3419 return setError(VBOX_E_VM_ERROR,
3420 tr("Failed to get a console object from the direct session (%Rrc)"), rc);
3421
3422 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
3423
3424 // share the session machine and W's console with the caller's session
3425 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3426 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
3427 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3428
3429 if (FAILED(rc))
3430 // the failure may occur w/o any error info (from RPC), so provide one
3431 return setError(VBOX_E_VM_ERROR,
3432 tr("Failed to assign the machine to the session (%Rrc)"), rc);
3433 alock.acquire();
3434
3435 // need to revalidate the state after acquiring the lock again
3436 if (mData->mSession.mState != SessionState_Locked)
3437 {
3438 pSessionControl->Uninitialize();
3439 return setError(VBOX_E_INVALID_SESSION_STATE,
3440 tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
3441 mUserData->s.strName.c_str());
3442 }
3443
3444 // add the caller's session to the list
3445 mData->mSession.mRemoteControls.push_back(pSessionControl);
3446 }
3447 else if ( mData->mSession.mState == SessionState_Locked
3448 || mData->mSession.mState == SessionState_Unlocking
3449 )
3450 {
3451 // sharing not permitted, or machine still unlocking:
3452 return setError(VBOX_E_INVALID_OBJECT_STATE,
3453 tr("The machine '%s' is already locked for a session (or being unlocked)"),
3454 mUserData->s.strName.c_str());
3455 }
3456 else
3457 {
3458 // machine is not locked: then write-lock the machine (create the session machine)
3459
3460 // must not be busy
3461 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
3462
3463 // get the caller's session PID
3464 RTPROCESS pid = NIL_RTPROCESS;
3465 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
3466 pSessionControl->GetPID((ULONG*)&pid);
3467 Assert(pid != NIL_RTPROCESS);
3468
3469 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
3470
3471 if (fLaunchingVMProcess)
3472 {
3473 // this machine is awaiting for a spawning session to be opened:
3474 // then the calling process must be the one that got started by
3475 // LaunchVMProcess()
3476
3477 LogFlowThisFunc(("mSession.mPID=%d(0x%x)\n", mData->mSession.mPID, mData->mSession.mPID));
3478 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3479
3480 if (mData->mSession.mPID != pid)
3481 return setError(E_ACCESSDENIED,
3482 tr("An unexpected process (PID=0x%08X) has tried to lock the "
3483 "machine '%s', while only the process started by LaunchVMProcess (PID=0x%08X) is allowed"),
3484 pid, mUserData->s.strName.c_str(), mData->mSession.mPID);
3485 }
3486
3487 // create the mutable SessionMachine from the current machine
3488 ComObjPtr<SessionMachine> sessionMachine;
3489 sessionMachine.createObject();
3490 rc = sessionMachine->init(this);
3491 AssertComRC(rc);
3492
3493 /* NOTE: doing return from this function after this point but
3494 * before the end is forbidden since it may call SessionMachine::uninit()
3495 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3496 * lock while still holding the Machine lock in alock so that a deadlock
3497 * is possible due to the wrong lock order. */
3498
3499 if (SUCCEEDED(rc))
3500 {
3501 /*
3502 * Set the session state to Spawning to protect against subsequent
3503 * attempts to open a session and to unregister the machine after
3504 * we release the lock.
3505 */
3506 SessionState_T origState = mData->mSession.mState;
3507 mData->mSession.mState = SessionState_Spawning;
3508
3509 /*
3510 * Release the lock before calling the client process -- it will call
3511 * Machine/SessionMachine methods. Releasing the lock here is quite safe
3512 * because the state is Spawning, so that LaunchVMProcess() and
3513 * LockMachine() calls will fail. This method, called before we
3514 * acquire the lock again, will fail because of the wrong PID.
3515 *
3516 * Note that mData->mSession.mRemoteControls accessed outside
3517 * the lock may not be modified when state is Spawning, so it's safe.
3518 */
3519 alock.release();
3520
3521 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3522 rc = pSessionControl->AssignMachine(sessionMachine, lockType);
3523 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3524
3525 /* The failure may occur w/o any error info (from RPC), so provide one */
3526 if (FAILED(rc))
3527 setError(VBOX_E_VM_ERROR,
3528 tr("Failed to assign the machine to the session (%Rrc)"), rc);
3529
3530 if ( SUCCEEDED(rc)
3531 && fLaunchingVMProcess
3532 )
3533 {
3534 /* complete the remote session initialization */
3535
3536 /* get the console from the direct session */
3537 ComPtr<IConsole> console;
3538 rc = pSessionControl->GetRemoteConsole(console.asOutParam());
3539 ComAssertComRC(rc);
3540
3541 if (SUCCEEDED(rc) && !console)
3542 {
3543 ComAssert(!!console);
3544 rc = E_FAIL;
3545 }
3546
3547 /* assign machine & console to the remote session */
3548 if (SUCCEEDED(rc))
3549 {
3550 /*
3551 * after LaunchVMProcess(), the first and the only
3552 * entry in remoteControls is that remote session
3553 */
3554 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3555 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
3556 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3557
3558 /* The failure may occur w/o any error info (from RPC), so provide one */
3559 if (FAILED(rc))
3560 setError(VBOX_E_VM_ERROR,
3561 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
3562 }
3563
3564 if (FAILED(rc))
3565 pSessionControl->Uninitialize();
3566 }
3567
3568 /* acquire the lock again */
3569 alock.acquire();
3570
3571 /* Restore the session state */
3572 mData->mSession.mState = origState;
3573 }
3574
3575 // finalize spawning anyway (this is why we don't return on errors above)
3576 if (fLaunchingVMProcess)
3577 {
3578 /* Note that the progress object is finalized later */
3579 /** @todo Consider checking mData->mSession.mProgress for cancellation
3580 * around here. */
3581
3582 /* We don't reset mSession.mPID here because it is necessary for
3583 * SessionMachine::uninit() to reap the child process later. */
3584
3585 if (FAILED(rc))
3586 {
3587 /* Close the remote session, remove the remote control from the list
3588 * and reset session state to Closed (@note keep the code in sync
3589 * with the relevant part in openSession()). */
3590
3591 Assert(mData->mSession.mRemoteControls.size() == 1);
3592 if (mData->mSession.mRemoteControls.size() == 1)
3593 {
3594 ErrorInfoKeeper eik;
3595 mData->mSession.mRemoteControls.front()->Uninitialize();
3596 }
3597
3598 mData->mSession.mRemoteControls.clear();
3599 mData->mSession.mState = SessionState_Unlocked;
3600 }
3601 }
3602 else
3603 {
3604 /* memorize PID of the directly opened session */
3605 if (SUCCEEDED(rc))
3606 mData->mSession.mPID = pid;
3607 }
3608
3609 if (SUCCEEDED(rc))
3610 {
3611 /* memorize the direct session control and cache IUnknown for it */
3612 mData->mSession.mDirectControl = pSessionControl;
3613 mData->mSession.mState = SessionState_Locked;
3614 /* associate the SessionMachine with this Machine */
3615 mData->mSession.mMachine = sessionMachine;
3616
3617 /* request an IUnknown pointer early from the remote party for later
3618 * identity checks (it will be internally cached within mDirectControl
3619 * at least on XPCOM) */
3620 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3621 NOREF(unk);
3622 }
3623
3624 /* Release the lock since SessionMachine::uninit() locks VirtualBox which
3625 * would break the lock order */
3626 alock.release();
3627
3628 /* uninitialize the created session machine on failure */
3629 if (FAILED(rc))
3630 sessionMachine->uninit();
3631
3632 }
3633
3634 if (SUCCEEDED(rc))
3635 {
3636 /*
3637 * tell the client watcher thread to update the set of
3638 * machines that have open sessions
3639 */
3640 mParent->updateClientWatcher();
3641
3642 if (oldState != SessionState_Locked)
3643 /* fire an event */
3644 mParent->onSessionStateChange(getId(), SessionState_Locked);
3645 }
3646
3647 return rc;
3648}
3649
3650/**
3651 * @note Locks objects!
3652 */
3653STDMETHODIMP Machine::LaunchVMProcess(ISession *aSession,
3654 IN_BSTR aFrontend,
3655 IN_BSTR aEnvironment,
3656 IProgress **aProgress)
3657{
3658 CheckComArgStr(aFrontend);
3659 Utf8Str strFrontend(aFrontend);
3660 Utf8Str strEnvironment(aEnvironment);
3661 /* "emergencystop" doesn't need the session, so skip the checks/interface
3662 * retrieval. This code doesn't quite fit in here, but introducing a
3663 * special API method would be even more effort, and would require explicit
3664 * support by every API client. It's better to hide the feature a bit. */
3665 if (strFrontend != "emergencystop")
3666 CheckComArgNotNull(aSession);
3667 CheckComArgOutPointerValid(aProgress);
3668
3669 AutoCaller autoCaller(this);
3670 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3671
3672 HRESULT rc = S_OK;
3673 if (strFrontend.isEmpty())
3674 {
3675 Bstr bstrFrontend;
3676 rc = COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3677 if (FAILED(rc))
3678 return rc;
3679 strFrontend = bstrFrontend;
3680 if (strFrontend.isEmpty())
3681 {
3682 ComPtr<ISystemProperties> systemProperties;
3683 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
3684 if (FAILED(rc))
3685 return rc;
3686 rc = systemProperties->COMGETTER(DefaultFrontend)(bstrFrontend.asOutParam());
3687 if (FAILED(rc))
3688 return rc;
3689 strFrontend = bstrFrontend;
3690 }
3691 /* paranoia - emergencystop is not a valid default */
3692 if (strFrontend == "emergencystop")
3693 strFrontend = Utf8Str::Empty;
3694 }
3695
3696 if (strFrontend != "emergencystop")
3697 {
3698 /* check the session state */
3699 SessionState_T state;
3700 rc = aSession->COMGETTER(State)(&state);
3701 if (FAILED(rc))
3702 return rc;
3703
3704 if (state != SessionState_Unlocked)
3705 return setError(VBOX_E_INVALID_OBJECT_STATE,
3706 tr("The given session is busy"));
3707
3708 /* get the IInternalSessionControl interface */
3709 ComPtr<IInternalSessionControl> control(aSession);
3710 ComAssertMsgRet(!control.isNull(),
3711 ("No IInternalSessionControl interface"),
3712 E_INVALIDARG);
3713
3714 /* get the teleporter enable state for the progress object init. */
3715 BOOL fTeleporterEnabled;
3716 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3717 if (FAILED(rc))
3718 return rc;
3719
3720 /* create a progress object */
3721 ComObjPtr<ProgressProxy> progress;
3722 progress.createObject();
3723 rc = progress->init(mParent,
3724 static_cast<IMachine*>(this),
3725 Bstr(tr("Starting VM")).raw(),
3726 TRUE /* aCancelable */,
3727 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3728 BstrFmt(tr("Creating process for virtual machine \"%s\" (%s)"), mUserData->s.strName.c_str(), strFrontend.c_str()).raw(),
3729 2 /* uFirstOperationWeight */,
3730 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3731
3732 if (SUCCEEDED(rc))
3733 {
3734 rc = launchVMProcess(control, strFrontend, strEnvironment, progress);
3735 if (SUCCEEDED(rc))
3736 {
3737 progress.queryInterfaceTo(aProgress);
3738
3739 /* signal the client watcher thread */
3740 mParent->updateClientWatcher();
3741
3742 /* fire an event */
3743 mParent->onSessionStateChange(getId(), SessionState_Spawning);
3744 }
3745 }
3746 }
3747 else
3748 {
3749 /* no progress object - either instant success or failure */
3750 *aProgress = NULL;
3751
3752 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3753
3754 if (mData->mSession.mState != SessionState_Locked)
3755 return setError(VBOX_E_INVALID_OBJECT_STATE,
3756 tr("The machine '%s' is not locked by a session"),
3757 mUserData->s.strName.c_str());
3758
3759 /* must have a VM process associated - do not kill normal API clients
3760 * with an open session */
3761 if (!Global::IsOnline(mData->mMachineState))
3762 return setError(VBOX_E_INVALID_OBJECT_STATE,
3763 tr("The machine '%s' does not have a VM process"),
3764 mUserData->s.strName.c_str());
3765
3766 /* forcibly terminate the VM process */
3767 if (mData->mSession.mPID != NIL_RTPROCESS)
3768 RTProcTerminate(mData->mSession.mPID);
3769
3770 /* signal the client watcher thread, as most likely the client has
3771 * been terminated */
3772 mParent->updateClientWatcher();
3773 }
3774
3775 return rc;
3776}
3777
3778STDMETHODIMP Machine::SetBootOrder(ULONG aPosition, DeviceType_T aDevice)
3779{
3780 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3781 return setError(E_INVALIDARG,
3782 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3783 aPosition, SchemaDefs::MaxBootPosition);
3784
3785 if (aDevice == DeviceType_USB)
3786 return setError(E_NOTIMPL,
3787 tr("Booting from USB device is currently not supported"));
3788
3789 AutoCaller autoCaller(this);
3790 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3791
3792 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3793
3794 HRESULT rc = checkStateDependency(MutableStateDep);
3795 if (FAILED(rc)) return rc;
3796
3797 setModified(IsModified_MachineData);
3798 mHWData.backup();
3799 mHWData->mBootOrder[aPosition - 1] = aDevice;
3800
3801 return S_OK;
3802}
3803
3804STDMETHODIMP Machine::GetBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3805{
3806 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3807 return setError(E_INVALIDARG,
3808 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3809 aPosition, SchemaDefs::MaxBootPosition);
3810
3811 AutoCaller autoCaller(this);
3812 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3813
3814 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3815
3816 *aDevice = mHWData->mBootOrder[aPosition - 1];
3817
3818 return S_OK;
3819}
3820
3821STDMETHODIMP Machine::AttachDevice(IN_BSTR aControllerName,
3822 LONG aControllerPort,
3823 LONG aDevice,
3824 DeviceType_T aType,
3825 IMedium *aMedium)
3826{
3827 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
3828 aControllerName, aControllerPort, aDevice, aType, aMedium));
3829
3830 CheckComArgStrNotEmptyOrNull(aControllerName);
3831
3832 AutoCaller autoCaller(this);
3833 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3834
3835 // request the host lock first, since might be calling Host methods for getting host drives;
3836 // next, protect the media tree all the while we're in here, as well as our member variables
3837 AutoMultiWriteLock2 alock(mParent->host(), this COMMA_LOCKVAL_SRC_POS);
3838 AutoWriteLock treeLock(&mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3839
3840 HRESULT rc = checkStateDependency(MutableStateDep);
3841 if (FAILED(rc)) return rc;
3842
3843 /// @todo NEWMEDIA implicit machine registration
3844 if (!mData->mRegistered)
3845 return setError(VBOX_E_INVALID_OBJECT_STATE,
3846 tr("Cannot attach storage devices to an unregistered machine"));
3847
3848 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3849
3850 /* Check for an existing controller. */
3851 ComObjPtr<StorageController> ctl;
3852 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
3853 if (FAILED(rc)) return rc;
3854
3855 StorageControllerType_T ctrlType;
3856 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
3857 if (FAILED(rc))
3858 return setError(E_FAIL,
3859 tr("Could not get type of controller '%ls'"),
3860 aControllerName);
3861
3862 bool fSilent = false;
3863 Utf8Str strReconfig;
3864
3865 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
3866 strReconfig = getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
3867 if (FAILED(rc))
3868 return rc;
3869 if ( mData->mMachineState == MachineState_Paused
3870 && strReconfig == "1")
3871 fSilent = true;
3872
3873 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
3874 bool fHotplug = false;
3875 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
3876 fHotplug = true;
3877
3878 if (fHotplug && !isControllerHotplugCapable(ctrlType))
3879 return setError(VBOX_E_INVALID_VM_STATE,
3880 tr("Controller '%ls' does not support hotplugging"),
3881 aControllerName);
3882
3883 // check that the port and device are not out of range
3884 rc = ctl->checkPortAndDeviceValid(aControllerPort, aDevice);
3885 if (FAILED(rc)) return rc;
3886
3887 /* check if the device slot is already busy */
3888 MediumAttachment *pAttachTemp;
3889 if ((pAttachTemp = findAttachment(mMediaData->mAttachments,
3890 aControllerName,
3891 aControllerPort,
3892 aDevice)))
3893 {
3894 Medium *pMedium = pAttachTemp->getMedium();
3895 if (pMedium)
3896 {
3897 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3898 return setError(VBOX_E_OBJECT_IN_USE,
3899 tr("Medium '%s' is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3900 pMedium->getLocationFull().c_str(),
3901 aControllerPort,
3902 aDevice,
3903 aControllerName);
3904 }
3905 else
3906 return setError(VBOX_E_OBJECT_IN_USE,
3907 tr("Device is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3908 aControllerPort, aDevice, aControllerName);
3909 }
3910
3911 ComObjPtr<Medium> medium = static_cast<Medium*>(aMedium);
3912 if (aMedium && medium.isNull())
3913 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3914
3915 AutoCaller mediumCaller(medium);
3916 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3917
3918 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3919
3920 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
3921 && !medium.isNull()
3922 )
3923 return setError(VBOX_E_OBJECT_IN_USE,
3924 tr("Medium '%s' is already attached to this virtual machine"),
3925 medium->getLocationFull().c_str());
3926
3927 if (!medium.isNull())
3928 {
3929 MediumType_T mtype = medium->getType();
3930 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3931 // For DVDs it's not written to the config file, so needs no global config
3932 // version bump. For floppies it's a new attribute "type", which is ignored
3933 // by older VirtualBox version, so needs no global config version bump either.
3934 // For hard disks this type is not accepted.
3935 if (mtype == MediumType_MultiAttach)
3936 {
3937 // This type is new with VirtualBox 4.0 and therefore requires settings
3938 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3939 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3940 // two reasons: The medium type is a property of the media registry tree, which
3941 // can reside in the global config file (for pre-4.0 media); we would therefore
3942 // possibly need to bump the global config version. We don't want to do that though
3943 // because that might make downgrading to pre-4.0 impossible.
3944 // As a result, we can only use these two new types if the medium is NOT in the
3945 // global registry:
3946 const Guid &uuidGlobalRegistry = mParent->getGlobalRegistryId();
3947 if ( medium->isInRegistry(uuidGlobalRegistry)
3948 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3949 )
3950 return setError(VBOX_E_INVALID_OBJECT_STATE,
3951 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3952 "to machines that were created with VirtualBox 4.0 or later"),
3953 medium->getLocationFull().c_str());
3954 }
3955 }
3956
3957 bool fIndirect = false;
3958 if (!medium.isNull())
3959 fIndirect = medium->isReadOnly();
3960 bool associate = true;
3961
3962 do
3963 {
3964 if ( aType == DeviceType_HardDisk
3965 && mMediaData.isBackedUp())
3966 {
3967 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3968
3969 /* check if the medium was attached to the VM before we started
3970 * changing attachments in which case the attachment just needs to
3971 * be restored */
3972 if ((pAttachTemp = findAttachment(oldAtts, medium)))
3973 {
3974 AssertReturn(!fIndirect, E_FAIL);
3975
3976 /* see if it's the same bus/channel/device */
3977 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
3978 {
3979 /* the simplest case: restore the whole attachment
3980 * and return, nothing else to do */
3981 mMediaData->mAttachments.push_back(pAttachTemp);
3982 return S_OK;
3983 }
3984
3985 /* bus/channel/device differ; we need a new attachment object,
3986 * but don't try to associate it again */
3987 associate = false;
3988 break;
3989 }
3990 }
3991
3992 /* go further only if the attachment is to be indirect */
3993 if (!fIndirect)
3994 break;
3995
3996 /* perform the so called smart attachment logic for indirect
3997 * attachments. Note that smart attachment is only applicable to base
3998 * hard disks. */
3999
4000 if (medium->getParent().isNull())
4001 {
4002 /* first, investigate the backup copy of the current hard disk
4003 * attachments to make it possible to re-attach existing diffs to
4004 * another device slot w/o losing their contents */
4005 if (mMediaData.isBackedUp())
4006 {
4007 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
4008
4009 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
4010 uint32_t foundLevel = 0;
4011
4012 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
4013 it != oldAtts.end();
4014 ++it)
4015 {
4016 uint32_t level = 0;
4017 MediumAttachment *pAttach = *it;
4018 ComObjPtr<Medium> pMedium = pAttach->getMedium();
4019 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
4020 if (pMedium.isNull())
4021 continue;
4022
4023 if (pMedium->getBase(&level) == medium)
4024 {
4025 /* skip the hard disk if its currently attached (we
4026 * cannot attach the same hard disk twice) */
4027 if (findAttachment(mMediaData->mAttachments,
4028 pMedium))
4029 continue;
4030
4031 /* matched device, channel and bus (i.e. attached to the
4032 * same place) will win and immediately stop the search;
4033 * otherwise the attachment that has the youngest
4034 * descendant of medium will be used
4035 */
4036 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
4037 {
4038 /* the simplest case: restore the whole attachment
4039 * and return, nothing else to do */
4040 mMediaData->mAttachments.push_back(*it);
4041 return S_OK;
4042 }
4043 else if ( foundIt == oldAtts.end()
4044 || level > foundLevel /* prefer younger */
4045 )
4046 {
4047 foundIt = it;
4048 foundLevel = level;
4049 }
4050 }
4051 }
4052
4053 if (foundIt != oldAtts.end())
4054 {
4055 /* use the previously attached hard disk */
4056 medium = (*foundIt)->getMedium();
4057 mediumCaller.attach(medium);
4058 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4059 mediumLock.attach(medium);
4060 /* not implicit, doesn't require association with this VM */
4061 fIndirect = false;
4062 associate = false;
4063 /* go right to the MediumAttachment creation */
4064 break;
4065 }
4066 }
4067
4068 /* must give up the medium lock and medium tree lock as below we
4069 * go over snapshots, which needs a lock with higher lock order. */
4070 mediumLock.release();
4071 treeLock.release();
4072
4073 /* then, search through snapshots for the best diff in the given
4074 * hard disk's chain to base the new diff on */
4075
4076 ComObjPtr<Medium> base;
4077 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
4078 while (snap)
4079 {
4080 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
4081
4082 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
4083
4084 MediumAttachment *pAttachFound = NULL;
4085 uint32_t foundLevel = 0;
4086
4087 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
4088 it != snapAtts.end();
4089 ++it)
4090 {
4091 MediumAttachment *pAttach = *it;
4092 ComObjPtr<Medium> pMedium = pAttach->getMedium();
4093 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
4094 if (pMedium.isNull())
4095 continue;
4096
4097 uint32_t level = 0;
4098 if (pMedium->getBase(&level) == medium)
4099 {
4100 /* matched device, channel and bus (i.e. attached to the
4101 * same place) will win and immediately stop the search;
4102 * otherwise the attachment that has the youngest
4103 * descendant of medium will be used
4104 */
4105 if ( pAttach->getDevice() == aDevice
4106 && pAttach->getPort() == aControllerPort
4107 && pAttach->getControllerName() == aControllerName
4108 )
4109 {
4110 pAttachFound = pAttach;
4111 break;
4112 }
4113 else if ( !pAttachFound
4114 || level > foundLevel /* prefer younger */
4115 )
4116 {
4117 pAttachFound = pAttach;
4118 foundLevel = level;
4119 }
4120 }
4121 }
4122
4123 if (pAttachFound)
4124 {
4125 base = pAttachFound->getMedium();
4126 break;
4127 }
4128
4129 snap = snap->getParent();
4130 }
4131
4132 /* re-lock medium tree and the medium, as we need it below */
4133 treeLock.acquire();
4134 mediumLock.acquire();
4135
4136 /* found a suitable diff, use it as a base */
4137 if (!base.isNull())
4138 {
4139 medium = base;
4140 mediumCaller.attach(medium);
4141 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4142 mediumLock.attach(medium);
4143 }
4144 }
4145
4146 Utf8Str strFullSnapshotFolder;
4147 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4148
4149 ComObjPtr<Medium> diff;
4150 diff.createObject();
4151 // store this diff in the same registry as the parent
4152 Guid uuidRegistryParent;
4153 if (!medium->getFirstRegistryMachineId(uuidRegistryParent))
4154 {
4155 // parent image has no registry: this can happen if we're attaching a new immutable
4156 // image that has not yet been attached (medium then points to the base and we're
4157 // creating the diff image for the immutable, and the parent is not yet registered);
4158 // put the parent in the machine registry then
4159 mediumLock.release();
4160 treeLock.release();
4161 alock.release();
4162 addMediumToRegistry(medium);
4163 alock.acquire();
4164 treeLock.acquire();
4165 mediumLock.acquire();
4166 medium->getFirstRegistryMachineId(uuidRegistryParent);
4167 }
4168 rc = diff->init(mParent,
4169 medium->getPreferredDiffFormat(),
4170 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
4171 uuidRegistryParent);
4172 if (FAILED(rc)) return rc;
4173
4174 /* Apply the normal locking logic to the entire chain. */
4175 MediumLockList *pMediumLockList(new MediumLockList());
4176 mediumLock.release();
4177 treeLock.release();
4178 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
4179 true /* fMediumLockWrite */,
4180 medium,
4181 *pMediumLockList);
4182 treeLock.acquire();
4183 mediumLock.acquire();
4184 if (SUCCEEDED(rc))
4185 {
4186 mediumLock.release();
4187 treeLock.release();
4188 rc = pMediumLockList->Lock();
4189 treeLock.acquire();
4190 mediumLock.acquire();
4191 if (FAILED(rc))
4192 setError(rc,
4193 tr("Could not lock medium when creating diff '%s'"),
4194 diff->getLocationFull().c_str());
4195 else
4196 {
4197 /* will release the lock before the potentially lengthy
4198 * operation, so protect with the special state */
4199 MachineState_T oldState = mData->mMachineState;
4200 setMachineState(MachineState_SettingUp);
4201
4202 mediumLock.release();
4203 treeLock.release();
4204 alock.release();
4205
4206 rc = medium->createDiffStorage(diff,
4207 MediumVariant_Standard,
4208 pMediumLockList,
4209 NULL /* aProgress */,
4210 true /* aWait */);
4211
4212 alock.acquire();
4213 treeLock.acquire();
4214 mediumLock.acquire();
4215
4216 setMachineState(oldState);
4217 }
4218 }
4219
4220 /* Unlock the media and free the associated memory. */
4221 delete pMediumLockList;
4222
4223 if (FAILED(rc)) return rc;
4224
4225 /* use the created diff for the actual attachment */
4226 medium = diff;
4227 mediumCaller.attach(medium);
4228 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4229 mediumLock.attach(medium);
4230 }
4231 while (0);
4232
4233 ComObjPtr<MediumAttachment> attachment;
4234 attachment.createObject();
4235 rc = attachment->init(this,
4236 medium,
4237 aControllerName,
4238 aControllerPort,
4239 aDevice,
4240 aType,
4241 fIndirect,
4242 false /* fPassthrough */,
4243 false /* fTempEject */,
4244 false /* fNonRotational */,
4245 false /* fDiscard */,
4246 Utf8Str::Empty);
4247 if (FAILED(rc)) return rc;
4248
4249 if (associate && !medium.isNull())
4250 {
4251 // as the last step, associate the medium to the VM
4252 rc = medium->addBackReference(mData->mUuid);
4253 // here we can fail because of Deleting, or being in process of creating a Diff
4254 if (FAILED(rc)) return rc;
4255
4256 mediumLock.release();
4257 treeLock.release();
4258 alock.release();
4259 addMediumToRegistry(medium);
4260 alock.acquire();
4261 treeLock.acquire();
4262 mediumLock.acquire();
4263 }
4264
4265 /* success: finally remember the attachment */
4266 setModified(IsModified_Storage);
4267 mMediaData.backup();
4268 mMediaData->mAttachments.push_back(attachment);
4269
4270 mediumLock.release();
4271 treeLock.release();
4272 alock.release();
4273
4274 if (fHotplug || fSilent)
4275 {
4276 MediumLockList *pMediumLockList(new MediumLockList());
4277
4278 rc = medium->createMediumLockList(true /* fFailIfInaccessible */,
4279 true /* fMediumLockWrite */,
4280 NULL,
4281 *pMediumLockList);
4282 alock.acquire();
4283 if (FAILED(rc))
4284 delete pMediumLockList;
4285 else
4286 {
4287 mData->mSession.mLockedMedia.Unlock();
4288 alock.release();
4289 rc = mData->mSession.mLockedMedia.Insert(attachment, pMediumLockList);
4290 mData->mSession.mLockedMedia.Lock();
4291 alock.acquire();
4292 }
4293 alock.release();
4294
4295 if (SUCCEEDED(rc))
4296 {
4297 rc = onStorageDeviceChange(attachment, FALSE /* aRemove */, fSilent);
4298 /* Remove lock list in case of error. */
4299 if (FAILED(rc))
4300 {
4301 mData->mSession.mLockedMedia.Unlock();
4302 mData->mSession.mLockedMedia.Remove(attachment);
4303 mData->mSession.mLockedMedia.Lock();
4304 }
4305 }
4306 }
4307
4308 mParent->saveModifiedRegistries();
4309
4310 return rc;
4311}
4312
4313STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
4314 LONG aDevice)
4315{
4316 CheckComArgStrNotEmptyOrNull(aControllerName);
4317
4318 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4319 aControllerName, aControllerPort, aDevice));
4320
4321 AutoCaller autoCaller(this);
4322 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4323
4324 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4325
4326 HRESULT rc = checkStateDependency(MutableStateDep);
4327 if (FAILED(rc)) return rc;
4328
4329 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4330
4331 /* Check for an existing controller. */
4332 ComObjPtr<StorageController> ctl;
4333 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
4334 if (FAILED(rc)) return rc;
4335
4336 StorageControllerType_T ctrlType;
4337 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
4338 if (FAILED(rc))
4339 return setError(E_FAIL,
4340 tr("Could not get type of controller '%ls'"),
4341 aControllerName);
4342
4343 bool fSilent = false;
4344 Utf8Str strReconfig;
4345
4346 /* Check whether the flag to allow silent storage attachment reconfiguration is set. */
4347 strReconfig = getExtraData(Utf8Str("VBoxInternal2/SilentReconfigureWhilePaused"));
4348 if (FAILED(rc))
4349 return rc;
4350 if ( mData->mMachineState == MachineState_Paused
4351 && strReconfig == "1")
4352 fSilent = true;
4353
4354 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
4355 bool fHotplug = false;
4356 if (!fSilent && Global::IsOnlineOrTransient(mData->mMachineState))
4357 fHotplug = true;
4358
4359 if (fHotplug && !isControllerHotplugCapable(ctrlType))
4360 return setError(VBOX_E_INVALID_VM_STATE,
4361 tr("Controller '%ls' does not support hotplugging"),
4362 aControllerName);
4363
4364 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4365 aControllerName,
4366 aControllerPort,
4367 aDevice);
4368 if (!pAttach)
4369 return setError(VBOX_E_OBJECT_NOT_FOUND,
4370 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4371 aDevice, aControllerPort, aControllerName);
4372
4373 /*
4374 * The VM has to detach the device before we delete any implicit diffs.
4375 * If this fails we can roll back without loosing data.
4376 */
4377 if (fHotplug || fSilent)
4378 {
4379 alock.release();
4380 rc = onStorageDeviceChange(pAttach, TRUE /* aRemove */, fSilent);
4381 alock.acquire();
4382 }
4383 if (FAILED(rc)) return rc;
4384
4385 /* If we are here everything went well and we can delete the implicit now. */
4386 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */);
4387
4388 alock.release();
4389
4390 mParent->saveModifiedRegistries();
4391
4392 return rc;
4393}
4394
4395STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
4396 LONG aDevice, BOOL aPassthrough)
4397{
4398 CheckComArgStrNotEmptyOrNull(aControllerName);
4399
4400 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aPassthrough=%d\n",
4401 aControllerName, aControllerPort, aDevice, aPassthrough));
4402
4403 AutoCaller autoCaller(this);
4404 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4405
4406 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4407
4408 HRESULT rc = checkStateDependency(MutableStateDep);
4409 if (FAILED(rc)) return rc;
4410
4411 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4412
4413 if (Global::IsOnlineOrTransient(mData->mMachineState))
4414 return setError(VBOX_E_INVALID_VM_STATE,
4415 tr("Invalid machine state: %s"),
4416 Global::stringifyMachineState(mData->mMachineState));
4417
4418 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4419 aControllerName,
4420 aControllerPort,
4421 aDevice);
4422 if (!pAttach)
4423 return setError(VBOX_E_OBJECT_NOT_FOUND,
4424 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4425 aDevice, aControllerPort, aControllerName);
4426
4427
4428 setModified(IsModified_Storage);
4429 mMediaData.backup();
4430
4431 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4432
4433 if (pAttach->getType() != DeviceType_DVD)
4434 return setError(E_INVALIDARG,
4435 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
4436 aDevice, aControllerPort, aControllerName);
4437 pAttach->updatePassthrough(!!aPassthrough);
4438
4439 return S_OK;
4440}
4441
4442STDMETHODIMP Machine::TemporaryEjectDevice(IN_BSTR aControllerName, LONG aControllerPort,
4443 LONG aDevice, BOOL aTemporaryEject)
4444{
4445 CheckComArgStrNotEmptyOrNull(aControllerName);
4446
4447 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aTemporaryEject=%d\n",
4448 aControllerName, aControllerPort, aDevice, aTemporaryEject));
4449
4450 AutoCaller autoCaller(this);
4451 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4452
4453 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4454
4455 HRESULT rc = checkStateDependency(MutableStateDep);
4456 if (FAILED(rc)) return rc;
4457
4458 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4459 aControllerName,
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 '%ls'"),
4465 aDevice, aControllerPort, aControllerName);
4466
4467
4468 setModified(IsModified_Storage);
4469 mMediaData.backup();
4470
4471 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4472
4473 if (pAttach->getType() != DeviceType_DVD)
4474 return setError(E_INVALIDARG,
4475 tr("Setting temporary eject flag rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
4476 aDevice, aControllerPort, aControllerName);
4477 pAttach->updateTempEject(!!aTemporaryEject);
4478
4479 return S_OK;
4480}
4481
4482STDMETHODIMP Machine::NonRotationalDevice(IN_BSTR aControllerName, LONG aControllerPort,
4483 LONG aDevice, BOOL aNonRotational)
4484{
4485 CheckComArgStrNotEmptyOrNull(aControllerName);
4486
4487 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aNonRotational=%d\n",
4488 aControllerName, aControllerPort, aDevice, aNonRotational));
4489
4490 AutoCaller autoCaller(this);
4491 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4492
4493 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4494
4495 HRESULT rc = checkStateDependency(MutableStateDep);
4496 if (FAILED(rc)) return rc;
4497
4498 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4499
4500 if (Global::IsOnlineOrTransient(mData->mMachineState))
4501 return setError(VBOX_E_INVALID_VM_STATE,
4502 tr("Invalid machine state: %s"),
4503 Global::stringifyMachineState(mData->mMachineState));
4504
4505 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4506 aControllerName,
4507 aControllerPort,
4508 aDevice);
4509 if (!pAttach)
4510 return setError(VBOX_E_OBJECT_NOT_FOUND,
4511 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4512 aDevice, aControllerPort, aControllerName);
4513
4514
4515 setModified(IsModified_Storage);
4516 mMediaData.backup();
4517
4518 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4519
4520 if (pAttach->getType() != DeviceType_HardDisk)
4521 return setError(E_INVALIDARG,
4522 tr("Setting the non-rotational medium flag rejected as the device attached to device slot %d on port %d of controller '%ls' is not a hard disk"),
4523 aDevice, aControllerPort, aControllerName);
4524 pAttach->updateNonRotational(!!aNonRotational);
4525
4526 return S_OK;
4527}
4528
4529STDMETHODIMP Machine::SetAutoDiscardForDevice(IN_BSTR aControllerName, LONG aControllerPort,
4530 LONG aDevice, BOOL aDiscard)
4531{
4532 CheckComArgStrNotEmptyOrNull(aControllerName);
4533
4534 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aDiscard=%d\n",
4535 aControllerName, aControllerPort, aDevice, aDiscard));
4536
4537 AutoCaller autoCaller(this);
4538 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4539
4540 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4541
4542 HRESULT rc = checkStateDependency(MutableStateDep);
4543 if (FAILED(rc)) return rc;
4544
4545 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4546
4547 if (Global::IsOnlineOrTransient(mData->mMachineState))
4548 return setError(VBOX_E_INVALID_VM_STATE,
4549 tr("Invalid machine state: %s"),
4550 Global::stringifyMachineState(mData->mMachineState));
4551
4552 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4553 aControllerName,
4554 aControllerPort,
4555 aDevice);
4556 if (!pAttach)
4557 return setError(VBOX_E_OBJECT_NOT_FOUND,
4558 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4559 aDevice, aControllerPort, aControllerName);
4560
4561
4562 setModified(IsModified_Storage);
4563 mMediaData.backup();
4564
4565 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4566
4567 if (pAttach->getType() != DeviceType_HardDisk)
4568 return setError(E_INVALIDARG,
4569 tr("Setting the discard medium flag rejected as the device attached to device slot %d on port %d of controller '%ls' is not a hard disk"),
4570 aDevice, aControllerPort, aControllerName);
4571 pAttach->updateDiscard(!!aDiscard);
4572
4573 return S_OK;
4574}
4575
4576STDMETHODIMP Machine::SetNoBandwidthGroupForDevice(IN_BSTR aControllerName, LONG aControllerPort,
4577 LONG aDevice)
4578{
4579 int rc = S_OK;
4580 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4581 aControllerName, aControllerPort, aDevice));
4582
4583 rc = SetBandwidthGroupForDevice(aControllerName, aControllerPort, aDevice, NULL);
4584
4585 return rc;
4586}
4587
4588STDMETHODIMP Machine::SetBandwidthGroupForDevice(IN_BSTR aControllerName, LONG aControllerPort,
4589 LONG aDevice, IBandwidthGroup *aBandwidthGroup)
4590{
4591 CheckComArgStrNotEmptyOrNull(aControllerName);
4592
4593 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4594 aControllerName, aControllerPort, aDevice));
4595
4596 AutoCaller autoCaller(this);
4597 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4598
4599 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4600
4601 HRESULT rc = checkStateDependency(MutableStateDep);
4602 if (FAILED(rc)) return rc;
4603
4604 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
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 = findAttachment(mMediaData->mAttachments,
4612 aControllerName,
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 '%ls'"),
4618 aDevice, aControllerPort, aControllerName);
4619
4620
4621 setModified(IsModified_Storage);
4622 mMediaData.backup();
4623
4624 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(aBandwidthGroup);
4625 if (aBandwidthGroup && group.isNull())
4626 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
4627
4628 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4629
4630 const Utf8Str strBandwidthGroupOld = pAttach->getBandwidthGroup();
4631 if (strBandwidthGroupOld.isNotEmpty())
4632 {
4633 /* Get the bandwidth group object and release it - this must not fail. */
4634 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
4635 rc = getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
4636 Assert(SUCCEEDED(rc));
4637
4638 pBandwidthGroupOld->release();
4639 pAttach->updateBandwidthGroup(Utf8Str::Empty);
4640 }
4641
4642 if (!group.isNull())
4643 {
4644 group->reference();
4645 pAttach->updateBandwidthGroup(group->getName());
4646 }
4647
4648 return S_OK;
4649}
4650
4651STDMETHODIMP Machine::AttachDeviceWithoutMedium(IN_BSTR aControllerName,
4652 LONG aControllerPort,
4653 LONG aDevice,
4654 DeviceType_T aType)
4655{
4656 HRESULT rc = S_OK;
4657
4658 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
4659 aControllerName, aControllerPort, aDevice, aType));
4660
4661 rc = AttachDevice(aControllerName, aControllerPort, aDevice, aType, NULL);
4662
4663 return rc;
4664}
4665
4666
4667
4668STDMETHODIMP Machine::UnmountMedium(IN_BSTR aControllerName,
4669 LONG aControllerPort,
4670 LONG aDevice,
4671 BOOL aForce)
4672{
4673 int rc = S_OK;
4674 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d",
4675 aControllerName, aControllerPort, aForce));
4676
4677 rc = MountMedium(aControllerName, aControllerPort, aDevice, NULL, aForce);
4678
4679 return rc;
4680}
4681
4682STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
4683 LONG aControllerPort,
4684 LONG aDevice,
4685 IMedium *aMedium,
4686 BOOL aForce)
4687{
4688 int rc = S_OK;
4689 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aForce=%d\n",
4690 aControllerName, aControllerPort, aDevice, aForce));
4691
4692 CheckComArgStrNotEmptyOrNull(aControllerName);
4693
4694 AutoCaller autoCaller(this);
4695 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4696
4697 // request the host lock first, since might be calling Host methods for getting host drives;
4698 // next, protect the media tree all the while we're in here, as well as our member variables
4699 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
4700 this->lockHandle(),
4701 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4702
4703 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4704 aControllerName,
4705 aControllerPort,
4706 aDevice);
4707 if (pAttach.isNull())
4708 return setError(VBOX_E_OBJECT_NOT_FOUND,
4709 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
4710 aDevice, aControllerPort, aControllerName);
4711
4712 /* Remember previously mounted medium. The medium before taking the
4713 * backup is not necessarily the same thing. */
4714 ComObjPtr<Medium> oldmedium;
4715 oldmedium = pAttach->getMedium();
4716
4717 ComObjPtr<Medium> pMedium = static_cast<Medium*>(aMedium);
4718 if (aMedium && pMedium.isNull())
4719 return setError(E_INVALIDARG, "The given medium pointer is invalid");
4720
4721 AutoCaller mediumCaller(pMedium);
4722 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4723
4724 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4725 if (pMedium)
4726 {
4727 DeviceType_T mediumType = pAttach->getType();
4728 switch (mediumType)
4729 {
4730 case DeviceType_DVD:
4731 case DeviceType_Floppy:
4732 break;
4733
4734 default:
4735 return setError(VBOX_E_INVALID_OBJECT_STATE,
4736 tr("The device at port %d, device %d of controller '%ls' of this virtual machine is not removeable"),
4737 aControllerPort,
4738 aDevice,
4739 aControllerName);
4740 }
4741 }
4742
4743 setModified(IsModified_Storage);
4744 mMediaData.backup();
4745
4746 {
4747 // The backup operation makes the pAttach reference point to the
4748 // old settings. Re-get the correct reference.
4749 pAttach = findAttachment(mMediaData->mAttachments,
4750 aControllerName,
4751 aControllerPort,
4752 aDevice);
4753 if (!oldmedium.isNull())
4754 oldmedium->removeBackReference(mData->mUuid);
4755 if (!pMedium.isNull())
4756 {
4757 pMedium->addBackReference(mData->mUuid);
4758
4759 mediumLock.release();
4760 multiLock.release();
4761 addMediumToRegistry(pMedium);
4762 multiLock.acquire();
4763 mediumLock.acquire();
4764 }
4765
4766 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4767 pAttach->updateMedium(pMedium);
4768 }
4769
4770 setModified(IsModified_Storage);
4771
4772 mediumLock.release();
4773 multiLock.release();
4774 rc = onMediumChange(pAttach, aForce);
4775 multiLock.acquire();
4776 mediumLock.acquire();
4777
4778 /* On error roll back this change only. */
4779 if (FAILED(rc))
4780 {
4781 if (!pMedium.isNull())
4782 pMedium->removeBackReference(mData->mUuid);
4783 pAttach = findAttachment(mMediaData->mAttachments,
4784 aControllerName,
4785 aControllerPort,
4786 aDevice);
4787 /* If the attachment is gone in the meantime, bail out. */
4788 if (pAttach.isNull())
4789 return rc;
4790 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4791 if (!oldmedium.isNull())
4792 oldmedium->addBackReference(mData->mUuid);
4793 pAttach->updateMedium(oldmedium);
4794 }
4795
4796 mediumLock.release();
4797 multiLock.release();
4798
4799 mParent->saveModifiedRegistries();
4800
4801 return rc;
4802}
4803
4804STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
4805 LONG aControllerPort,
4806 LONG aDevice,
4807 IMedium **aMedium)
4808{
4809 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4810 aControllerName, aControllerPort, aDevice));
4811
4812 CheckComArgStrNotEmptyOrNull(aControllerName);
4813 CheckComArgOutPointerValid(aMedium);
4814
4815 AutoCaller autoCaller(this);
4816 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4817
4818 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4819
4820 *aMedium = NULL;
4821
4822 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4823 aControllerName,
4824 aControllerPort,
4825 aDevice);
4826 if (pAttach.isNull())
4827 return setError(VBOX_E_OBJECT_NOT_FOUND,
4828 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4829 aDevice, aControllerPort, aControllerName);
4830
4831 pAttach->getMedium().queryInterfaceTo(aMedium);
4832
4833 return S_OK;
4834}
4835
4836STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
4837{
4838 CheckComArgOutPointerValid(port);
4839 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
4840
4841 AutoCaller autoCaller(this);
4842 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4843
4844 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4845
4846 mSerialPorts[slot].queryInterfaceTo(port);
4847
4848 return S_OK;
4849}
4850
4851STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
4852{
4853 CheckComArgOutPointerValid(port);
4854 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
4855
4856 AutoCaller autoCaller(this);
4857 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4858
4859 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4860
4861 mParallelPorts[slot].queryInterfaceTo(port);
4862
4863 return S_OK;
4864}
4865
4866STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
4867{
4868 CheckComArgOutPointerValid(adapter);
4869 /* Do not assert if slot is out of range, just return the advertised
4870 status. testdriver/vbox.py triggers this in logVmInfo. */
4871 if (slot >= mNetworkAdapters.size())
4872 return setError(E_INVALIDARG,
4873 tr("No network adapter in slot %RU32 (total %RU32 adapters)"),
4874 slot, mNetworkAdapters.size());
4875
4876 AutoCaller autoCaller(this);
4877 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4878
4879 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4880
4881 mNetworkAdapters[slot].queryInterfaceTo(adapter);
4882
4883 return S_OK;
4884}
4885
4886STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
4887{
4888 CheckComArgOutSafeArrayPointerValid(aKeys);
4889
4890 AutoCaller autoCaller(this);
4891 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4892
4893 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4894
4895 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
4896 int i = 0;
4897 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4898 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4899 ++it, ++i)
4900 {
4901 const Utf8Str &strKey = it->first;
4902 strKey.cloneTo(&saKeys[i]);
4903 }
4904 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
4905
4906 return S_OK;
4907 }
4908
4909 /**
4910 * @note Locks this object for reading.
4911 */
4912STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
4913 BSTR *aValue)
4914{
4915 CheckComArgStrNotEmptyOrNull(aKey);
4916 CheckComArgOutPointerValid(aValue);
4917
4918 AutoCaller autoCaller(this);
4919 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4920
4921 /* start with nothing found */
4922 Bstr bstrResult("");
4923
4924 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4925
4926 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
4927 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4928 // found:
4929 bstrResult = it->second; // source is a Utf8Str
4930
4931 /* return the result to caller (may be empty) */
4932 bstrResult.cloneTo(aValue);
4933
4934 return S_OK;
4935}
4936
4937 /**
4938 * @note Locks mParent for writing + this object for writing.
4939 */
4940STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
4941{
4942 CheckComArgStrNotEmptyOrNull(aKey);
4943
4944 AutoCaller autoCaller(this);
4945 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4946
4947 Utf8Str strKey(aKey);
4948 Utf8Str strValue(aValue);
4949 Utf8Str strOldValue; // empty
4950
4951 // locking note: we only hold the read lock briefly to look up the old value,
4952 // then release it and call the onExtraCanChange callbacks. There is a small
4953 // chance of a race insofar as the callback might be called twice if two callers
4954 // change the same key at the same time, but that's a much better solution
4955 // than the deadlock we had here before. The actual changing of the extradata
4956 // is then performed under the write lock and race-free.
4957
4958 // look up the old value first; if nothing has changed then we need not do anything
4959 {
4960 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
4961 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
4962 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4963 strOldValue = it->second;
4964 }
4965
4966 bool fChanged;
4967 if ((fChanged = (strOldValue != strValue)))
4968 {
4969 // ask for permission from all listeners outside the locks;
4970 // onExtraDataCanChange() only briefly requests the VirtualBox
4971 // lock to copy the list of callbacks to invoke
4972 Bstr error;
4973 Bstr bstrValue(aValue);
4974
4975 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue.raw(), error))
4976 {
4977 const char *sep = error.isEmpty() ? "" : ": ";
4978 CBSTR err = error.raw();
4979 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
4980 sep, err));
4981 return setError(E_ACCESSDENIED,
4982 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
4983 aKey,
4984 bstrValue.raw(),
4985 sep,
4986 err);
4987 }
4988
4989 // data is changing and change not vetoed: then write it out under the lock
4990 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4991
4992 if (isSnapshotMachine())
4993 {
4994 HRESULT rc = checkStateDependency(MutableStateDep);
4995 if (FAILED(rc)) return rc;
4996 }
4997
4998 if (strValue.isEmpty())
4999 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
5000 else
5001 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
5002 // creates a new key if needed
5003
5004 bool fNeedsGlobalSaveSettings = false;
5005 saveSettings(&fNeedsGlobalSaveSettings);
5006
5007 if (fNeedsGlobalSaveSettings)
5008 {
5009 // save the global settings; for that we should hold only the VirtualBox lock
5010 alock.release();
5011 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
5012 mParent->saveSettings();
5013 }
5014 }
5015
5016 // fire notification outside the lock
5017 if (fChanged)
5018 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
5019
5020 return S_OK;
5021}
5022
5023STDMETHODIMP Machine::SaveSettings()
5024{
5025 AutoCaller autoCaller(this);
5026 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5027
5028 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
5029
5030 /* when there was auto-conversion, we want to save the file even if
5031 * the VM is saved */
5032 HRESULT rc = checkStateDependency(MutableOrSavedStateDep);
5033 if (FAILED(rc)) return rc;
5034
5035 /* the settings file path may never be null */
5036 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
5037
5038 /* save all VM data excluding snapshots */
5039 bool fNeedsGlobalSaveSettings = false;
5040 rc = saveSettings(&fNeedsGlobalSaveSettings);
5041 mlock.release();
5042
5043 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
5044 {
5045 // save the global settings; for that we should hold only the VirtualBox lock
5046 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
5047 rc = mParent->saveSettings();
5048 }
5049
5050 return rc;
5051}
5052
5053STDMETHODIMP Machine::DiscardSettings()
5054{
5055 AutoCaller autoCaller(this);
5056 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5057
5058 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5059
5060 HRESULT rc = checkStateDependency(MutableStateDep);
5061 if (FAILED(rc)) return rc;
5062
5063 /*
5064 * during this rollback, the session will be notified if data has
5065 * been actually changed
5066 */
5067 rollback(true /* aNotify */);
5068
5069 return S_OK;
5070}
5071
5072/** @note Locks objects! */
5073STDMETHODIMP Machine::Unregister(CleanupMode_T cleanupMode,
5074 ComSafeArrayOut(IMedium*, aMedia))
5075{
5076 // use AutoLimitedCaller because this call is valid on inaccessible machines as well
5077 AutoLimitedCaller autoCaller(this);
5078 AssertComRCReturnRC(autoCaller.rc());
5079
5080 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5081
5082 Guid id(getId());
5083
5084 if (mData->mSession.mState != SessionState_Unlocked)
5085 return setError(VBOX_E_INVALID_OBJECT_STATE,
5086 tr("Cannot unregister the machine '%s' while it is locked"),
5087 mUserData->s.strName.c_str());
5088
5089 // wait for state dependents to drop to zero
5090 ensureNoStateDependencies();
5091
5092 if (!mData->mAccessible)
5093 {
5094 // inaccessible maschines can only be unregistered; uninitialize ourselves
5095 // here because currently there may be no unregistered that are inaccessible
5096 // (this state combination is not supported). Note releasing the caller and
5097 // leaving the lock before calling uninit()
5098 alock.release();
5099 autoCaller.release();
5100
5101 uninit();
5102
5103 mParent->unregisterMachine(this, id);
5104 // calls VirtualBox::saveSettings()
5105
5106 return S_OK;
5107 }
5108
5109 HRESULT rc = S_OK;
5110
5111 // discard saved state
5112 if (mData->mMachineState == MachineState_Saved)
5113 {
5114 // add the saved state file to the list of files the caller should delete
5115 Assert(!mSSData->strStateFilePath.isEmpty());
5116 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
5117
5118 mSSData->strStateFilePath.setNull();
5119
5120 // unconditionally set the machine state to powered off, we now
5121 // know no session has locked the machine
5122 mData->mMachineState = MachineState_PoweredOff;
5123 }
5124
5125 size_t cSnapshots = 0;
5126 if (mData->mFirstSnapshot)
5127 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
5128 if (cSnapshots && cleanupMode == CleanupMode_UnregisterOnly)
5129 // fail now before we start detaching media
5130 return setError(VBOX_E_INVALID_OBJECT_STATE,
5131 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
5132 mUserData->s.strName.c_str(), cSnapshots);
5133
5134 // This list collects the medium objects from all medium attachments
5135 // which we will detach from the machine and its snapshots, in a specific
5136 // order which allows for closing all media without getting "media in use"
5137 // errors, simply by going through the list from the front to the back:
5138 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
5139 // and must be closed before the parent media from the snapshots, or closing the parents
5140 // will fail because they still have children);
5141 // 2) media from the youngest snapshots followed by those from the parent snapshots until
5142 // the root ("first") snapshot of the machine.
5143 MediaList llMedia;
5144
5145 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
5146 && mMediaData->mAttachments.size()
5147 )
5148 {
5149 // we have media attachments: detach them all and add the Medium objects to our list
5150 if (cleanupMode != CleanupMode_UnregisterOnly)
5151 detachAllMedia(alock, NULL /* pSnapshot */, cleanupMode, llMedia);
5152 else
5153 return setError(VBOX_E_INVALID_OBJECT_STATE,
5154 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
5155 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
5156 }
5157
5158 if (cSnapshots)
5159 {
5160 // autoCleanup must be true here, or we would have failed above
5161
5162 // add the media from the medium attachments of the snapshots to llMedia
5163 // as well, after the "main" machine media; Snapshot::uninitRecursively()
5164 // calls Machine::detachAllMedia() for the snapshot machine, recursing
5165 // into the children first
5166
5167 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
5168 MachineState_T oldState = mData->mMachineState;
5169 mData->mMachineState = MachineState_DeletingSnapshot;
5170
5171 // make a copy of the first snapshot so the refcount does not drop to 0
5172 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
5173 // because of the AutoCaller voodoo)
5174 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
5175
5176 // GO!
5177 pFirstSnapshot->uninitRecursively(alock, cleanupMode, llMedia, mData->llFilesToDelete);
5178
5179 mData->mMachineState = oldState;
5180 }
5181
5182 if (FAILED(rc))
5183 {
5184 rollbackMedia();
5185 return rc;
5186 }
5187
5188 // commit all the media changes made above
5189 commitMedia();
5190
5191 mData->mRegistered = false;
5192
5193 // machine lock no longer needed
5194 alock.release();
5195
5196 // return media to caller
5197 SafeIfaceArray<IMedium> sfaMedia(llMedia);
5198 sfaMedia.detachTo(ComSafeArrayOutArg(aMedia));
5199
5200 mParent->unregisterMachine(this, id);
5201 // calls VirtualBox::saveSettings() and VirtualBox::saveModifiedRegistries()
5202
5203 return S_OK;
5204}
5205
5206struct Machine::DeleteTask
5207{
5208 ComObjPtr<Machine> pMachine;
5209 RTCList<ComPtr<IMedium> > llMediums;
5210 StringsList llFilesToDelete;
5211 ComObjPtr<Progress> pProgress;
5212};
5213
5214STDMETHODIMP Machine::DeleteConfig(ComSafeArrayIn(IMedium*, aMedia), IProgress **aProgress)
5215{
5216 LogFlowFuncEnter();
5217
5218 AutoCaller autoCaller(this);
5219 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5220
5221 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5222
5223 HRESULT rc = checkStateDependency(MutableStateDep);
5224 if (FAILED(rc)) return rc;
5225
5226 if (mData->mRegistered)
5227 return setError(VBOX_E_INVALID_VM_STATE,
5228 tr("Cannot delete settings of a registered machine"));
5229
5230 DeleteTask *pTask = new DeleteTask;
5231 pTask->pMachine = this;
5232 com::SafeIfaceArray<IMedium> sfaMedia(ComSafeArrayInArg(aMedia));
5233
5234 // collect files to delete
5235 pTask->llFilesToDelete = mData->llFilesToDelete; // saved states pushed here by Unregister()
5236
5237 for (size_t i = 0; i < sfaMedia.size(); ++i)
5238 {
5239 IMedium *pIMedium(sfaMedia[i]);
5240 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
5241 if (pMedium.isNull())
5242 return setError(E_INVALIDARG, "The given medium pointer with index %d is invalid", i);
5243 SafeArray<BSTR> ids;
5244 rc = pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(ids));
5245 if (FAILED(rc)) return rc;
5246 /* At this point the medium should not have any back references
5247 * anymore. If it has it is attached to another VM and *must* not
5248 * deleted. */
5249 if (ids.size() < 1)
5250 pTask->llMediums.append(pMedium);
5251 }
5252 if (mData->pMachineConfigFile->fileExists())
5253 pTask->llFilesToDelete.push_back(mData->m_strConfigFileFull);
5254
5255 pTask->pProgress.createObject();
5256 pTask->pProgress->init(getVirtualBox(),
5257 static_cast<IMachine*>(this) /* aInitiator */,
5258 Bstr(tr("Deleting files")).raw(),
5259 true /* fCancellable */,
5260 pTask->llFilesToDelete.size() + pTask->llMediums.size() + 1, // cOperations
5261 BstrFmt(tr("Deleting '%s'"), pTask->llFilesToDelete.front().c_str()).raw());
5262
5263 int vrc = RTThreadCreate(NULL,
5264 Machine::deleteThread,
5265 (void*)pTask,
5266 0,
5267 RTTHREADTYPE_MAIN_WORKER,
5268 0,
5269 "MachineDelete");
5270
5271 pTask->pProgress.queryInterfaceTo(aProgress);
5272
5273 if (RT_FAILURE(vrc))
5274 {
5275 delete pTask;
5276 return setError(E_FAIL, "Could not create MachineDelete thread (%Rrc)", vrc);
5277 }
5278
5279 LogFlowFuncLeave();
5280
5281 return S_OK;
5282}
5283
5284/**
5285 * Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
5286 * calls Machine::deleteTaskWorker() on the actual machine object.
5287 * @param Thread
5288 * @param pvUser
5289 * @return
5290 */
5291/*static*/
5292DECLCALLBACK(int) Machine::deleteThread(RTTHREAD Thread, void *pvUser)
5293{
5294 LogFlowFuncEnter();
5295
5296 DeleteTask *pTask = (DeleteTask*)pvUser;
5297 Assert(pTask);
5298 Assert(pTask->pMachine);
5299 Assert(pTask->pProgress);
5300
5301 HRESULT rc = pTask->pMachine->deleteTaskWorker(*pTask);
5302 pTask->pProgress->notifyComplete(rc);
5303
5304 delete pTask;
5305
5306 LogFlowFuncLeave();
5307
5308 NOREF(Thread);
5309
5310 return VINF_SUCCESS;
5311}
5312
5313/**
5314 * Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
5315 * @param task
5316 * @return
5317 */
5318HRESULT Machine::deleteTaskWorker(DeleteTask &task)
5319{
5320 AutoCaller autoCaller(this);
5321 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5322
5323 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5324
5325 HRESULT rc = S_OK;
5326
5327 try
5328 {
5329 ULONG uLogHistoryCount = 3;
5330 ComPtr<ISystemProperties> systemProperties;
5331 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
5332 if (FAILED(rc)) throw rc;
5333
5334 if (!systemProperties.isNull())
5335 {
5336 rc = systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
5337 if (FAILED(rc)) throw rc;
5338 }
5339
5340 MachineState_T oldState = mData->mMachineState;
5341 setMachineState(MachineState_SettingUp);
5342 alock.release();
5343 for (size_t i = 0; i < task.llMediums.size(); ++i)
5344 {
5345 ComObjPtr<Medium> pMedium = (Medium*)(IMedium*)task.llMediums.at(i);
5346 {
5347 AutoCaller mac(pMedium);
5348 if (FAILED(mac.rc())) throw mac.rc();
5349 Utf8Str strLocation = pMedium->getLocationFull();
5350 rc = task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), strLocation.c_str()).raw(), 1);
5351 if (FAILED(rc)) throw rc;
5352 LogFunc(("Deleting file %s\n", strLocation.c_str()));
5353 }
5354 ComPtr<IProgress> pProgress2;
5355 rc = pMedium->DeleteStorage(pProgress2.asOutParam());
5356 if (FAILED(rc)) throw rc;
5357 rc = task.pProgress->WaitForAsyncProgressCompletion(pProgress2);
5358 if (FAILED(rc)) throw rc;
5359 /* Check the result of the asynchrony process. */
5360 LONG iRc;
5361 rc = pProgress2->COMGETTER(ResultCode)(&iRc);
5362 if (FAILED(rc)) throw rc;
5363 /* If the thread of the progress object has an error, then
5364 * retrieve the error info from there, or it'll be lost. */
5365 if (FAILED(iRc))
5366 throw setError(ProgressErrorInfo(pProgress2));
5367 }
5368 setMachineState(oldState);
5369 alock.acquire();
5370
5371 // delete the files pushed on the task list by Machine::Delete()
5372 // (this includes saved states of the machine and snapshots and
5373 // medium storage files from the IMedium list passed in, and the
5374 // machine XML file)
5375 StringsList::const_iterator it = task.llFilesToDelete.begin();
5376 while (it != task.llFilesToDelete.end())
5377 {
5378 const Utf8Str &strFile = *it;
5379 LogFunc(("Deleting file %s\n", strFile.c_str()));
5380 int vrc = RTFileDelete(strFile.c_str());
5381 if (RT_FAILURE(vrc))
5382 throw setError(VBOX_E_IPRT_ERROR,
5383 tr("Could not delete file '%s' (%Rrc)"), strFile.c_str(), vrc);
5384
5385 ++it;
5386 if (it == task.llFilesToDelete.end())
5387 {
5388 rc = task.pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
5389 if (FAILED(rc)) throw rc;
5390 break;
5391 }
5392
5393 rc = task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
5394 if (FAILED(rc)) throw rc;
5395 }
5396
5397 /* delete the settings only when the file actually exists */
5398 if (mData->pMachineConfigFile->fileExists())
5399 {
5400 /* Delete any backup or uncommitted XML files. Ignore failures.
5401 See the fSafe parameter of xml::XmlFileWriter::write for details. */
5402 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
5403 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
5404 RTFileDelete(otherXml.c_str());
5405 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
5406 RTFileDelete(otherXml.c_str());
5407
5408 /* delete the Logs folder, nothing important should be left
5409 * there (we don't check for errors because the user might have
5410 * some private files there that we don't want to delete) */
5411 Utf8Str logFolder;
5412 getLogFolder(logFolder);
5413 Assert(logFolder.length());
5414 if (RTDirExists(logFolder.c_str()))
5415 {
5416 /* Delete all VBox.log[.N] files from the Logs folder
5417 * (this must be in sync with the rotation logic in
5418 * Console::powerUpThread()). Also, delete the VBox.png[.N]
5419 * files that may have been created by the GUI. */
5420 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
5421 logFolder.c_str(), RTPATH_DELIMITER);
5422 RTFileDelete(log.c_str());
5423 log = Utf8StrFmt("%s%cVBox.png",
5424 logFolder.c_str(), RTPATH_DELIMITER);
5425 RTFileDelete(log.c_str());
5426 for (int i = uLogHistoryCount; i > 0; i--)
5427 {
5428 log = Utf8StrFmt("%s%cVBox.log.%d",
5429 logFolder.c_str(), RTPATH_DELIMITER, i);
5430 RTFileDelete(log.c_str());
5431 log = Utf8StrFmt("%s%cVBox.png.%d",
5432 logFolder.c_str(), RTPATH_DELIMITER, i);
5433 RTFileDelete(log.c_str());
5434 }
5435
5436 RTDirRemove(logFolder.c_str());
5437 }
5438
5439 /* delete the Snapshots folder, nothing important should be left
5440 * there (we don't check for errors because the user might have
5441 * some private files there that we don't want to delete) */
5442 Utf8Str strFullSnapshotFolder;
5443 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
5444 Assert(!strFullSnapshotFolder.isEmpty());
5445 if (RTDirExists(strFullSnapshotFolder.c_str()))
5446 RTDirRemove(strFullSnapshotFolder.c_str());
5447
5448 // delete the directory that contains the settings file, but only
5449 // if it matches the VM name
5450 Utf8Str settingsDir;
5451 if (isInOwnDir(&settingsDir))
5452 RTDirRemove(settingsDir.c_str());
5453 }
5454
5455 alock.release();
5456
5457 mParent->saveModifiedRegistries();
5458 }
5459 catch (HRESULT aRC) { rc = aRC; }
5460
5461 return rc;
5462}
5463
5464STDMETHODIMP Machine::FindSnapshot(IN_BSTR aNameOrId, ISnapshot **aSnapshot)
5465{
5466 CheckComArgOutPointerValid(aSnapshot);
5467
5468 AutoCaller autoCaller(this);
5469 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5470
5471 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5472
5473 ComObjPtr<Snapshot> pSnapshot;
5474 HRESULT rc;
5475
5476 if (!aNameOrId || !*aNameOrId)
5477 // null case (caller wants root snapshot): findSnapshotById() handles this
5478 rc = findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
5479 else
5480 {
5481 Guid uuid(aNameOrId);
5482 if (uuid.isValid())
5483 rc = findSnapshotById(uuid, pSnapshot, true /* aSetError */);
5484 else
5485 rc = findSnapshotByName(Utf8Str(aNameOrId), pSnapshot, true /* aSetError */);
5486 }
5487 pSnapshot.queryInterfaceTo(aSnapshot);
5488
5489 return rc;
5490}
5491
5492STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
5493{
5494 CheckComArgStrNotEmptyOrNull(aName);
5495 CheckComArgStrNotEmptyOrNull(aHostPath);
5496
5497 AutoCaller autoCaller(this);
5498 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5499
5500 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5501
5502 HRESULT rc = checkStateDependency(MutableStateDep);
5503 if (FAILED(rc)) return rc;
5504
5505 Utf8Str strName(aName);
5506
5507 ComObjPtr<SharedFolder> sharedFolder;
5508 rc = findSharedFolder(strName, sharedFolder, false /* aSetError */);
5509 if (SUCCEEDED(rc))
5510 return setError(VBOX_E_OBJECT_IN_USE,
5511 tr("Shared folder named '%s' already exists"),
5512 strName.c_str());
5513
5514 sharedFolder.createObject();
5515 rc = sharedFolder->init(getMachine(),
5516 strName,
5517 aHostPath,
5518 !!aWritable,
5519 !!aAutoMount,
5520 true /* fFailOnError */);
5521 if (FAILED(rc)) return rc;
5522
5523 setModified(IsModified_SharedFolders);
5524 mHWData.backup();
5525 mHWData->mSharedFolders.push_back(sharedFolder);
5526
5527 /* inform the direct session if any */
5528 alock.release();
5529 onSharedFolderChange();
5530
5531 return S_OK;
5532}
5533
5534STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
5535{
5536 CheckComArgStrNotEmptyOrNull(aName);
5537
5538 AutoCaller autoCaller(this);
5539 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5540
5541 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5542
5543 HRESULT rc = checkStateDependency(MutableStateDep);
5544 if (FAILED(rc)) return rc;
5545
5546 ComObjPtr<SharedFolder> sharedFolder;
5547 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
5548 if (FAILED(rc)) return rc;
5549
5550 setModified(IsModified_SharedFolders);
5551 mHWData.backup();
5552 mHWData->mSharedFolders.remove(sharedFolder);
5553
5554 /* inform the direct session if any */
5555 alock.release();
5556 onSharedFolderChange();
5557
5558 return S_OK;
5559}
5560
5561STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
5562{
5563 CheckComArgOutPointerValid(aCanShow);
5564
5565 /* start with No */
5566 *aCanShow = FALSE;
5567
5568 AutoCaller autoCaller(this);
5569 AssertComRCReturnRC(autoCaller.rc());
5570
5571 ComPtr<IInternalSessionControl> directControl;
5572 {
5573 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5574
5575 if (mData->mSession.mState != SessionState_Locked)
5576 return setError(VBOX_E_INVALID_VM_STATE,
5577 tr("Machine is not locked for session (session state: %s)"),
5578 Global::stringifySessionState(mData->mSession.mState));
5579
5580 directControl = mData->mSession.mDirectControl;
5581 }
5582
5583 /* ignore calls made after #OnSessionEnd() is called */
5584 if (!directControl)
5585 return S_OK;
5586
5587 LONG64 dummy;
5588 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
5589}
5590
5591STDMETHODIMP Machine::ShowConsoleWindow(LONG64 *aWinId)
5592{
5593 CheckComArgOutPointerValid(aWinId);
5594
5595 AutoCaller autoCaller(this);
5596 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5597
5598 ComPtr<IInternalSessionControl> directControl;
5599 {
5600 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5601
5602 if (mData->mSession.mState != SessionState_Locked)
5603 return setError(E_FAIL,
5604 tr("Machine is not locked for session (session state: %s)"),
5605 Global::stringifySessionState(mData->mSession.mState));
5606
5607 directControl = mData->mSession.mDirectControl;
5608 }
5609
5610 /* ignore calls made after #OnSessionEnd() is called */
5611 if (!directControl)
5612 return S_OK;
5613
5614 BOOL dummy;
5615 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
5616}
5617
5618#ifdef VBOX_WITH_GUEST_PROPS
5619/**
5620 * Look up a guest property in VBoxSVC's internal structures.
5621 */
5622HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
5623 BSTR *aValue,
5624 LONG64 *aTimestamp,
5625 BSTR *aFlags) const
5626{
5627 using namespace guestProp;
5628
5629 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5630 Utf8Str strName(aName);
5631 HWData::GuestPropertyMap::const_iterator it =
5632 mHWData->mGuestProperties.find(strName);
5633
5634 if (it != mHWData->mGuestProperties.end())
5635 {
5636 char szFlags[MAX_FLAGS_LEN + 1];
5637 it->second.strValue.cloneTo(aValue);
5638 *aTimestamp = it->second.mTimestamp;
5639 writeFlags(it->second.mFlags, szFlags);
5640 Bstr(szFlags).cloneTo(aFlags);
5641 }
5642
5643 return S_OK;
5644}
5645
5646/**
5647 * Query the VM that a guest property belongs to for the property.
5648 * @returns E_ACCESSDENIED if the VM process is not available or not
5649 * currently handling queries and the lookup should then be done in
5650 * VBoxSVC.
5651 */
5652HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
5653 BSTR *aValue,
5654 LONG64 *aTimestamp,
5655 BSTR *aFlags) const
5656{
5657 HRESULT rc;
5658 ComPtr<IInternalSessionControl> directControl;
5659 directControl = mData->mSession.mDirectControl;
5660
5661 /* fail if we were called after #OnSessionEnd() is called. This is a
5662 * silly race condition. */
5663
5664 if (!directControl)
5665 rc = E_ACCESSDENIED;
5666 else
5667 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
5668 false /* isSetter */,
5669 aValue, aTimestamp, aFlags);
5670 return rc;
5671}
5672#endif // VBOX_WITH_GUEST_PROPS
5673
5674STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
5675 BSTR *aValue,
5676 LONG64 *aTimestamp,
5677 BSTR *aFlags)
5678{
5679#ifndef VBOX_WITH_GUEST_PROPS
5680 ReturnComNotImplemented();
5681#else // VBOX_WITH_GUEST_PROPS
5682 CheckComArgStrNotEmptyOrNull(aName);
5683 CheckComArgOutPointerValid(aValue);
5684 CheckComArgOutPointerValid(aTimestamp);
5685 CheckComArgOutPointerValid(aFlags);
5686
5687 AutoCaller autoCaller(this);
5688 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5689
5690 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
5691 if (rc == E_ACCESSDENIED)
5692 /* The VM is not running or the service is not (yet) accessible */
5693 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
5694 return rc;
5695#endif // VBOX_WITH_GUEST_PROPS
5696}
5697
5698STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
5699{
5700 LONG64 dummyTimestamp;
5701 Bstr dummyFlags;
5702 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
5703}
5704
5705STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, LONG64 *aTimestamp)
5706{
5707 Bstr dummyValue;
5708 Bstr dummyFlags;
5709 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
5710}
5711
5712#ifdef VBOX_WITH_GUEST_PROPS
5713/**
5714 * Set a guest property in VBoxSVC's internal structures.
5715 */
5716HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
5717 IN_BSTR aFlags)
5718{
5719 using namespace guestProp;
5720
5721 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5722 HRESULT rc = S_OK;
5723 HWData::GuestProperty property;
5724 property.mFlags = NILFLAG;
5725
5726 rc = checkStateDependency(MutableStateDep);
5727 if (FAILED(rc)) return rc;
5728
5729 try
5730 {
5731 Utf8Str utf8Name(aName);
5732 Utf8Str utf8Flags(aFlags);
5733 uint32_t fFlags = NILFLAG;
5734 if ( (aFlags != NULL)
5735 && RT_FAILURE(validateFlags(utf8Flags.c_str(), &fFlags))
5736 )
5737 return setError(E_INVALIDARG,
5738 tr("Invalid guest property flag values: '%ls'"),
5739 aFlags);
5740
5741 HWData::GuestPropertyMap::iterator it =
5742 mHWData->mGuestProperties.find(utf8Name);
5743
5744 if (it == mHWData->mGuestProperties.end())
5745 {
5746 setModified(IsModified_MachineData);
5747 mHWData.backupEx();
5748
5749 RTTIMESPEC time;
5750 HWData::GuestProperty prop;
5751 prop.strValue = aValue;
5752 prop.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5753 prop.mFlags = fFlags;
5754
5755 mHWData->mGuestProperties[Utf8Str(aName)] = prop;
5756 }
5757 else
5758 {
5759 if (it->second.mFlags & (RDONLYHOST))
5760 {
5761 rc = setError(E_ACCESSDENIED,
5762 tr("The property '%ls' cannot be changed by the host"),
5763 aName);
5764 }
5765 else
5766 {
5767 setModified(IsModified_MachineData);
5768 mHWData.backupEx();
5769
5770 /* The backupEx() operation invalidates our iterator,
5771 * so get a new one. */
5772 it = mHWData->mGuestProperties.find(utf8Name);
5773 Assert(it != mHWData->mGuestProperties.end());
5774
5775 if (RT_VALID_PTR(aValue) && *(aValue) != '\0')
5776 {
5777 RTTIMESPEC time;
5778 it->second.strValue = aValue;
5779 it->second.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5780 if (aFlags != NULL)
5781 it->second.mFlags = fFlags;
5782 }
5783 else
5784 {
5785 mHWData->mGuestProperties.erase(it);
5786 }
5787 }
5788 }
5789
5790 if ( SUCCEEDED(rc)
5791 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
5792 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
5793 RTSTR_MAX,
5794 utf8Name.c_str(),
5795 RTSTR_MAX,
5796 NULL)
5797 )
5798 )
5799 {
5800 alock.release();
5801
5802 mParent->onGuestPropertyChange(mData->mUuid, aName,
5803 aValue ? aValue : Bstr("").raw(),
5804 aFlags ? aFlags : Bstr("").raw());
5805 }
5806 }
5807 catch (std::bad_alloc &)
5808 {
5809 rc = E_OUTOFMEMORY;
5810 }
5811
5812 return rc;
5813}
5814
5815/**
5816 * Set a property on the VM that that property belongs to.
5817 * @returns E_ACCESSDENIED if the VM process is not available or not
5818 * currently handling queries and the setting should then be done in
5819 * VBoxSVC.
5820 */
5821HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
5822 IN_BSTR aFlags)
5823{
5824 HRESULT rc;
5825
5826 try
5827 {
5828 ComPtr<IInternalSessionControl> directControl = mData->mSession.mDirectControl;
5829
5830 BSTR dummy = NULL; /* will not be changed (setter) */
5831 LONG64 dummy64;
5832 if (!directControl)
5833 rc = E_ACCESSDENIED;
5834 else
5835 {
5836 /** @todo Fix when adding DeleteGuestProperty(),
5837 see defect. */
5838 rc = directControl->AccessGuestProperty(aName, aValue, aFlags,
5839 true /* isSetter */,
5840 &dummy, &dummy64, &dummy);
5841 if (FAILED(rc))
5842 {
5843 /* testbox hacking: a shot in the dark. */
5844 ErrorInfoKeeper eik;
5845 return rc;
5846 }
5847 }
5848 }
5849 catch (std::bad_alloc &)
5850 {
5851 rc = E_OUTOFMEMORY;
5852 }
5853
5854 return rc;
5855}
5856#endif // VBOX_WITH_GUEST_PROPS
5857
5858STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
5859 IN_BSTR aFlags)
5860{
5861#ifndef VBOX_WITH_GUEST_PROPS
5862 ReturnComNotImplemented();
5863#else // VBOX_WITH_GUEST_PROPS
5864 CheckComArgStrNotEmptyOrNull(aName);
5865 CheckComArgMaybeNull1(aFlags, 0x80face03);
5866 CheckComArgMaybeNull1(aValue, 0x80face04);
5867
5868 AutoCaller autoCaller(this);
5869 if (FAILED(autoCaller.rc()))
5870 return autoCaller.rc();
5871
5872 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
5873 if (rc == E_ACCESSDENIED)
5874 /* The VM is not running or the service is not (yet) accessible */
5875 rc = setGuestPropertyToService(aName, aValue, aFlags);
5876 return rc;
5877#endif // VBOX_WITH_GUEST_PROPS
5878}
5879
5880STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
5881{
5882 return SetGuestProperty(aName, aValue, NULL);
5883}
5884
5885STDMETHODIMP Machine::DeleteGuestProperty(IN_BSTR aName)
5886{
5887 return SetGuestProperty(aName, NULL, NULL);
5888}
5889
5890#ifdef VBOX_WITH_GUEST_PROPS
5891/**
5892 * Enumerate the guest properties in VBoxSVC's internal structures.
5893 */
5894HRESULT Machine::enumerateGuestPropertiesInService
5895 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5896 ComSafeArrayOut(BSTR, aValues),
5897 ComSafeArrayOut(LONG64, aTimestamps),
5898 ComSafeArrayOut(BSTR, aFlags))
5899{
5900 using namespace guestProp;
5901
5902 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5903 Utf8Str strPatterns(aPatterns);
5904
5905 HWData::GuestPropertyMap propMap;
5906
5907 /*
5908 * Look for matching patterns and build up a list.
5909 */
5910 HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.begin();
5911 while (it != mHWData->mGuestProperties.end())
5912 {
5913 if ( strPatterns.isEmpty()
5914 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5915 RTSTR_MAX,
5916 it->first.c_str(),
5917 RTSTR_MAX,
5918 NULL)
5919 )
5920 {
5921 propMap.insert(*it);
5922 }
5923
5924 it++;
5925 }
5926
5927 alock.release();
5928
5929 /*
5930 * And build up the arrays for returning the property information.
5931 */
5932 size_t cEntries = propMap.size();
5933 SafeArray<BSTR> names(cEntries);
5934 SafeArray<BSTR> values(cEntries);
5935 SafeArray<LONG64> timestamps(cEntries);
5936 SafeArray<BSTR> flags(cEntries);
5937 size_t iProp = 0;
5938
5939 it = propMap.begin();
5940 while (it != propMap.end())
5941 {
5942 char szFlags[MAX_FLAGS_LEN + 1];
5943 it->first.cloneTo(&names[iProp]);
5944 it->second.strValue.cloneTo(&values[iProp]);
5945 timestamps[iProp] = it->second.mTimestamp;
5946 writeFlags(it->second.mFlags, szFlags);
5947 Bstr(szFlags).cloneTo(&flags[iProp++]);
5948 it++;
5949 }
5950 names.detachTo(ComSafeArrayOutArg(aNames));
5951 values.detachTo(ComSafeArrayOutArg(aValues));
5952 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
5953 flags.detachTo(ComSafeArrayOutArg(aFlags));
5954 return S_OK;
5955}
5956
5957/**
5958 * Enumerate the properties managed by a VM.
5959 * @returns E_ACCESSDENIED if the VM process is not available or not
5960 * currently handling queries and the setting should then be done in
5961 * VBoxSVC.
5962 */
5963HRESULT Machine::enumerateGuestPropertiesOnVM
5964 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5965 ComSafeArrayOut(BSTR, aValues),
5966 ComSafeArrayOut(LONG64, aTimestamps),
5967 ComSafeArrayOut(BSTR, aFlags))
5968{
5969 HRESULT rc;
5970 ComPtr<IInternalSessionControl> directControl;
5971 directControl = mData->mSession.mDirectControl;
5972
5973 if (!directControl)
5974 rc = E_ACCESSDENIED;
5975 else
5976 rc = directControl->EnumerateGuestProperties
5977 (aPatterns, ComSafeArrayOutArg(aNames),
5978 ComSafeArrayOutArg(aValues),
5979 ComSafeArrayOutArg(aTimestamps),
5980 ComSafeArrayOutArg(aFlags));
5981 return rc;
5982}
5983#endif // VBOX_WITH_GUEST_PROPS
5984
5985STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
5986 ComSafeArrayOut(BSTR, aNames),
5987 ComSafeArrayOut(BSTR, aValues),
5988 ComSafeArrayOut(LONG64, aTimestamps),
5989 ComSafeArrayOut(BSTR, aFlags))
5990{
5991#ifndef VBOX_WITH_GUEST_PROPS
5992 ReturnComNotImplemented();
5993#else // VBOX_WITH_GUEST_PROPS
5994 CheckComArgMaybeNull(aPatterns);
5995 CheckComArgOutSafeArrayPointerValid(aNames);
5996 CheckComArgOutSafeArrayPointerValid(aValues);
5997 CheckComArgOutSafeArrayPointerValid(aTimestamps);
5998 CheckComArgOutSafeArrayPointerValid(aFlags);
5999
6000 AutoCaller autoCaller(this);
6001 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6002
6003 HRESULT rc = enumerateGuestPropertiesOnVM
6004 (aPatterns, ComSafeArrayOutArg(aNames),
6005 ComSafeArrayOutArg(aValues),
6006 ComSafeArrayOutArg(aTimestamps),
6007 ComSafeArrayOutArg(aFlags));
6008 if (rc == E_ACCESSDENIED)
6009 /* The VM is not running or the service is not (yet) accessible */
6010 rc = enumerateGuestPropertiesInService
6011 (aPatterns, ComSafeArrayOutArg(aNames),
6012 ComSafeArrayOutArg(aValues),
6013 ComSafeArrayOutArg(aTimestamps),
6014 ComSafeArrayOutArg(aFlags));
6015 return rc;
6016#endif // VBOX_WITH_GUEST_PROPS
6017}
6018
6019STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
6020 ComSafeArrayOut(IMediumAttachment*, aAttachments))
6021{
6022 MediaData::AttachmentList atts;
6023
6024 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
6025 if (FAILED(rc)) return rc;
6026
6027 SafeIfaceArray<IMediumAttachment> attachments(atts);
6028 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
6029
6030 return S_OK;
6031}
6032
6033STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
6034 LONG aControllerPort,
6035 LONG aDevice,
6036 IMediumAttachment **aAttachment)
6037{
6038 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
6039 aControllerName, aControllerPort, aDevice));
6040
6041 CheckComArgStrNotEmptyOrNull(aControllerName);
6042 CheckComArgOutPointerValid(aAttachment);
6043
6044 AutoCaller autoCaller(this);
6045 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6046
6047 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6048
6049 *aAttachment = NULL;
6050
6051 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
6052 aControllerName,
6053 aControllerPort,
6054 aDevice);
6055 if (pAttach.isNull())
6056 return setError(VBOX_E_OBJECT_NOT_FOUND,
6057 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
6058 aDevice, aControllerPort, aControllerName);
6059
6060 pAttach.queryInterfaceTo(aAttachment);
6061
6062 return S_OK;
6063}
6064
6065STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
6066 StorageBus_T aConnectionType,
6067 IStorageController **controller)
6068{
6069 CheckComArgStrNotEmptyOrNull(aName);
6070
6071 if ( (aConnectionType <= StorageBus_Null)
6072 || (aConnectionType > StorageBus_SAS))
6073 return setError(E_INVALIDARG,
6074 tr("Invalid connection type: %d"),
6075 aConnectionType);
6076
6077 AutoCaller autoCaller(this);
6078 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6079
6080 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6081
6082 HRESULT rc = checkStateDependency(MutableStateDep);
6083 if (FAILED(rc)) return rc;
6084
6085 /* try to find one with the name first. */
6086 ComObjPtr<StorageController> ctrl;
6087
6088 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
6089 if (SUCCEEDED(rc))
6090 return setError(VBOX_E_OBJECT_IN_USE,
6091 tr("Storage controller named '%ls' already exists"),
6092 aName);
6093
6094 ctrl.createObject();
6095
6096 /* get a new instance number for the storage controller */
6097 ULONG ulInstance = 0;
6098 bool fBootable = true;
6099 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6100 it != mStorageControllers->end();
6101 ++it)
6102 {
6103 if ((*it)->getStorageBus() == aConnectionType)
6104 {
6105 ULONG ulCurInst = (*it)->getInstance();
6106
6107 if (ulCurInst >= ulInstance)
6108 ulInstance = ulCurInst + 1;
6109
6110 /* Only one controller of each type can be marked as bootable. */
6111 if ((*it)->getBootable())
6112 fBootable = false;
6113 }
6114 }
6115
6116 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
6117 if (FAILED(rc)) return rc;
6118
6119 setModified(IsModified_Storage);
6120 mStorageControllers.backup();
6121 mStorageControllers->push_back(ctrl);
6122
6123 ctrl.queryInterfaceTo(controller);
6124
6125 /* inform the direct session if any */
6126 alock.release();
6127 onStorageControllerChange();
6128
6129 return S_OK;
6130}
6131
6132STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
6133 IStorageController **aStorageController)
6134{
6135 CheckComArgStrNotEmptyOrNull(aName);
6136
6137 AutoCaller autoCaller(this);
6138 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6139
6140 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6141
6142 ComObjPtr<StorageController> ctrl;
6143
6144 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
6145 if (SUCCEEDED(rc))
6146 ctrl.queryInterfaceTo(aStorageController);
6147
6148 return rc;
6149}
6150
6151STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
6152 IStorageController **aStorageController)
6153{
6154 AutoCaller autoCaller(this);
6155 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6156
6157 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6158
6159 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6160 it != mStorageControllers->end();
6161 ++it)
6162 {
6163 if ((*it)->getInstance() == aInstance)
6164 {
6165 (*it).queryInterfaceTo(aStorageController);
6166 return S_OK;
6167 }
6168 }
6169
6170 return setError(VBOX_E_OBJECT_NOT_FOUND,
6171 tr("Could not find a storage controller with instance number '%lu'"),
6172 aInstance);
6173}
6174
6175STDMETHODIMP Machine::SetStorageControllerBootable(IN_BSTR aName, BOOL fBootable)
6176{
6177 AutoCaller autoCaller(this);
6178 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6179
6180 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6181
6182 HRESULT rc = checkStateDependency(MutableStateDep);
6183 if (FAILED(rc)) return rc;
6184
6185 ComObjPtr<StorageController> ctrl;
6186
6187 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
6188 if (SUCCEEDED(rc))
6189 {
6190 /* Ensure that only one controller of each type is marked as bootable. */
6191 if (fBootable == TRUE)
6192 {
6193 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6194 it != mStorageControllers->end();
6195 ++it)
6196 {
6197 ComObjPtr<StorageController> aCtrl = (*it);
6198
6199 if ( (aCtrl->getName() != Utf8Str(aName))
6200 && aCtrl->getBootable() == TRUE
6201 && aCtrl->getStorageBus() == ctrl->getStorageBus()
6202 && aCtrl->getControllerType() == ctrl->getControllerType())
6203 {
6204 aCtrl->setBootable(FALSE);
6205 break;
6206 }
6207 }
6208 }
6209
6210 if (SUCCEEDED(rc))
6211 {
6212 ctrl->setBootable(fBootable);
6213 setModified(IsModified_Storage);
6214 }
6215 }
6216
6217 if (SUCCEEDED(rc))
6218 {
6219 /* inform the direct session if any */
6220 alock.release();
6221 onStorageControllerChange();
6222 }
6223
6224 return rc;
6225}
6226
6227STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
6228{
6229 CheckComArgStrNotEmptyOrNull(aName);
6230
6231 AutoCaller autoCaller(this);
6232 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6233
6234 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6235
6236 HRESULT rc = checkStateDependency(MutableStateDep);
6237 if (FAILED(rc)) return rc;
6238
6239 ComObjPtr<StorageController> ctrl;
6240 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
6241 if (FAILED(rc)) return rc;
6242
6243 {
6244 /* find all attached devices to the appropriate storage controller and detach them all */
6245 // make a temporary list because detachDevice invalidates iterators into
6246 // mMediaData->mAttachments
6247 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
6248
6249 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
6250 it != llAttachments2.end();
6251 ++it)
6252 {
6253 MediumAttachment *pAttachTemp = *it;
6254
6255 AutoCaller localAutoCaller(pAttachTemp);
6256 if (FAILED(localAutoCaller.rc())) return localAutoCaller.rc();
6257
6258 AutoReadLock local_alock(pAttachTemp COMMA_LOCKVAL_SRC_POS);
6259
6260 if (pAttachTemp->getControllerName() == aName)
6261 {
6262 rc = detachDevice(pAttachTemp, alock, NULL);
6263 if (FAILED(rc)) return rc;
6264 }
6265 }
6266 }
6267
6268 /* We can remove it now. */
6269 setModified(IsModified_Storage);
6270 mStorageControllers.backup();
6271
6272 ctrl->unshare();
6273
6274 mStorageControllers->remove(ctrl);
6275
6276 /* inform the direct session if any */
6277 alock.release();
6278 onStorageControllerChange();
6279
6280 return S_OK;
6281}
6282
6283STDMETHODIMP Machine::QuerySavedGuestScreenInfo(ULONG uScreenId,
6284 ULONG *puOriginX,
6285 ULONG *puOriginY,
6286 ULONG *puWidth,
6287 ULONG *puHeight,
6288 BOOL *pfEnabled)
6289{
6290 LogFlowThisFunc(("\n"));
6291
6292 CheckComArgNotNull(puOriginX);
6293 CheckComArgNotNull(puOriginY);
6294 CheckComArgNotNull(puWidth);
6295 CheckComArgNotNull(puHeight);
6296 CheckComArgNotNull(pfEnabled);
6297
6298 uint32_t u32OriginX= 0;
6299 uint32_t u32OriginY= 0;
6300 uint32_t u32Width = 0;
6301 uint32_t u32Height = 0;
6302 uint16_t u16Flags = 0;
6303
6304 int vrc = readSavedGuestScreenInfo(mSSData->strStateFilePath, uScreenId,
6305 &u32OriginX, &u32OriginY, &u32Width, &u32Height, &u16Flags);
6306 if (RT_FAILURE(vrc))
6307 {
6308#ifdef RT_OS_WINDOWS
6309 /* HACK: GUI sets *pfEnabled to 'true' and expects it to stay so if the API fails.
6310 * This works with XPCOM. But Windows COM sets all output parameters to zero.
6311 * So just assign fEnable to TRUE again.
6312 * The right fix would be to change GUI API wrappers to make sure that parameters
6313 * are changed only if API succeeds.
6314 */
6315 *pfEnabled = TRUE;
6316#endif
6317 return setError(VBOX_E_IPRT_ERROR,
6318 tr("Saved guest size is not available (%Rrc)"),
6319 vrc);
6320 }
6321
6322 *puOriginX = u32OriginX;
6323 *puOriginY = u32OriginY;
6324 *puWidth = u32Width;
6325 *puHeight = u32Height;
6326 *pfEnabled = (u16Flags & VBVA_SCREEN_F_DISABLED) == 0;
6327
6328 return S_OK;
6329}
6330
6331STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
6332{
6333 LogFlowThisFunc(("\n"));
6334
6335 CheckComArgNotNull(aSize);
6336 CheckComArgNotNull(aWidth);
6337 CheckComArgNotNull(aHeight);
6338
6339 if (aScreenId != 0)
6340 return E_NOTIMPL;
6341
6342 AutoCaller autoCaller(this);
6343 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6344
6345 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6346
6347 uint8_t *pu8Data = NULL;
6348 uint32_t cbData = 0;
6349 uint32_t u32Width = 0;
6350 uint32_t u32Height = 0;
6351
6352 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6353
6354 if (RT_FAILURE(vrc))
6355 return setError(VBOX_E_IPRT_ERROR,
6356 tr("Saved screenshot data is not available (%Rrc)"),
6357 vrc);
6358
6359 *aSize = cbData;
6360 *aWidth = u32Width;
6361 *aHeight = u32Height;
6362
6363 freeSavedDisplayScreenshot(pu8Data);
6364
6365 return S_OK;
6366}
6367
6368STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
6369{
6370 LogFlowThisFunc(("\n"));
6371
6372 CheckComArgNotNull(aWidth);
6373 CheckComArgNotNull(aHeight);
6374 CheckComArgOutSafeArrayPointerValid(aData);
6375
6376 if (aScreenId != 0)
6377 return E_NOTIMPL;
6378
6379 AutoCaller autoCaller(this);
6380 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6381
6382 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6383
6384 uint8_t *pu8Data = NULL;
6385 uint32_t cbData = 0;
6386 uint32_t u32Width = 0;
6387 uint32_t u32Height = 0;
6388
6389 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6390
6391 if (RT_FAILURE(vrc))
6392 return setError(VBOX_E_IPRT_ERROR,
6393 tr("Saved screenshot data is not available (%Rrc)"),
6394 vrc);
6395
6396 *aWidth = u32Width;
6397 *aHeight = u32Height;
6398
6399 com::SafeArray<BYTE> bitmap(cbData);
6400 /* Convert pixels to format expected by the API caller. */
6401 if (aBGR)
6402 {
6403 /* [0] B, [1] G, [2] R, [3] A. */
6404 for (unsigned i = 0; i < cbData; i += 4)
6405 {
6406 bitmap[i] = pu8Data[i];
6407 bitmap[i + 1] = pu8Data[i + 1];
6408 bitmap[i + 2] = pu8Data[i + 2];
6409 bitmap[i + 3] = 0xff;
6410 }
6411 }
6412 else
6413 {
6414 /* [0] R, [1] G, [2] B, [3] A. */
6415 for (unsigned i = 0; i < cbData; i += 4)
6416 {
6417 bitmap[i] = pu8Data[i + 2];
6418 bitmap[i + 1] = pu8Data[i + 1];
6419 bitmap[i + 2] = pu8Data[i];
6420 bitmap[i + 3] = 0xff;
6421 }
6422 }
6423 bitmap.detachTo(ComSafeArrayOutArg(aData));
6424
6425 freeSavedDisplayScreenshot(pu8Data);
6426
6427 return S_OK;
6428}
6429
6430
6431STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
6432{
6433 LogFlowThisFunc(("\n"));
6434
6435 CheckComArgNotNull(aWidth);
6436 CheckComArgNotNull(aHeight);
6437 CheckComArgOutSafeArrayPointerValid(aData);
6438
6439 if (aScreenId != 0)
6440 return E_NOTIMPL;
6441
6442 AutoCaller autoCaller(this);
6443 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6444
6445 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6446
6447 uint8_t *pu8Data = NULL;
6448 uint32_t cbData = 0;
6449 uint32_t u32Width = 0;
6450 uint32_t u32Height = 0;
6451
6452 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6453
6454 if (RT_FAILURE(vrc))
6455 return setError(VBOX_E_IPRT_ERROR,
6456 tr("Saved screenshot data is not available (%Rrc)"),
6457 vrc);
6458
6459 *aWidth = u32Width;
6460 *aHeight = u32Height;
6461
6462 HRESULT rc = S_OK;
6463 uint8_t *pu8PNG = NULL;
6464 uint32_t cbPNG = 0;
6465 uint32_t cxPNG = 0;
6466 uint32_t cyPNG = 0;
6467
6468 vrc = DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
6469
6470 if (RT_SUCCESS(vrc))
6471 {
6472 com::SafeArray<BYTE> screenData(cbPNG);
6473 screenData.initFrom(pu8PNG, cbPNG);
6474 if (pu8PNG)
6475 RTMemFree(pu8PNG);
6476 screenData.detachTo(ComSafeArrayOutArg(aData));
6477 }
6478 else
6479 {
6480 if (pu8PNG)
6481 RTMemFree(pu8PNG);
6482 return setError(VBOX_E_IPRT_ERROR,
6483 tr("Could not convert screenshot to PNG (%Rrc)"),
6484 vrc);
6485 }
6486
6487 freeSavedDisplayScreenshot(pu8Data);
6488
6489 return rc;
6490}
6491
6492STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
6493{
6494 LogFlowThisFunc(("\n"));
6495
6496 CheckComArgNotNull(aSize);
6497 CheckComArgNotNull(aWidth);
6498 CheckComArgNotNull(aHeight);
6499
6500 if (aScreenId != 0)
6501 return E_NOTIMPL;
6502
6503 AutoCaller autoCaller(this);
6504 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6505
6506 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6507
6508 uint8_t *pu8Data = NULL;
6509 uint32_t cbData = 0;
6510 uint32_t u32Width = 0;
6511 uint32_t u32Height = 0;
6512
6513 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6514
6515 if (RT_FAILURE(vrc))
6516 return setError(VBOX_E_IPRT_ERROR,
6517 tr("Saved screenshot data is not available (%Rrc)"),
6518 vrc);
6519
6520 *aSize = cbData;
6521 *aWidth = u32Width;
6522 *aHeight = u32Height;
6523
6524 freeSavedDisplayScreenshot(pu8Data);
6525
6526 return S_OK;
6527}
6528
6529STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
6530{
6531 LogFlowThisFunc(("\n"));
6532
6533 CheckComArgNotNull(aWidth);
6534 CheckComArgNotNull(aHeight);
6535 CheckComArgOutSafeArrayPointerValid(aData);
6536
6537 if (aScreenId != 0)
6538 return E_NOTIMPL;
6539
6540 AutoCaller autoCaller(this);
6541 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6542
6543 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6544
6545 uint8_t *pu8Data = NULL;
6546 uint32_t cbData = 0;
6547 uint32_t u32Width = 0;
6548 uint32_t u32Height = 0;
6549
6550 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
6551
6552 if (RT_FAILURE(vrc))
6553 return setError(VBOX_E_IPRT_ERROR,
6554 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
6555 vrc);
6556
6557 *aWidth = u32Width;
6558 *aHeight = u32Height;
6559
6560 com::SafeArray<BYTE> png(cbData);
6561 png.initFrom(pu8Data, cbData);
6562 png.detachTo(ComSafeArrayOutArg(aData));
6563
6564 freeSavedDisplayScreenshot(pu8Data);
6565
6566 return S_OK;
6567}
6568
6569STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
6570{
6571 HRESULT rc = S_OK;
6572 LogFlowThisFunc(("\n"));
6573
6574 AutoCaller autoCaller(this);
6575 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6576
6577 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6578
6579 if (!mHWData->mCPUHotPlugEnabled)
6580 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6581
6582 if (aCpu >= mHWData->mCPUCount)
6583 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
6584
6585 if (mHWData->mCPUAttached[aCpu])
6586 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
6587
6588 alock.release();
6589 rc = onCPUChange(aCpu, false);
6590 alock.acquire();
6591 if (FAILED(rc)) return rc;
6592
6593 setModified(IsModified_MachineData);
6594 mHWData.backup();
6595 mHWData->mCPUAttached[aCpu] = true;
6596
6597 /* Save settings if online */
6598 if (Global::IsOnline(mData->mMachineState))
6599 saveSettings(NULL);
6600
6601 return S_OK;
6602}
6603
6604STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
6605{
6606 HRESULT rc = S_OK;
6607 LogFlowThisFunc(("\n"));
6608
6609 AutoCaller autoCaller(this);
6610 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6611
6612 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6613
6614 if (!mHWData->mCPUHotPlugEnabled)
6615 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
6616
6617 if (aCpu >= SchemaDefs::MaxCPUCount)
6618 return setError(E_INVALIDARG,
6619 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
6620 SchemaDefs::MaxCPUCount);
6621
6622 if (!mHWData->mCPUAttached[aCpu])
6623 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
6624
6625 /* CPU 0 can't be detached */
6626 if (aCpu == 0)
6627 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
6628
6629 alock.release();
6630 rc = onCPUChange(aCpu, true);
6631 alock.acquire();
6632 if (FAILED(rc)) return rc;
6633
6634 setModified(IsModified_MachineData);
6635 mHWData.backup();
6636 mHWData->mCPUAttached[aCpu] = false;
6637
6638 /* Save settings if online */
6639 if (Global::IsOnline(mData->mMachineState))
6640 saveSettings(NULL);
6641
6642 return S_OK;
6643}
6644
6645STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
6646{
6647 LogFlowThisFunc(("\n"));
6648
6649 CheckComArgNotNull(aCpuAttached);
6650
6651 *aCpuAttached = false;
6652
6653 AutoCaller autoCaller(this);
6654 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6655
6656 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6657
6658 /* If hotplug is enabled the CPU is always enabled. */
6659 if (!mHWData->mCPUHotPlugEnabled)
6660 {
6661 if (aCpu < mHWData->mCPUCount)
6662 *aCpuAttached = true;
6663 }
6664 else
6665 {
6666 if (aCpu < SchemaDefs::MaxCPUCount)
6667 *aCpuAttached = mHWData->mCPUAttached[aCpu];
6668 }
6669
6670 return S_OK;
6671}
6672
6673STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
6674{
6675 CheckComArgOutPointerValid(aName);
6676
6677 AutoCaller autoCaller(this);
6678 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6679
6680 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6681
6682 Utf8Str log = queryLogFilename(aIdx);
6683 if (!RTFileExists(log.c_str()))
6684 log.setNull();
6685 log.cloneTo(aName);
6686
6687 return S_OK;
6688}
6689
6690STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
6691{
6692 LogFlowThisFunc(("\n"));
6693 CheckComArgOutSafeArrayPointerValid(aData);
6694 if (aSize < 0)
6695 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
6696
6697 AutoCaller autoCaller(this);
6698 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6699
6700 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6701
6702 HRESULT rc = S_OK;
6703 Utf8Str log = queryLogFilename(aIdx);
6704
6705 /* do not unnecessarily hold the lock while doing something which does
6706 * not need the lock and potentially takes a long time. */
6707 alock.release();
6708
6709 /* Limit the chunk size to 32K for now, as that gives better performance
6710 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
6711 * One byte expands to approx. 25 bytes of breathtaking XML. */
6712 size_t cbData = (size_t)RT_MIN(aSize, 32768);
6713 com::SafeArray<BYTE> logData(cbData);
6714
6715 RTFILE LogFile;
6716 int vrc = RTFileOpen(&LogFile, log.c_str(),
6717 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
6718 if (RT_SUCCESS(vrc))
6719 {
6720 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
6721 if (RT_SUCCESS(vrc))
6722 logData.resize(cbData);
6723 else
6724 rc = setError(VBOX_E_IPRT_ERROR,
6725 tr("Could not read log file '%s' (%Rrc)"),
6726 log.c_str(), vrc);
6727 RTFileClose(LogFile);
6728 }
6729 else
6730 rc = setError(VBOX_E_IPRT_ERROR,
6731 tr("Could not open log file '%s' (%Rrc)"),
6732 log.c_str(), vrc);
6733
6734 if (FAILED(rc))
6735 logData.resize(0);
6736 logData.detachTo(ComSafeArrayOutArg(aData));
6737
6738 return rc;
6739}
6740
6741
6742/**
6743 * Currently this method doesn't attach device to the running VM,
6744 * just makes sure it's plugged on next VM start.
6745 */
6746STDMETHODIMP Machine::AttachHostPCIDevice(LONG hostAddress, LONG desiredGuestAddress, BOOL /*tryToUnbind*/)
6747{
6748 AutoCaller autoCaller(this);
6749 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6750
6751 // lock scope
6752 {
6753 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6754
6755 HRESULT rc = checkStateDependency(MutableStateDep);
6756 if (FAILED(rc)) return rc;
6757
6758 ChipsetType_T aChipset = ChipsetType_PIIX3;
6759 COMGETTER(ChipsetType)(&aChipset);
6760
6761 if (aChipset != ChipsetType_ICH9)
6762 {
6763 return setError(E_INVALIDARG,
6764 tr("Host PCI attachment only supported with ICH9 chipset"));
6765 }
6766
6767 // check if device with this host PCI address already attached
6768 for (HWData::PCIDeviceAssignmentList::iterator it = mHWData->mPCIDeviceAssignments.begin();
6769 it != mHWData->mPCIDeviceAssignments.end();
6770 ++it)
6771 {
6772 LONG iHostAddress = -1;
6773 ComPtr<PCIDeviceAttachment> pAttach;
6774 pAttach = *it;
6775 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6776 if (iHostAddress == hostAddress)
6777 return setError(E_INVALIDARG,
6778 tr("Device with host PCI address already attached to this VM"));
6779 }
6780
6781 ComObjPtr<PCIDeviceAttachment> pda;
6782 char name[32];
6783
6784 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (hostAddress>>8) & 0xff, (hostAddress & 0xf8) >> 3, hostAddress & 7);
6785 Bstr bname(name);
6786 pda.createObject();
6787 pda->init(this, bname, hostAddress, desiredGuestAddress, TRUE);
6788 setModified(IsModified_MachineData);
6789 mHWData.backup();
6790 mHWData->mPCIDeviceAssignments.push_back(pda);
6791 }
6792
6793 return S_OK;
6794}
6795
6796/**
6797 * Currently this method doesn't detach device from the running VM,
6798 * just makes sure it's not plugged on next VM start.
6799 */
6800STDMETHODIMP Machine::DetachHostPCIDevice(LONG hostAddress)
6801{
6802 AutoCaller autoCaller(this);
6803 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6804
6805 ComObjPtr<PCIDeviceAttachment> pAttach;
6806 bool fRemoved = false;
6807 HRESULT rc;
6808
6809 // lock scope
6810 {
6811 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6812
6813 rc = checkStateDependency(MutableStateDep);
6814 if (FAILED(rc)) return rc;
6815
6816 for (HWData::PCIDeviceAssignmentList::iterator it = mHWData->mPCIDeviceAssignments.begin();
6817 it != mHWData->mPCIDeviceAssignments.end();
6818 ++it)
6819 {
6820 LONG iHostAddress = -1;
6821 pAttach = *it;
6822 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6823 if (iHostAddress != -1 && iHostAddress == hostAddress)
6824 {
6825 setModified(IsModified_MachineData);
6826 mHWData.backup();
6827 mHWData->mPCIDeviceAssignments.remove(pAttach);
6828 fRemoved = true;
6829 break;
6830 }
6831 }
6832 }
6833
6834
6835 /* Fire event outside of the lock */
6836 if (fRemoved)
6837 {
6838 Assert(!pAttach.isNull());
6839 ComPtr<IEventSource> es;
6840 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
6841 Assert(SUCCEEDED(rc));
6842 Bstr mid;
6843 rc = this->COMGETTER(Id)(mid.asOutParam());
6844 Assert(SUCCEEDED(rc));
6845 fireHostPCIDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
6846 }
6847
6848 return fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
6849 tr("No host PCI device %08x attached"),
6850 hostAddress
6851 );
6852}
6853
6854STDMETHODIMP Machine::COMGETTER(PCIDeviceAssignments)(ComSafeArrayOut(IPCIDeviceAttachment *, aAssignments))
6855{
6856 CheckComArgOutSafeArrayPointerValid(aAssignments);
6857
6858 AutoCaller autoCaller(this);
6859 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6860
6861 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6862
6863 SafeIfaceArray<IPCIDeviceAttachment> assignments(mHWData->mPCIDeviceAssignments);
6864 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
6865
6866 return S_OK;
6867}
6868
6869STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
6870{
6871 CheckComArgOutPointerValid(aBandwidthControl);
6872
6873 AutoCaller autoCaller(this);
6874 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6875
6876 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
6877
6878 return S_OK;
6879}
6880
6881STDMETHODIMP Machine::COMGETTER(TracingEnabled)(BOOL *pfEnabled)
6882{
6883 CheckComArgOutPointerValid(pfEnabled);
6884 AutoCaller autoCaller(this);
6885 HRESULT hrc = autoCaller.rc();
6886 if (SUCCEEDED(hrc))
6887 {
6888 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6889 *pfEnabled = mHWData->mDebugging.fTracingEnabled;
6890 }
6891 return hrc;
6892}
6893
6894STDMETHODIMP Machine::COMSETTER(TracingEnabled)(BOOL fEnabled)
6895{
6896 AutoCaller autoCaller(this);
6897 HRESULT hrc = autoCaller.rc();
6898 if (SUCCEEDED(hrc))
6899 {
6900 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6901 hrc = checkStateDependency(MutableStateDep);
6902 if (SUCCEEDED(hrc))
6903 {
6904 hrc = mHWData.backupEx();
6905 if (SUCCEEDED(hrc))
6906 {
6907 setModified(IsModified_MachineData);
6908 mHWData->mDebugging.fTracingEnabled = fEnabled != FALSE;
6909 }
6910 }
6911 }
6912 return hrc;
6913}
6914
6915STDMETHODIMP Machine::COMGETTER(TracingConfig)(BSTR *pbstrConfig)
6916{
6917 CheckComArgOutPointerValid(pbstrConfig);
6918 AutoCaller autoCaller(this);
6919 HRESULT hrc = autoCaller.rc();
6920 if (SUCCEEDED(hrc))
6921 {
6922 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6923 hrc = mHWData->mDebugging.strTracingConfig.cloneToEx(pbstrConfig);
6924 }
6925 return hrc;
6926}
6927
6928STDMETHODIMP Machine::COMSETTER(TracingConfig)(IN_BSTR bstrConfig)
6929{
6930 CheckComArgStr(bstrConfig);
6931 AutoCaller autoCaller(this);
6932 HRESULT hrc = autoCaller.rc();
6933 if (SUCCEEDED(hrc))
6934 {
6935 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6936 hrc = checkStateDependency(MutableStateDep);
6937 if (SUCCEEDED(hrc))
6938 {
6939 hrc = mHWData.backupEx();
6940 if (SUCCEEDED(hrc))
6941 {
6942 hrc = mHWData->mDebugging.strTracingConfig.cloneEx(bstrConfig);
6943 if (SUCCEEDED(hrc))
6944 setModified(IsModified_MachineData);
6945 }
6946 }
6947 }
6948 return hrc;
6949
6950}
6951
6952STDMETHODIMP Machine::COMGETTER(AllowTracingToAccessVM)(BOOL *pfAllow)
6953{
6954 CheckComArgOutPointerValid(pfAllow);
6955 AutoCaller autoCaller(this);
6956 HRESULT hrc = autoCaller.rc();
6957 if (SUCCEEDED(hrc))
6958 {
6959 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6960 *pfAllow = mHWData->mDebugging.fAllowTracingToAccessVM;
6961 }
6962 return hrc;
6963}
6964
6965STDMETHODIMP Machine::COMSETTER(AllowTracingToAccessVM)(BOOL fAllow)
6966{
6967 AutoCaller autoCaller(this);
6968 HRESULT hrc = autoCaller.rc();
6969 if (SUCCEEDED(hrc))
6970 {
6971 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6972 hrc = checkStateDependency(MutableStateDep);
6973 if (SUCCEEDED(hrc))
6974 {
6975 hrc = mHWData.backupEx();
6976 if (SUCCEEDED(hrc))
6977 {
6978 setModified(IsModified_MachineData);
6979 mHWData->mDebugging.fAllowTracingToAccessVM = fAllow != FALSE;
6980 }
6981 }
6982 }
6983 return hrc;
6984}
6985
6986STDMETHODIMP Machine::COMGETTER(AutostartEnabled)(BOOL *pfEnabled)
6987{
6988 CheckComArgOutPointerValid(pfEnabled);
6989 AutoCaller autoCaller(this);
6990 HRESULT hrc = autoCaller.rc();
6991 if (SUCCEEDED(hrc))
6992 {
6993 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6994 *pfEnabled = mHWData->mAutostart.fAutostartEnabled;
6995 }
6996 return hrc;
6997}
6998
6999STDMETHODIMP Machine::COMSETTER(AutostartEnabled)(BOOL fEnabled)
7000{
7001 AutoCaller autoCaller(this);
7002 HRESULT hrc = autoCaller.rc();
7003 if (SUCCEEDED(hrc))
7004 {
7005 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7006 hrc = checkStateDependency(MutableStateDep);
7007 if ( SUCCEEDED(hrc)
7008 && mHWData->mAutostart.fAutostartEnabled != !!fEnabled)
7009 {
7010 AutostartDb *autostartDb = mParent->getAutostartDb();
7011 int vrc;
7012
7013 if (fEnabled)
7014 vrc = autostartDb->addAutostartVM(mUserData->s.strName.c_str());
7015 else
7016 vrc = autostartDb->removeAutostartVM(mUserData->s.strName.c_str());
7017
7018 if (RT_SUCCESS(vrc))
7019 {
7020 hrc = mHWData.backupEx();
7021 if (SUCCEEDED(hrc))
7022 {
7023 setModified(IsModified_MachineData);
7024 mHWData->mAutostart.fAutostartEnabled = fEnabled != FALSE;
7025 }
7026 }
7027 else if (vrc == VERR_NOT_SUPPORTED)
7028 hrc = setError(VBOX_E_NOT_SUPPORTED,
7029 tr("The VM autostart feature is not supported on this platform"));
7030 else if (vrc == VERR_PATH_NOT_FOUND)
7031 hrc = setError(E_FAIL,
7032 tr("The path to the autostart database is not set"));
7033 else
7034 hrc = setError(E_UNEXPECTED,
7035 tr("%s machine '%s' to the autostart database failed with %Rrc"),
7036 fEnabled ? "Adding" : "Removing",
7037 mUserData->s.strName.c_str(), vrc);
7038 }
7039 }
7040 return hrc;
7041}
7042
7043STDMETHODIMP Machine::COMGETTER(AutostartDelay)(ULONG *puDelay)
7044{
7045 CheckComArgOutPointerValid(puDelay);
7046 AutoCaller autoCaller(this);
7047 HRESULT hrc = autoCaller.rc();
7048 if (SUCCEEDED(hrc))
7049 {
7050 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7051 *puDelay = mHWData->mAutostart.uAutostartDelay;
7052 }
7053 return hrc;
7054}
7055
7056STDMETHODIMP Machine::COMSETTER(AutostartDelay)(ULONG uDelay)
7057{
7058 AutoCaller autoCaller(this);
7059 HRESULT hrc = autoCaller.rc();
7060 if (SUCCEEDED(hrc))
7061 {
7062 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7063 hrc = checkStateDependency(MutableStateDep);
7064 if (SUCCEEDED(hrc))
7065 {
7066 hrc = mHWData.backupEx();
7067 if (SUCCEEDED(hrc))
7068 {
7069 setModified(IsModified_MachineData);
7070 mHWData->mAutostart.uAutostartDelay = uDelay;
7071 }
7072 }
7073 }
7074 return hrc;
7075}
7076
7077STDMETHODIMP Machine::COMGETTER(AutostopType)(AutostopType_T *penmAutostopType)
7078{
7079 CheckComArgOutPointerValid(penmAutostopType);
7080 AutoCaller autoCaller(this);
7081 HRESULT hrc = autoCaller.rc();
7082 if (SUCCEEDED(hrc))
7083 {
7084 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7085 *penmAutostopType = mHWData->mAutostart.enmAutostopType;
7086 }
7087 return hrc;
7088}
7089
7090STDMETHODIMP Machine::COMSETTER(AutostopType)(AutostopType_T enmAutostopType)
7091{
7092 AutoCaller autoCaller(this);
7093 HRESULT hrc = autoCaller.rc();
7094 if (SUCCEEDED(hrc))
7095 {
7096 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7097 hrc = checkStateDependency(MutableStateDep);
7098 if ( SUCCEEDED(hrc)
7099 && mHWData->mAutostart.enmAutostopType != enmAutostopType)
7100 {
7101 AutostartDb *autostartDb = mParent->getAutostartDb();
7102 int vrc;
7103
7104 if (enmAutostopType != AutostopType_Disabled)
7105 vrc = autostartDb->addAutostopVM(mUserData->s.strName.c_str());
7106 else
7107 vrc = autostartDb->removeAutostopVM(mUserData->s.strName.c_str());
7108
7109 if (RT_SUCCESS(vrc))
7110 {
7111 hrc = mHWData.backupEx();
7112 if (SUCCEEDED(hrc))
7113 {
7114 setModified(IsModified_MachineData);
7115 mHWData->mAutostart.enmAutostopType = enmAutostopType;
7116 }
7117 }
7118 else if (vrc == VERR_NOT_SUPPORTED)
7119 hrc = setError(VBOX_E_NOT_SUPPORTED,
7120 tr("The VM autostop feature is not supported on this platform"));
7121 else if (vrc == VERR_PATH_NOT_FOUND)
7122 hrc = setError(E_FAIL,
7123 tr("The path to the autostart database is not set"));
7124 else
7125 hrc = setError(E_UNEXPECTED,
7126 tr("%s machine '%s' to the autostop database failed with %Rrc"),
7127 enmAutostopType != AutostopType_Disabled ? "Adding" : "Removing",
7128 mUserData->s.strName.c_str(), vrc);
7129 }
7130 }
7131 return hrc;
7132}
7133
7134STDMETHODIMP Machine::COMGETTER(DefaultFrontend)(BSTR *aDefaultFrontend)
7135{
7136 CheckComArgOutPointerValid(aDefaultFrontend);
7137 AutoCaller autoCaller(this);
7138 HRESULT hrc = autoCaller.rc();
7139 if (SUCCEEDED(hrc))
7140 {
7141 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7142 mHWData->mDefaultFrontend.cloneTo(aDefaultFrontend);
7143 }
7144 return hrc;
7145}
7146
7147STDMETHODIMP Machine::COMSETTER(DefaultFrontend)(IN_BSTR aDefaultFrontend)
7148{
7149 CheckComArgStr(aDefaultFrontend);
7150 AutoCaller autoCaller(this);
7151 HRESULT hrc = autoCaller.rc();
7152 if (SUCCEEDED(hrc))
7153 {
7154 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7155 hrc = checkStateDependency(MutableOrSavedStateDep);
7156 if (SUCCEEDED(hrc))
7157 {
7158 hrc = mHWData.backupEx();
7159 if (SUCCEEDED(hrc))
7160 {
7161 setModified(IsModified_MachineData);
7162 mHWData->mDefaultFrontend = aDefaultFrontend;
7163 }
7164 }
7165 }
7166 return hrc;
7167}
7168
7169
7170STDMETHODIMP Machine::CloneTo(IMachine *pTarget, CloneMode_T mode, ComSafeArrayIn(CloneOptions_T, options), IProgress **pProgress)
7171{
7172 LogFlowFuncEnter();
7173
7174 CheckComArgNotNull(pTarget);
7175 CheckComArgOutPointerValid(pProgress);
7176
7177 /* Convert the options. */
7178 RTCList<CloneOptions_T> optList;
7179 if (options != NULL)
7180 optList = com::SafeArray<CloneOptions_T>(ComSafeArrayInArg(options)).toList();
7181
7182 if (optList.contains(CloneOptions_Link))
7183 {
7184 if (!isSnapshotMachine())
7185 return setError(E_INVALIDARG,
7186 tr("Linked clone can only be created from a snapshot"));
7187 if (mode != CloneMode_MachineState)
7188 return setError(E_INVALIDARG,
7189 tr("Linked clone can only be created for a single machine state"));
7190 }
7191 AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_INVALIDARG);
7192
7193 AutoCaller autoCaller(this);
7194 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7195
7196
7197 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), mode, optList);
7198
7199 HRESULT rc = pWorker->start(pProgress);
7200
7201 LogFlowFuncLeave();
7202
7203 return rc;
7204}
7205
7206// public methods for internal purposes
7207/////////////////////////////////////////////////////////////////////////////
7208
7209/**
7210 * Adds the given IsModified_* flag to the dirty flags of the machine.
7211 * This must be called either during loadSettings or under the machine write lock.
7212 * @param fl
7213 */
7214void Machine::setModified(uint32_t fl, bool fAllowStateModification /* = true */)
7215{
7216 mData->flModifications |= fl;
7217 if (fAllowStateModification && isStateModificationAllowed())
7218 mData->mCurrentStateModified = true;
7219}
7220
7221/**
7222 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
7223 * care of the write locking.
7224 *
7225 * @param fModifications The flag to add.
7226 */
7227void Machine::setModifiedLock(uint32_t fModification, bool fAllowStateModification /* = true */)
7228{
7229 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7230 setModified(fModification, fAllowStateModification);
7231}
7232
7233/**
7234 * Saves the registry entry of this machine to the given configuration node.
7235 *
7236 * @param aEntryNode Node to save the registry entry to.
7237 *
7238 * @note locks this object for reading.
7239 */
7240HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
7241{
7242 AutoLimitedCaller autoCaller(this);
7243 AssertComRCReturnRC(autoCaller.rc());
7244
7245 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7246
7247 data.uuid = mData->mUuid;
7248 data.strSettingsFile = mData->m_strConfigFile;
7249
7250 return S_OK;
7251}
7252
7253/**
7254 * Calculates the absolute path of the given path taking the directory of the
7255 * machine settings file as the current directory.
7256 *
7257 * @param aPath Path to calculate the absolute path for.
7258 * @param aResult Where to put the result (used only on success, can be the
7259 * same Utf8Str instance as passed in @a aPath).
7260 * @return IPRT result.
7261 *
7262 * @note Locks this object for reading.
7263 */
7264int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
7265{
7266 AutoCaller autoCaller(this);
7267 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7268
7269 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7270
7271 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
7272
7273 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
7274
7275 strSettingsDir.stripFilename();
7276 char folder[RTPATH_MAX];
7277 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
7278 if (RT_SUCCESS(vrc))
7279 aResult = folder;
7280
7281 return vrc;
7282}
7283
7284/**
7285 * Copies strSource to strTarget, making it relative to the machine folder
7286 * if it is a subdirectory thereof, or simply copying it otherwise.
7287 *
7288 * @param strSource Path to evaluate and copy.
7289 * @param strTarget Buffer to receive target path.
7290 *
7291 * @note Locks this object for reading.
7292 */
7293void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
7294 Utf8Str &strTarget)
7295{
7296 AutoCaller autoCaller(this);
7297 AssertComRCReturn(autoCaller.rc(), (void)0);
7298
7299 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7300
7301 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
7302 // use strTarget as a temporary buffer to hold the machine settings dir
7303 strTarget = mData->m_strConfigFileFull;
7304 strTarget.stripFilename();
7305 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
7306 {
7307 // is relative: then append what's left
7308 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
7309 // for empty paths (only possible for subdirs) use "." to avoid
7310 // triggering default settings for not present config attributes.
7311 if (strTarget.isEmpty())
7312 strTarget = ".";
7313 }
7314 else
7315 // is not relative: then overwrite
7316 strTarget = strSource;
7317}
7318
7319/**
7320 * Returns the full path to the machine's log folder in the
7321 * \a aLogFolder argument.
7322 */
7323void Machine::getLogFolder(Utf8Str &aLogFolder)
7324{
7325 AutoCaller autoCaller(this);
7326 AssertComRCReturnVoid(autoCaller.rc());
7327
7328 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7329
7330 char szTmp[RTPATH_MAX];
7331 int vrc = RTEnvGetEx(RTENV_DEFAULT, "VBOX_USER_VMLOGDIR", szTmp, sizeof(szTmp), NULL);
7332 if (RT_SUCCESS(vrc))
7333 {
7334 if (szTmp[0] && !mUserData.isNull())
7335 {
7336 char szTmp2[RTPATH_MAX];
7337 vrc = RTPathAbs(szTmp, szTmp2, sizeof(szTmp2));
7338 if (RT_SUCCESS(vrc))
7339 aLogFolder = BstrFmt("%s%c%s",
7340 szTmp2,
7341 RTPATH_DELIMITER,
7342 mUserData->s.strName.c_str()); // path/to/logfolder/vmname
7343 }
7344 else
7345 vrc = VERR_PATH_IS_RELATIVE;
7346 }
7347
7348 if (RT_FAILURE(vrc))
7349 {
7350 // fallback if VBOX_USER_LOGHOME is not set or invalid
7351 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
7352 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
7353 aLogFolder.append(RTPATH_DELIMITER);
7354 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
7355 }
7356}
7357
7358/**
7359 * Returns the full path to the machine's log file for an given index.
7360 */
7361Utf8Str Machine::queryLogFilename(ULONG idx)
7362{
7363 Utf8Str logFolder;
7364 getLogFolder(logFolder);
7365 Assert(logFolder.length());
7366 Utf8Str log;
7367 if (idx == 0)
7368 log = Utf8StrFmt("%s%cVBox.log",
7369 logFolder.c_str(), RTPATH_DELIMITER);
7370 else
7371 log = Utf8StrFmt("%s%cVBox.log.%d",
7372 logFolder.c_str(), RTPATH_DELIMITER, idx);
7373 return log;
7374}
7375
7376/**
7377 * Composes a unique saved state filename based on the current system time. The filename is
7378 * granular to the second so this will work so long as no more than one snapshot is taken on
7379 * a machine per second.
7380 *
7381 * Before version 4.1, we used this formula for saved state files:
7382 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
7383 * which no longer works because saved state files can now be shared between the saved state of the
7384 * "saved" machine and an online snapshot, and the following would cause problems:
7385 * 1) save machine
7386 * 2) create online snapshot from that machine state --> reusing saved state file
7387 * 3) save machine again --> filename would be reused, breaking the online snapshot
7388 *
7389 * So instead we now use a timestamp.
7390 *
7391 * @param str
7392 */
7393void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
7394{
7395 AutoCaller autoCaller(this);
7396 AssertComRCReturnVoid(autoCaller.rc());
7397
7398 {
7399 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7400 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
7401 }
7402
7403 RTTIMESPEC ts;
7404 RTTimeNow(&ts);
7405 RTTIME time;
7406 RTTimeExplode(&time, &ts);
7407
7408 strStateFilePath += RTPATH_DELIMITER;
7409 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
7410 time.i32Year, time.u8Month, time.u8MonthDay,
7411 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
7412}
7413
7414/**
7415 * @note Locks this object for writing, calls the client process
7416 * (inside the lock).
7417 */
7418HRESULT Machine::launchVMProcess(IInternalSessionControl *aControl,
7419 const Utf8Str &strFrontend,
7420 const Utf8Str &strEnvironment,
7421 ProgressProxy *aProgress)
7422{
7423 LogFlowThisFuncEnter();
7424
7425 AssertReturn(aControl, E_FAIL);
7426 AssertReturn(aProgress, E_FAIL);
7427
7428 AutoCaller autoCaller(this);
7429 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7430
7431 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7432
7433 if (!mData->mRegistered)
7434 return setError(E_UNEXPECTED,
7435 tr("The machine '%s' is not registered"),
7436 mUserData->s.strName.c_str());
7437
7438 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
7439
7440 if ( mData->mSession.mState == SessionState_Locked
7441 || mData->mSession.mState == SessionState_Spawning
7442 || mData->mSession.mState == SessionState_Unlocking)
7443 return setError(VBOX_E_INVALID_OBJECT_STATE,
7444 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
7445 mUserData->s.strName.c_str());
7446
7447 /* may not be busy */
7448 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
7449
7450 /* get the path to the executable */
7451 char szPath[RTPATH_MAX];
7452 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
7453 size_t sz = strlen(szPath);
7454 szPath[sz++] = RTPATH_DELIMITER;
7455 szPath[sz] = 0;
7456 char *cmd = szPath + sz;
7457 sz = RTPATH_MAX - sz;
7458
7459 int vrc = VINF_SUCCESS;
7460 RTPROCESS pid = NIL_RTPROCESS;
7461
7462 RTENV env = RTENV_DEFAULT;
7463
7464 if (!strEnvironment.isEmpty())
7465 {
7466 char *newEnvStr = NULL;
7467
7468 do
7469 {
7470 /* clone the current environment */
7471 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
7472 AssertRCBreakStmt(vrc2, vrc = vrc2);
7473
7474 newEnvStr = RTStrDup(strEnvironment.c_str());
7475 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
7476
7477 /* put new variables to the environment
7478 * (ignore empty variable names here since RTEnv API
7479 * intentionally doesn't do that) */
7480 char *var = newEnvStr;
7481 for (char *p = newEnvStr; *p; ++p)
7482 {
7483 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
7484 {
7485 *p = '\0';
7486 if (*var)
7487 {
7488 char *val = strchr(var, '=');
7489 if (val)
7490 {
7491 *val++ = '\0';
7492 vrc2 = RTEnvSetEx(env, var, val);
7493 }
7494 else
7495 vrc2 = RTEnvUnsetEx(env, var);
7496 if (RT_FAILURE(vrc2))
7497 break;
7498 }
7499 var = p + 1;
7500 }
7501 }
7502 if (RT_SUCCESS(vrc2) && *var)
7503 vrc2 = RTEnvPutEx(env, var);
7504
7505 AssertRCBreakStmt(vrc2, vrc = vrc2);
7506 }
7507 while (0);
7508
7509 if (newEnvStr != NULL)
7510 RTStrFree(newEnvStr);
7511 }
7512
7513 /* Qt is default */
7514#ifdef VBOX_WITH_QTGUI
7515 if (strFrontend == "gui" || strFrontend == "GUI/Qt" || strFrontend == "")
7516 {
7517# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
7518 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
7519# else
7520 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
7521# endif
7522 Assert(sz >= sizeof(VirtualBox_exe));
7523 strcpy(cmd, VirtualBox_exe);
7524
7525 Utf8Str idStr = mData->mUuid.toString();
7526 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
7527 vrc = RTProcCreate(szPath, args, env, 0, &pid);
7528 }
7529#else /* !VBOX_WITH_QTGUI */
7530 if (0)
7531 ;
7532#endif /* VBOX_WITH_QTGUI */
7533
7534 else
7535
7536#ifdef VBOX_WITH_VBOXSDL
7537 if (strFrontend == "sdl" || strFrontend == "GUI/SDL")
7538 {
7539 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
7540 Assert(sz >= sizeof(VBoxSDL_exe));
7541 strcpy(cmd, VBoxSDL_exe);
7542
7543 Utf8Str idStr = mData->mUuid.toString();
7544 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
7545 vrc = RTProcCreate(szPath, args, env, 0, &pid);
7546 }
7547#else /* !VBOX_WITH_VBOXSDL */
7548 if (0)
7549 ;
7550#endif /* !VBOX_WITH_VBOXSDL */
7551
7552 else
7553
7554#ifdef VBOX_WITH_HEADLESS
7555 if ( strFrontend == "headless"
7556 || strFrontend == "capture"
7557 || strFrontend == "vrdp" /* Deprecated. Same as headless. */
7558 )
7559 {
7560 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
7561 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
7562 * and a VM works even if the server has not been installed.
7563 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
7564 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
7565 * differently in 4.0 and 3.x.
7566 */
7567 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
7568 Assert(sz >= sizeof(VBoxHeadless_exe));
7569 strcpy(cmd, VBoxHeadless_exe);
7570
7571 Utf8Str idStr = mData->mUuid.toString();
7572 /* Leave space for "--capture" arg. */
7573 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
7574 "--startvm", idStr.c_str(),
7575 "--vrde", "config",
7576 0, /* For "--capture". */
7577 0 };
7578 if (strFrontend == "capture")
7579 {
7580 unsigned pos = RT_ELEMENTS(args) - 2;
7581 args[pos] = "--capture";
7582 }
7583 vrc = RTProcCreate(szPath, args, env,
7584#ifdef RT_OS_WINDOWS
7585 RTPROC_FLAGS_NO_WINDOW
7586#else
7587 0
7588#endif
7589 , &pid);
7590 }
7591#else /* !VBOX_WITH_HEADLESS */
7592 if (0)
7593 ;
7594#endif /* !VBOX_WITH_HEADLESS */
7595 else
7596 {
7597 RTEnvDestroy(env);
7598 return setError(E_INVALIDARG,
7599 tr("Invalid frontend name: '%s'"),
7600 strFrontend.c_str());
7601 }
7602
7603 RTEnvDestroy(env);
7604
7605 if (RT_FAILURE(vrc))
7606 return setError(VBOX_E_IPRT_ERROR,
7607 tr("Could not launch a process for the machine '%s' (%Rrc)"),
7608 mUserData->s.strName.c_str(), vrc);
7609
7610 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
7611
7612 /*
7613 * Note that we don't release the lock here before calling the client,
7614 * because it doesn't need to call us back if called with a NULL argument.
7615 * Releasing the lock here is dangerous because we didn't prepare the
7616 * launch data yet, but the client we've just started may happen to be
7617 * too fast and call openSession() that will fail (because of PID, etc.),
7618 * so that the Machine will never get out of the Spawning session state.
7619 */
7620
7621 /* inform the session that it will be a remote one */
7622 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
7623 HRESULT rc = aControl->AssignMachine(NULL, LockType_Write);
7624 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
7625
7626 if (FAILED(rc))
7627 {
7628 /* restore the session state */
7629 mData->mSession.mState = SessionState_Unlocked;
7630 /* The failure may occur w/o any error info (from RPC), so provide one */
7631 return setError(VBOX_E_VM_ERROR,
7632 tr("Failed to assign the machine to the session (%Rrc)"), rc);
7633 }
7634
7635 /* attach launch data to the machine */
7636 Assert(mData->mSession.mPID == NIL_RTPROCESS);
7637 mData->mSession.mRemoteControls.push_back(aControl);
7638 mData->mSession.mProgress = aProgress;
7639 mData->mSession.mPID = pid;
7640 mData->mSession.mState = SessionState_Spawning;
7641 mData->mSession.mType = strFrontend;
7642
7643 LogFlowThisFuncLeave();
7644 return S_OK;
7645}
7646
7647/**
7648 * Returns @c true if the given machine has an open direct session and returns
7649 * the session machine instance and additional session data (on some platforms)
7650 * if so.
7651 *
7652 * Note that when the method returns @c false, the arguments remain unchanged.
7653 *
7654 * @param aMachine Session machine object.
7655 * @param aControl Direct session control object (optional).
7656 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
7657 *
7658 * @note locks this object for reading.
7659 */
7660#if defined(RT_OS_WINDOWS)
7661bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7662 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7663 HANDLE *aIPCSem /*= NULL*/,
7664 bool aAllowClosing /*= false*/)
7665#elif defined(RT_OS_OS2)
7666bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7667 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7668 HMTX *aIPCSem /*= NULL*/,
7669 bool aAllowClosing /*= false*/)
7670#else
7671bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7672 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7673 bool aAllowClosing /*= false*/)
7674#endif
7675{
7676 AutoLimitedCaller autoCaller(this);
7677 AssertComRCReturn(autoCaller.rc(), false);
7678
7679 /* just return false for inaccessible machines */
7680 if (autoCaller.state() != Ready)
7681 return false;
7682
7683 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7684
7685 if ( mData->mSession.mState == SessionState_Locked
7686 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
7687 )
7688 {
7689 AssertReturn(!mData->mSession.mMachine.isNull(), false);
7690
7691 aMachine = mData->mSession.mMachine;
7692
7693 if (aControl != NULL)
7694 *aControl = mData->mSession.mDirectControl;
7695
7696#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7697 /* Additional session data */
7698 if (aIPCSem != NULL)
7699 *aIPCSem = aMachine->mIPCSem;
7700#endif
7701 return true;
7702 }
7703
7704 return false;
7705}
7706
7707/**
7708 * Returns @c true if the given machine has an spawning direct session and
7709 * returns and additional session data (on some platforms) if so.
7710 *
7711 * Note that when the method returns @c false, the arguments remain unchanged.
7712 *
7713 * @param aPID PID of the spawned direct session process.
7714 *
7715 * @note locks this object for reading.
7716 */
7717#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7718bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
7719#else
7720bool Machine::isSessionSpawning()
7721#endif
7722{
7723 AutoLimitedCaller autoCaller(this);
7724 AssertComRCReturn(autoCaller.rc(), false);
7725
7726 /* just return false for inaccessible machines */
7727 if (autoCaller.state() != Ready)
7728 return false;
7729
7730 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7731
7732 if (mData->mSession.mState == SessionState_Spawning)
7733 {
7734#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7735 /* Additional session data */
7736 if (aPID != NULL)
7737 {
7738 AssertReturn(mData->mSession.mPID != NIL_RTPROCESS, false);
7739 *aPID = mData->mSession.mPID;
7740 }
7741#endif
7742 return true;
7743 }
7744
7745 return false;
7746}
7747
7748/**
7749 * Called from the client watcher thread to check for unexpected client process
7750 * death during Session_Spawning state (e.g. before it successfully opened a
7751 * direct session).
7752 *
7753 * On Win32 and on OS/2, this method is called only when we've got the
7754 * direct client's process termination notification, so it always returns @c
7755 * true.
7756 *
7757 * On other platforms, this method returns @c true if the client process is
7758 * terminated and @c false if it's still alive.
7759 *
7760 * @note Locks this object for writing.
7761 */
7762bool Machine::checkForSpawnFailure()
7763{
7764 AutoCaller autoCaller(this);
7765 if (!autoCaller.isOk())
7766 {
7767 /* nothing to do */
7768 LogFlowThisFunc(("Already uninitialized!\n"));
7769 return true;
7770 }
7771
7772 /* VirtualBox::addProcessToReap() needs a write lock */
7773 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
7774
7775 if (mData->mSession.mState != SessionState_Spawning)
7776 {
7777 /* nothing to do */
7778 LogFlowThisFunc(("Not spawning any more!\n"));
7779 return true;
7780 }
7781
7782 HRESULT rc = S_OK;
7783
7784#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7785
7786 /* the process was already unexpectedly terminated, we just need to set an
7787 * error and finalize session spawning */
7788 rc = setError(E_FAIL,
7789 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
7790 getName().c_str());
7791#else
7792
7793 /* PID not yet initialized, skip check. */
7794 if (mData->mSession.mPID == NIL_RTPROCESS)
7795 return false;
7796
7797 RTPROCSTATUS status;
7798 int vrc = ::RTProcWait(mData->mSession.mPID, RTPROCWAIT_FLAGS_NOBLOCK,
7799 &status);
7800
7801 if (vrc != VERR_PROCESS_RUNNING)
7802 {
7803 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
7804 rc = setError(E_FAIL,
7805 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
7806 getName().c_str(), status.iStatus);
7807 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
7808 rc = setError(E_FAIL,
7809 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
7810 getName().c_str(), status.iStatus);
7811 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
7812 rc = setError(E_FAIL,
7813 tr("The virtual machine '%s' has terminated abnormally"),
7814 getName().c_str(), status.iStatus);
7815 else
7816 rc = setError(E_FAIL,
7817 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
7818 getName().c_str(), rc);
7819 }
7820
7821#endif
7822
7823 if (FAILED(rc))
7824 {
7825 /* Close the remote session, remove the remote control from the list
7826 * and reset session state to Closed (@note keep the code in sync with
7827 * the relevant part in checkForSpawnFailure()). */
7828
7829 Assert(mData->mSession.mRemoteControls.size() == 1);
7830 if (mData->mSession.mRemoteControls.size() == 1)
7831 {
7832 ErrorInfoKeeper eik;
7833 mData->mSession.mRemoteControls.front()->Uninitialize();
7834 }
7835
7836 mData->mSession.mRemoteControls.clear();
7837 mData->mSession.mState = SessionState_Unlocked;
7838
7839 /* finalize the progress after setting the state */
7840 if (!mData->mSession.mProgress.isNull())
7841 {
7842 mData->mSession.mProgress->notifyComplete(rc);
7843 mData->mSession.mProgress.setNull();
7844 }
7845
7846 mParent->addProcessToReap(mData->mSession.mPID);
7847 mData->mSession.mPID = NIL_RTPROCESS;
7848
7849 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
7850 return true;
7851 }
7852
7853 return false;
7854}
7855
7856/**
7857 * Checks whether the machine can be registered. If so, commits and saves
7858 * all settings.
7859 *
7860 * @note Must be called from mParent's write lock. Locks this object and
7861 * children for writing.
7862 */
7863HRESULT Machine::prepareRegister()
7864{
7865 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
7866
7867 AutoLimitedCaller autoCaller(this);
7868 AssertComRCReturnRC(autoCaller.rc());
7869
7870 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7871
7872 /* wait for state dependents to drop to zero */
7873 ensureNoStateDependencies();
7874
7875 if (!mData->mAccessible)
7876 return setError(VBOX_E_INVALID_OBJECT_STATE,
7877 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
7878 mUserData->s.strName.c_str(),
7879 mData->mUuid.toString().c_str());
7880
7881 AssertReturn(autoCaller.state() == Ready, E_FAIL);
7882
7883 if (mData->mRegistered)
7884 return setError(VBOX_E_INVALID_OBJECT_STATE,
7885 tr("The machine '%s' with UUID {%s} is already registered"),
7886 mUserData->s.strName.c_str(),
7887 mData->mUuid.toString().c_str());
7888
7889 HRESULT rc = S_OK;
7890
7891 // Ensure the settings are saved. If we are going to be registered and
7892 // no config file exists yet, create it by calling saveSettings() too.
7893 if ( (mData->flModifications)
7894 || (!mData->pMachineConfigFile->fileExists())
7895 )
7896 {
7897 rc = saveSettings(NULL);
7898 // no need to check whether VirtualBox.xml needs saving too since
7899 // we can't have a machine XML file rename pending
7900 if (FAILED(rc)) return rc;
7901 }
7902
7903 /* more config checking goes here */
7904
7905 if (SUCCEEDED(rc))
7906 {
7907 /* we may have had implicit modifications we want to fix on success */
7908 commit();
7909
7910 mData->mRegistered = true;
7911 }
7912 else
7913 {
7914 /* we may have had implicit modifications we want to cancel on failure*/
7915 rollback(false /* aNotify */);
7916 }
7917
7918 return rc;
7919}
7920
7921/**
7922 * Increases the number of objects dependent on the machine state or on the
7923 * registered state. Guarantees that these two states will not change at least
7924 * until #releaseStateDependency() is called.
7925 *
7926 * Depending on the @a aDepType value, additional state checks may be made.
7927 * These checks will set extended error info on failure. See
7928 * #checkStateDependency() for more info.
7929 *
7930 * If this method returns a failure, the dependency is not added and the caller
7931 * is not allowed to rely on any particular machine state or registration state
7932 * value and may return the failed result code to the upper level.
7933 *
7934 * @param aDepType Dependency type to add.
7935 * @param aState Current machine state (NULL if not interested).
7936 * @param aRegistered Current registered state (NULL if not interested).
7937 *
7938 * @note Locks this object for writing.
7939 */
7940HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
7941 MachineState_T *aState /* = NULL */,
7942 BOOL *aRegistered /* = NULL */)
7943{
7944 AutoCaller autoCaller(this);
7945 AssertComRCReturnRC(autoCaller.rc());
7946
7947 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7948
7949 HRESULT rc = checkStateDependency(aDepType);
7950 if (FAILED(rc)) return rc;
7951
7952 {
7953 if (mData->mMachineStateChangePending != 0)
7954 {
7955 /* ensureNoStateDependencies() is waiting for state dependencies to
7956 * drop to zero so don't add more. It may make sense to wait a bit
7957 * and retry before reporting an error (since the pending state
7958 * transition should be really quick) but let's just assert for
7959 * now to see if it ever happens on practice. */
7960
7961 AssertFailed();
7962
7963 return setError(E_ACCESSDENIED,
7964 tr("Machine state change is in progress. Please retry the operation later."));
7965 }
7966
7967 ++mData->mMachineStateDeps;
7968 Assert(mData->mMachineStateDeps != 0 /* overflow */);
7969 }
7970
7971 if (aState)
7972 *aState = mData->mMachineState;
7973 if (aRegistered)
7974 *aRegistered = mData->mRegistered;
7975
7976 return S_OK;
7977}
7978
7979/**
7980 * Decreases the number of objects dependent on the machine state.
7981 * Must always complete the #addStateDependency() call after the state
7982 * dependency is no more necessary.
7983 */
7984void Machine::releaseStateDependency()
7985{
7986 AutoCaller autoCaller(this);
7987 AssertComRCReturnVoid(autoCaller.rc());
7988
7989 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7990
7991 /* releaseStateDependency() w/o addStateDependency()? */
7992 AssertReturnVoid(mData->mMachineStateDeps != 0);
7993 -- mData->mMachineStateDeps;
7994
7995 if (mData->mMachineStateDeps == 0)
7996 {
7997 /* inform ensureNoStateDependencies() that there are no more deps */
7998 if (mData->mMachineStateChangePending != 0)
7999 {
8000 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
8001 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
8002 }
8003 }
8004}
8005
8006Utf8Str Machine::getExtraData(const Utf8Str &strKey)
8007{
8008 /* start with nothing found */
8009 Utf8Str strResult("");
8010
8011 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8012
8013 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
8014 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
8015 // found:
8016 strResult = it->second; // source is a Utf8Str
8017
8018 return strResult;
8019}
8020
8021// protected methods
8022/////////////////////////////////////////////////////////////////////////////
8023
8024/**
8025 * Performs machine state checks based on the @a aDepType value. If a check
8026 * fails, this method will set extended error info, otherwise it will return
8027 * S_OK. It is supposed, that on failure, the caller will immediately return
8028 * the return value of this method to the upper level.
8029 *
8030 * When @a aDepType is AnyStateDep, this method always returns S_OK.
8031 *
8032 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
8033 * current state of this machine object allows to change settings of the
8034 * machine (i.e. the machine is not registered, or registered but not running
8035 * and not saved). It is useful to call this method from Machine setters
8036 * before performing any change.
8037 *
8038 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
8039 * as for MutableStateDep except that if the machine is saved, S_OK is also
8040 * returned. This is useful in setters which allow changing machine
8041 * properties when it is in the saved state.
8042 *
8043 * When @a aDepType is OfflineStateDep, this method returns S_OK if the
8044 * state is one of the 4 offline states (PoweredOff, Saved, Teleported,
8045 * Aborted).
8046 *
8047 * @param aDepType Dependency type to check.
8048 *
8049 * @note Non Machine based classes should use #addStateDependency() and
8050 * #releaseStateDependency() methods or the smart AutoStateDependency
8051 * template.
8052 *
8053 * @note This method must be called from under this object's read or write
8054 * lock.
8055 */
8056HRESULT Machine::checkStateDependency(StateDependency aDepType)
8057{
8058 switch (aDepType)
8059 {
8060 case AnyStateDep:
8061 {
8062 break;
8063 }
8064 case MutableStateDep:
8065 {
8066 if ( mData->mRegistered
8067 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
8068 || ( mData->mMachineState != MachineState_Paused
8069 && mData->mMachineState != MachineState_Running
8070 && mData->mMachineState != MachineState_Aborted
8071 && mData->mMachineState != MachineState_Teleported
8072 && mData->mMachineState != MachineState_PoweredOff
8073 )
8074 )
8075 )
8076 return setError(VBOX_E_INVALID_VM_STATE,
8077 tr("The machine is not mutable (state is %s)"),
8078 Global::stringifyMachineState(mData->mMachineState));
8079 break;
8080 }
8081 case MutableOrSavedStateDep:
8082 {
8083 if ( mData->mRegistered
8084 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
8085 || ( mData->mMachineState != MachineState_Paused
8086 && mData->mMachineState != MachineState_Running
8087 && mData->mMachineState != MachineState_Aborted
8088 && mData->mMachineState != MachineState_Teleported
8089 && mData->mMachineState != MachineState_Saved
8090 && mData->mMachineState != MachineState_PoweredOff
8091 )
8092 )
8093 )
8094 return setError(VBOX_E_INVALID_VM_STATE,
8095 tr("The machine is not mutable (state is %s)"),
8096 Global::stringifyMachineState(mData->mMachineState));
8097 break;
8098 }
8099 case OfflineStateDep:
8100 {
8101 if ( mData->mRegistered
8102 && ( !isSessionMachine()
8103 || ( mData->mMachineState != MachineState_PoweredOff
8104 && mData->mMachineState != MachineState_Saved
8105 && mData->mMachineState != MachineState_Aborted
8106 && mData->mMachineState != MachineState_Teleported
8107 )
8108 )
8109 )
8110 return setError(VBOX_E_INVALID_VM_STATE,
8111 tr("The machine is not offline (state is %s)"),
8112 Global::stringifyMachineState(mData->mMachineState));
8113 break;
8114 }
8115 }
8116
8117 return S_OK;
8118}
8119
8120/**
8121 * Helper to initialize all associated child objects and allocate data
8122 * structures.
8123 *
8124 * This method must be called as a part of the object's initialization procedure
8125 * (usually done in the #init() method).
8126 *
8127 * @note Must be called only from #init() or from #registeredInit().
8128 */
8129HRESULT Machine::initDataAndChildObjects()
8130{
8131 AutoCaller autoCaller(this);
8132 AssertComRCReturnRC(autoCaller.rc());
8133 AssertComRCReturn(autoCaller.state() == InInit ||
8134 autoCaller.state() == Limited, E_FAIL);
8135
8136 AssertReturn(!mData->mAccessible, E_FAIL);
8137
8138 /* allocate data structures */
8139 mSSData.allocate();
8140 mUserData.allocate();
8141 mHWData.allocate();
8142 mMediaData.allocate();
8143 mStorageControllers.allocate();
8144
8145 /* initialize mOSTypeId */
8146 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
8147
8148 /* create associated BIOS settings object */
8149 unconst(mBIOSSettings).createObject();
8150 mBIOSSettings->init(this);
8151
8152 /* create an associated VRDE object (default is disabled) */
8153 unconst(mVRDEServer).createObject();
8154 mVRDEServer->init(this);
8155
8156 /* create associated serial port objects */
8157 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
8158 {
8159 unconst(mSerialPorts[slot]).createObject();
8160 mSerialPorts[slot]->init(this, slot);
8161 }
8162
8163 /* create associated parallel port objects */
8164 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
8165 {
8166 unconst(mParallelPorts[slot]).createObject();
8167 mParallelPorts[slot]->init(this, slot);
8168 }
8169
8170 /* create the audio adapter object (always present, default is disabled) */
8171 unconst(mAudioAdapter).createObject();
8172 mAudioAdapter->init(this);
8173
8174 /* create the USB controller object (always present, default is disabled) */
8175 unconst(mUSBController).createObject();
8176 mUSBController->init(this);
8177
8178 /* create associated network adapter objects */
8179 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
8180 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
8181 {
8182 unconst(mNetworkAdapters[slot]).createObject();
8183 mNetworkAdapters[slot]->init(this, slot);
8184 }
8185
8186 /* create the bandwidth control */
8187 unconst(mBandwidthControl).createObject();
8188 mBandwidthControl->init(this);
8189
8190 return S_OK;
8191}
8192
8193/**
8194 * Helper to uninitialize all associated child objects and to free all data
8195 * structures.
8196 *
8197 * This method must be called as a part of the object's uninitialization
8198 * procedure (usually done in the #uninit() method).
8199 *
8200 * @note Must be called only from #uninit() or from #registeredInit().
8201 */
8202void Machine::uninitDataAndChildObjects()
8203{
8204 AutoCaller autoCaller(this);
8205 AssertComRCReturnVoid(autoCaller.rc());
8206 AssertComRCReturnVoid( autoCaller.state() == InUninit
8207 || autoCaller.state() == Limited);
8208
8209 /* tell all our other child objects we've been uninitialized */
8210 if (mBandwidthControl)
8211 {
8212 mBandwidthControl->uninit();
8213 unconst(mBandwidthControl).setNull();
8214 }
8215
8216 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
8217 {
8218 if (mNetworkAdapters[slot])
8219 {
8220 mNetworkAdapters[slot]->uninit();
8221 unconst(mNetworkAdapters[slot]).setNull();
8222 }
8223 }
8224
8225 if (mUSBController)
8226 {
8227 mUSBController->uninit();
8228 unconst(mUSBController).setNull();
8229 }
8230
8231 if (mAudioAdapter)
8232 {
8233 mAudioAdapter->uninit();
8234 unconst(mAudioAdapter).setNull();
8235 }
8236
8237 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
8238 {
8239 if (mParallelPorts[slot])
8240 {
8241 mParallelPorts[slot]->uninit();
8242 unconst(mParallelPorts[slot]).setNull();
8243 }
8244 }
8245
8246 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
8247 {
8248 if (mSerialPorts[slot])
8249 {
8250 mSerialPorts[slot]->uninit();
8251 unconst(mSerialPorts[slot]).setNull();
8252 }
8253 }
8254
8255 if (mVRDEServer)
8256 {
8257 mVRDEServer->uninit();
8258 unconst(mVRDEServer).setNull();
8259 }
8260
8261 if (mBIOSSettings)
8262 {
8263 mBIOSSettings->uninit();
8264 unconst(mBIOSSettings).setNull();
8265 }
8266
8267 /* Deassociate media (only when a real Machine or a SnapshotMachine
8268 * instance is uninitialized; SessionMachine instances refer to real
8269 * Machine media). This is necessary for a clean re-initialization of
8270 * the VM after successfully re-checking the accessibility state. Note
8271 * that in case of normal Machine or SnapshotMachine uninitialization (as
8272 * a result of unregistering or deleting the snapshot), outdated media
8273 * attachments will already be uninitialized and deleted, so this
8274 * code will not affect them. */
8275 if ( !!mMediaData
8276 && (!isSessionMachine())
8277 )
8278 {
8279 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8280 it != mMediaData->mAttachments.end();
8281 ++it)
8282 {
8283 ComObjPtr<Medium> pMedium = (*it)->getMedium();
8284 if (pMedium.isNull())
8285 continue;
8286 HRESULT rc = pMedium->removeBackReference(mData->mUuid, getSnapshotId());
8287 AssertComRC(rc);
8288 }
8289 }
8290
8291 if (!isSessionMachine() && !isSnapshotMachine())
8292 {
8293 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
8294 if (mData->mFirstSnapshot)
8295 {
8296 // snapshots tree is protected by machine write lock; strictly
8297 // this isn't necessary here since we're deleting the entire
8298 // machine, but otherwise we assert in Snapshot::uninit()
8299 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8300 mData->mFirstSnapshot->uninit();
8301 mData->mFirstSnapshot.setNull();
8302 }
8303
8304 mData->mCurrentSnapshot.setNull();
8305 }
8306
8307 /* free data structures (the essential mData structure is not freed here
8308 * since it may be still in use) */
8309 mMediaData.free();
8310 mStorageControllers.free();
8311 mHWData.free();
8312 mUserData.free();
8313 mSSData.free();
8314}
8315
8316/**
8317 * Returns a pointer to the Machine object for this machine that acts like a
8318 * parent for complex machine data objects such as shared folders, etc.
8319 *
8320 * For primary Machine objects and for SnapshotMachine objects, returns this
8321 * object's pointer itself. For SessionMachine objects, returns the peer
8322 * (primary) machine pointer.
8323 */
8324Machine* Machine::getMachine()
8325{
8326 if (isSessionMachine())
8327 return (Machine*)mPeer;
8328 return this;
8329}
8330
8331/**
8332 * Makes sure that there are no machine state dependents. If necessary, waits
8333 * for the number of dependents to drop to zero.
8334 *
8335 * Make sure this method is called from under this object's write lock to
8336 * guarantee that no new dependents may be added when this method returns
8337 * control to the caller.
8338 *
8339 * @note Locks this object for writing. The lock will be released while waiting
8340 * (if necessary).
8341 *
8342 * @warning To be used only in methods that change the machine state!
8343 */
8344void Machine::ensureNoStateDependencies()
8345{
8346 AssertReturnVoid(isWriteLockOnCurrentThread());
8347
8348 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8349
8350 /* Wait for all state dependents if necessary */
8351 if (mData->mMachineStateDeps != 0)
8352 {
8353 /* lazy semaphore creation */
8354 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
8355 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
8356
8357 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
8358 mData->mMachineStateDeps));
8359
8360 ++mData->mMachineStateChangePending;
8361
8362 /* reset the semaphore before waiting, the last dependent will signal
8363 * it */
8364 RTSemEventMultiReset(mData->mMachineStateDepsSem);
8365
8366 alock.release();
8367
8368 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
8369
8370 alock.acquire();
8371
8372 -- mData->mMachineStateChangePending;
8373 }
8374}
8375
8376/**
8377 * Changes the machine state and informs callbacks.
8378 *
8379 * This method is not intended to fail so it either returns S_OK or asserts (and
8380 * returns a failure).
8381 *
8382 * @note Locks this object for writing.
8383 */
8384HRESULT Machine::setMachineState(MachineState_T aMachineState)
8385{
8386 LogFlowThisFuncEnter();
8387 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
8388
8389 AutoCaller autoCaller(this);
8390 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8391
8392 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8393
8394 /* wait for state dependents to drop to zero */
8395 ensureNoStateDependencies();
8396
8397 if (mData->mMachineState != aMachineState)
8398 {
8399 mData->mMachineState = aMachineState;
8400
8401 RTTimeNow(&mData->mLastStateChange);
8402
8403 mParent->onMachineStateChange(mData->mUuid, aMachineState);
8404 }
8405
8406 LogFlowThisFuncLeave();
8407 return S_OK;
8408}
8409
8410/**
8411 * Searches for a shared folder with the given logical name
8412 * in the collection of shared folders.
8413 *
8414 * @param aName logical name of the shared folder
8415 * @param aSharedFolder where to return the found object
8416 * @param aSetError whether to set the error info if the folder is
8417 * not found
8418 * @return
8419 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
8420 *
8421 * @note
8422 * must be called from under the object's lock!
8423 */
8424HRESULT Machine::findSharedFolder(const Utf8Str &aName,
8425 ComObjPtr<SharedFolder> &aSharedFolder,
8426 bool aSetError /* = false */)
8427{
8428 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
8429 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8430 it != mHWData->mSharedFolders.end();
8431 ++it)
8432 {
8433 SharedFolder *pSF = *it;
8434 AutoCaller autoCaller(pSF);
8435 if (pSF->getName() == aName)
8436 {
8437 aSharedFolder = pSF;
8438 rc = S_OK;
8439 break;
8440 }
8441 }
8442
8443 if (aSetError && FAILED(rc))
8444 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
8445
8446 return rc;
8447}
8448
8449/**
8450 * Initializes all machine instance data from the given settings structures
8451 * from XML. The exception is the machine UUID which needs special handling
8452 * depending on the caller's use case, so the caller needs to set that herself.
8453 *
8454 * This gets called in several contexts during machine initialization:
8455 *
8456 * -- When machine XML exists on disk already and needs to be loaded into memory,
8457 * for example, from registeredInit() to load all registered machines on
8458 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
8459 * attached to the machine should be part of some media registry already.
8460 *
8461 * -- During OVF import, when a machine config has been constructed from an
8462 * OVF file. In this case, puuidRegistry is set to the machine UUID to
8463 * ensure that the media listed as attachments in the config (which have
8464 * been imported from the OVF) receive the correct registry ID.
8465 *
8466 * -- During VM cloning.
8467 *
8468 * @param config Machine settings from XML.
8469 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
8470 * @return
8471 */
8472HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
8473 const Guid *puuidRegistry)
8474{
8475 // copy name, description, OS type, teleporter, UTC etc.
8476 mUserData->s = config.machineUserData;
8477
8478 // look up the object by Id to check it is valid
8479 ComPtr<IGuestOSType> guestOSType;
8480 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
8481 guestOSType.asOutParam());
8482 if (FAILED(rc)) return rc;
8483
8484 // stateFile (optional)
8485 if (config.strStateFile.isEmpty())
8486 mSSData->strStateFilePath.setNull();
8487 else
8488 {
8489 Utf8Str stateFilePathFull(config.strStateFile);
8490 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
8491 if (RT_FAILURE(vrc))
8492 return setError(E_FAIL,
8493 tr("Invalid saved state file path '%s' (%Rrc)"),
8494 config.strStateFile.c_str(),
8495 vrc);
8496 mSSData->strStateFilePath = stateFilePathFull;
8497 }
8498
8499 // snapshot folder needs special processing so set it again
8500 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
8501 if (FAILED(rc)) return rc;
8502
8503 /* Copy the extra data items (Not in any case config is already the same as
8504 * mData->pMachineConfigFile, like when the xml files are read from disk. So
8505 * make sure the extra data map is copied). */
8506 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
8507
8508 /* currentStateModified (optional, default is true) */
8509 mData->mCurrentStateModified = config.fCurrentStateModified;
8510
8511 mData->mLastStateChange = config.timeLastStateChange;
8512
8513 /*
8514 * note: all mUserData members must be assigned prior this point because
8515 * we need to commit changes in order to let mUserData be shared by all
8516 * snapshot machine instances.
8517 */
8518 mUserData.commitCopy();
8519
8520 // machine registry, if present (must be loaded before snapshots)
8521 if (config.canHaveOwnMediaRegistry())
8522 {
8523 // determine machine folder
8524 Utf8Str strMachineFolder = getSettingsFileFull();
8525 strMachineFolder.stripFilename();
8526 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
8527 config.mediaRegistry,
8528 strMachineFolder);
8529 if (FAILED(rc)) return rc;
8530 }
8531
8532 /* Snapshot node (optional) */
8533 size_t cRootSnapshots;
8534 if ((cRootSnapshots = config.llFirstSnapshot.size()))
8535 {
8536 // there must be only one root snapshot
8537 Assert(cRootSnapshots == 1);
8538
8539 const settings::Snapshot &snap = config.llFirstSnapshot.front();
8540
8541 rc = loadSnapshot(snap,
8542 config.uuidCurrentSnapshot,
8543 NULL); // no parent == first snapshot
8544 if (FAILED(rc)) return rc;
8545 }
8546
8547 // hardware data
8548 rc = loadHardware(config.hardwareMachine, &config.debugging, &config.autostart);
8549 if (FAILED(rc)) return rc;
8550
8551 // load storage controllers
8552 rc = loadStorageControllers(config.storageMachine,
8553 puuidRegistry,
8554 NULL /* puuidSnapshot */);
8555 if (FAILED(rc)) return rc;
8556
8557 /*
8558 * NOTE: the assignment below must be the last thing to do,
8559 * otherwise it will be not possible to change the settings
8560 * somewhere in the code above because all setters will be
8561 * blocked by checkStateDependency(MutableStateDep).
8562 */
8563
8564 /* set the machine state to Aborted or Saved when appropriate */
8565 if (config.fAborted)
8566 {
8567 mSSData->strStateFilePath.setNull();
8568
8569 /* no need to use setMachineState() during init() */
8570 mData->mMachineState = MachineState_Aborted;
8571 }
8572 else if (!mSSData->strStateFilePath.isEmpty())
8573 {
8574 /* no need to use setMachineState() during init() */
8575 mData->mMachineState = MachineState_Saved;
8576 }
8577
8578 // after loading settings, we are no longer different from the XML on disk
8579 mData->flModifications = 0;
8580
8581 return S_OK;
8582}
8583
8584/**
8585 * Recursively loads all snapshots starting from the given.
8586 *
8587 * @param aNode <Snapshot> node.
8588 * @param aCurSnapshotId Current snapshot ID from the settings file.
8589 * @param aParentSnapshot Parent snapshot.
8590 */
8591HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
8592 const Guid &aCurSnapshotId,
8593 Snapshot *aParentSnapshot)
8594{
8595 AssertReturn(!isSnapshotMachine(), E_FAIL);
8596 AssertReturn(!isSessionMachine(), E_FAIL);
8597
8598 HRESULT rc = S_OK;
8599
8600 Utf8Str strStateFile;
8601 if (!data.strStateFile.isEmpty())
8602 {
8603 /* optional */
8604 strStateFile = data.strStateFile;
8605 int vrc = calculateFullPath(strStateFile, strStateFile);
8606 if (RT_FAILURE(vrc))
8607 return setError(E_FAIL,
8608 tr("Invalid saved state file path '%s' (%Rrc)"),
8609 strStateFile.c_str(),
8610 vrc);
8611 }
8612
8613 /* create a snapshot machine object */
8614 ComObjPtr<SnapshotMachine> pSnapshotMachine;
8615 pSnapshotMachine.createObject();
8616 rc = pSnapshotMachine->initFromSettings(this,
8617 data.hardware,
8618 &data.debugging,
8619 &data.autostart,
8620 data.storage,
8621 data.uuid.ref(),
8622 strStateFile);
8623 if (FAILED(rc)) return rc;
8624
8625 /* create a snapshot object */
8626 ComObjPtr<Snapshot> pSnapshot;
8627 pSnapshot.createObject();
8628 /* initialize the snapshot */
8629 rc = pSnapshot->init(mParent, // VirtualBox object
8630 data.uuid,
8631 data.strName,
8632 data.strDescription,
8633 data.timestamp,
8634 pSnapshotMachine,
8635 aParentSnapshot);
8636 if (FAILED(rc)) return rc;
8637
8638 /* memorize the first snapshot if necessary */
8639 if (!mData->mFirstSnapshot)
8640 mData->mFirstSnapshot = pSnapshot;
8641
8642 /* memorize the current snapshot when appropriate */
8643 if ( !mData->mCurrentSnapshot
8644 && pSnapshot->getId() == aCurSnapshotId
8645 )
8646 mData->mCurrentSnapshot = pSnapshot;
8647
8648 // now create the children
8649 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
8650 it != data.llChildSnapshots.end();
8651 ++it)
8652 {
8653 const settings::Snapshot &childData = *it;
8654 // recurse
8655 rc = loadSnapshot(childData,
8656 aCurSnapshotId,
8657 pSnapshot); // parent = the one we created above
8658 if (FAILED(rc)) return rc;
8659 }
8660
8661 return rc;
8662}
8663
8664/**
8665 * Loads settings into mHWData.
8666 *
8667 * @param data Reference to the hardware settings.
8668 * @param pDbg Pointer to the debugging settings.
8669 * @param pAutostart Pointer to the autostart settings.
8670 */
8671HRESULT Machine::loadHardware(const settings::Hardware &data, const settings::Debugging *pDbg,
8672 const settings::Autostart *pAutostart)
8673{
8674 AssertReturn(!isSessionMachine(), E_FAIL);
8675
8676 HRESULT rc = S_OK;
8677
8678 try
8679 {
8680 /* The hardware version attribute (optional). */
8681 mHWData->mHWVersion = data.strVersion;
8682 mHWData->mHardwareUUID = data.uuid;
8683
8684 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
8685 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
8686 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
8687 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
8688 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
8689 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
8690 mHWData->mPAEEnabled = data.fPAE;
8691 mHWData->mSyntheticCpu = data.fSyntheticCpu;
8692 mHWData->mLongMode = data.enmLongMode;
8693 mHWData->mCPUCount = data.cCPUs;
8694 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
8695 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
8696
8697 // cpu
8698 if (mHWData->mCPUHotPlugEnabled)
8699 {
8700 for (settings::CpuList::const_iterator it = data.llCpus.begin();
8701 it != data.llCpus.end();
8702 ++it)
8703 {
8704 const settings::Cpu &cpu = *it;
8705
8706 mHWData->mCPUAttached[cpu.ulId] = true;
8707 }
8708 }
8709
8710 // cpuid leafs
8711 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
8712 it != data.llCpuIdLeafs.end();
8713 ++it)
8714 {
8715 const settings::CpuIdLeaf &leaf = *it;
8716
8717 switch (leaf.ulId)
8718 {
8719 case 0x0:
8720 case 0x1:
8721 case 0x2:
8722 case 0x3:
8723 case 0x4:
8724 case 0x5:
8725 case 0x6:
8726 case 0x7:
8727 case 0x8:
8728 case 0x9:
8729 case 0xA:
8730 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
8731 break;
8732
8733 case 0x80000000:
8734 case 0x80000001:
8735 case 0x80000002:
8736 case 0x80000003:
8737 case 0x80000004:
8738 case 0x80000005:
8739 case 0x80000006:
8740 case 0x80000007:
8741 case 0x80000008:
8742 case 0x80000009:
8743 case 0x8000000A:
8744 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
8745 break;
8746
8747 default:
8748 /* just ignore */
8749 break;
8750 }
8751 }
8752
8753 mHWData->mMemorySize = data.ulMemorySizeMB;
8754 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
8755
8756 // boot order
8757 for (size_t i = 0;
8758 i < RT_ELEMENTS(mHWData->mBootOrder);
8759 i++)
8760 {
8761 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
8762 if (it == data.mapBootOrder.end())
8763 mHWData->mBootOrder[i] = DeviceType_Null;
8764 else
8765 mHWData->mBootOrder[i] = it->second;
8766 }
8767
8768 mHWData->mGraphicsControllerType = data.graphicsControllerType;
8769 mHWData->mVRAMSize = data.ulVRAMSizeMB;
8770 mHWData->mMonitorCount = data.cMonitors;
8771 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
8772 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
8773 mHWData->mVideoCaptureWidth = data.ulVideoCaptureHorzRes;
8774 mHWData->mVideoCaptureHeight = data.ulVideoCaptureVertRes;
8775 mHWData->mVideoCaptureEnabled = false; /* @todo r=klaus restore to data.fVideoCaptureEnabled */
8776 mHWData->mVideoCaptureFile = data.strVideoCaptureFile;
8777 mHWData->mFirmwareType = data.firmwareType;
8778 mHWData->mPointingHIDType = data.pointingHIDType;
8779 mHWData->mKeyboardHIDType = data.keyboardHIDType;
8780 mHWData->mChipsetType = data.chipsetType;
8781 mHWData->mEmulatedUSBWebcamEnabled = data.fEmulatedUSBWebcam;
8782 mHWData->mEmulatedUSBCardReaderEnabled = data.fEmulatedUSBCardReader;
8783 mHWData->mHPETEnabled = data.fHPETEnabled;
8784
8785 /* VRDEServer */
8786 rc = mVRDEServer->loadSettings(data.vrdeSettings);
8787 if (FAILED(rc)) return rc;
8788
8789 /* BIOS */
8790 rc = mBIOSSettings->loadSettings(data.biosSettings);
8791 if (FAILED(rc)) return rc;
8792
8793 // Bandwidth control (must come before network adapters)
8794 rc = mBandwidthControl->loadSettings(data.ioSettings);
8795 if (FAILED(rc)) return rc;
8796
8797 /* USB Controller */
8798 rc = mUSBController->loadSettings(data.usbController);
8799 if (FAILED(rc)) return rc;
8800
8801 // network adapters
8802 uint32_t newCount = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
8803 uint32_t oldCount = mNetworkAdapters.size();
8804 if (newCount > oldCount)
8805 {
8806 mNetworkAdapters.resize(newCount);
8807 for (ULONG slot = oldCount; slot < mNetworkAdapters.size(); slot++)
8808 {
8809 unconst(mNetworkAdapters[slot]).createObject();
8810 mNetworkAdapters[slot]->init(this, slot);
8811 }
8812 }
8813 else if (newCount < oldCount)
8814 mNetworkAdapters.resize(newCount);
8815 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
8816 it != data.llNetworkAdapters.end();
8817 ++it)
8818 {
8819 const settings::NetworkAdapter &nic = *it;
8820
8821 /* slot unicity is guaranteed by XML Schema */
8822 AssertBreak(nic.ulSlot < mNetworkAdapters.size());
8823 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
8824 if (FAILED(rc)) return rc;
8825 }
8826
8827 // serial ports
8828 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
8829 it != data.llSerialPorts.end();
8830 ++it)
8831 {
8832 const settings::SerialPort &s = *it;
8833
8834 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
8835 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
8836 if (FAILED(rc)) return rc;
8837 }
8838
8839 // parallel ports (optional)
8840 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
8841 it != data.llParallelPorts.end();
8842 ++it)
8843 {
8844 const settings::ParallelPort &p = *it;
8845
8846 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
8847 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
8848 if (FAILED(rc)) return rc;
8849 }
8850
8851 /* AudioAdapter */
8852 rc = mAudioAdapter->loadSettings(data.audioAdapter);
8853 if (FAILED(rc)) return rc;
8854
8855 /* Shared folders */
8856 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
8857 it != data.llSharedFolders.end();
8858 ++it)
8859 {
8860 const settings::SharedFolder &sf = *it;
8861
8862 ComObjPtr<SharedFolder> sharedFolder;
8863 /* Check for double entries. Not allowed! */
8864 rc = findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
8865 if (SUCCEEDED(rc))
8866 return setError(VBOX_E_OBJECT_IN_USE,
8867 tr("Shared folder named '%s' already exists"),
8868 sf.strName.c_str());
8869
8870 /* Create the new shared folder. Don't break on error. This will be
8871 * reported when the machine starts. */
8872 sharedFolder.createObject();
8873 rc = sharedFolder->init(getMachine(),
8874 sf.strName,
8875 sf.strHostPath,
8876 RT_BOOL(sf.fWritable),
8877 RT_BOOL(sf.fAutoMount),
8878 false /* fFailOnError */);
8879 if (FAILED(rc)) return rc;
8880 mHWData->mSharedFolders.push_back(sharedFolder);
8881 }
8882
8883 // Clipboard
8884 mHWData->mClipboardMode = data.clipboardMode;
8885
8886 // drag'n'drop
8887 mHWData->mDragAndDropMode = data.dragAndDropMode;
8888
8889 // guest settings
8890 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
8891
8892 // IO settings
8893 mHWData->mIOCacheEnabled = data.ioSettings.fIOCacheEnabled;
8894 mHWData->mIOCacheSize = data.ioSettings.ulIOCacheSize;
8895
8896 // Host PCI devices
8897 for (settings::HostPCIDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
8898 it != data.pciAttachments.end();
8899 ++it)
8900 {
8901 const settings::HostPCIDeviceAttachment &hpda = *it;
8902 ComObjPtr<PCIDeviceAttachment> pda;
8903
8904 pda.createObject();
8905 pda->loadSettings(this, hpda);
8906 mHWData->mPCIDeviceAssignments.push_back(pda);
8907 }
8908
8909 /*
8910 * (The following isn't really real hardware, but it lives in HWData
8911 * for reasons of convenience.)
8912 */
8913
8914#ifdef VBOX_WITH_GUEST_PROPS
8915 /* Guest properties (optional) */
8916 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
8917 it != data.llGuestProperties.end();
8918 ++it)
8919 {
8920 const settings::GuestProperty &prop = *it;
8921 uint32_t fFlags = guestProp::NILFLAG;
8922 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
8923 HWData::GuestProperty property = { prop.strValue, (LONG64) prop.timestamp, fFlags };
8924 mHWData->mGuestProperties[prop.strName] = property;
8925 }
8926
8927 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
8928#endif /* VBOX_WITH_GUEST_PROPS defined */
8929
8930 rc = loadDebugging(pDbg);
8931 if (FAILED(rc))
8932 return rc;
8933
8934 mHWData->mAutostart = *pAutostart;
8935
8936 /* default frontend */
8937 mHWData->mDefaultFrontend = data.strDefaultFrontend;
8938 }
8939 catch(std::bad_alloc &)
8940 {
8941 return E_OUTOFMEMORY;
8942 }
8943
8944 AssertComRC(rc);
8945 return rc;
8946}
8947
8948/**
8949 * Called from Machine::loadHardware() to load the debugging settings of the
8950 * machine.
8951 *
8952 * @param pDbg Pointer to the settings.
8953 */
8954HRESULT Machine::loadDebugging(const settings::Debugging *pDbg)
8955{
8956 mHWData->mDebugging = *pDbg;
8957 /* no more processing currently required, this will probably change. */
8958 return S_OK;
8959}
8960
8961/**
8962 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
8963 *
8964 * @param data
8965 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
8966 * @param puuidSnapshot
8967 * @return
8968 */
8969HRESULT Machine::loadStorageControllers(const settings::Storage &data,
8970 const Guid *puuidRegistry,
8971 const Guid *puuidSnapshot)
8972{
8973 AssertReturn(!isSessionMachine(), E_FAIL);
8974
8975 HRESULT rc = S_OK;
8976
8977 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
8978 it != data.llStorageControllers.end();
8979 ++it)
8980 {
8981 const settings::StorageController &ctlData = *it;
8982
8983 ComObjPtr<StorageController> pCtl;
8984 /* Try to find one with the name first. */
8985 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
8986 if (SUCCEEDED(rc))
8987 return setError(VBOX_E_OBJECT_IN_USE,
8988 tr("Storage controller named '%s' already exists"),
8989 ctlData.strName.c_str());
8990
8991 pCtl.createObject();
8992 rc = pCtl->init(this,
8993 ctlData.strName,
8994 ctlData.storageBus,
8995 ctlData.ulInstance,
8996 ctlData.fBootable);
8997 if (FAILED(rc)) return rc;
8998
8999 mStorageControllers->push_back(pCtl);
9000
9001 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
9002 if (FAILED(rc)) return rc;
9003
9004 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
9005 if (FAILED(rc)) return rc;
9006
9007 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
9008 if (FAILED(rc)) return rc;
9009
9010 /* Set IDE emulation settings (only for AHCI controller). */
9011 if (ctlData.controllerType == StorageControllerType_IntelAhci)
9012 {
9013 if ( (FAILED(rc = pCtl->setIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
9014 || (FAILED(rc = pCtl->setIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
9015 || (FAILED(rc = pCtl->setIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
9016 || (FAILED(rc = pCtl->setIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
9017 )
9018 return rc;
9019 }
9020
9021 /* Load the attached devices now. */
9022 rc = loadStorageDevices(pCtl,
9023 ctlData,
9024 puuidRegistry,
9025 puuidSnapshot);
9026 if (FAILED(rc)) return rc;
9027 }
9028
9029 return S_OK;
9030}
9031
9032/**
9033 * Called from loadStorageControllers for a controller's devices.
9034 *
9035 * @param aStorageController
9036 * @param data
9037 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
9038 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
9039 * @return
9040 */
9041HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
9042 const settings::StorageController &data,
9043 const Guid *puuidRegistry,
9044 const Guid *puuidSnapshot)
9045{
9046 HRESULT rc = S_OK;
9047
9048 /* paranoia: detect duplicate attachments */
9049 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
9050 it != data.llAttachedDevices.end();
9051 ++it)
9052 {
9053 const settings::AttachedDevice &ad = *it;
9054
9055 for (settings::AttachedDevicesList::const_iterator it2 = it;
9056 it2 != data.llAttachedDevices.end();
9057 ++it2)
9058 {
9059 if (it == it2)
9060 continue;
9061
9062 const settings::AttachedDevice &ad2 = *it2;
9063
9064 if ( ad.lPort == ad2.lPort
9065 && ad.lDevice == ad2.lDevice)
9066 {
9067 return setError(E_FAIL,
9068 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
9069 aStorageController->getName().c_str(),
9070 ad.lPort,
9071 ad.lDevice,
9072 mUserData->s.strName.c_str());
9073 }
9074 }
9075 }
9076
9077 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
9078 it != data.llAttachedDevices.end();
9079 ++it)
9080 {
9081 const settings::AttachedDevice &dev = *it;
9082 ComObjPtr<Medium> medium;
9083
9084 switch (dev.deviceType)
9085 {
9086 case DeviceType_Floppy:
9087 case DeviceType_DVD:
9088 if (dev.strHostDriveSrc.isNotEmpty())
9089 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
9090 else
9091 rc = mParent->findRemoveableMedium(dev.deviceType,
9092 dev.uuid,
9093 false /* fRefresh */,
9094 false /* aSetError */,
9095 medium);
9096 if (rc == VBOX_E_OBJECT_NOT_FOUND)
9097 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
9098 rc = S_OK;
9099 break;
9100
9101 case DeviceType_HardDisk:
9102 {
9103 /* find a hard disk by UUID */
9104 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
9105 if (FAILED(rc))
9106 {
9107 if (isSnapshotMachine())
9108 {
9109 // wrap another error message around the "cannot find hard disk" set by findHardDisk
9110 // so the user knows that the bad disk is in a snapshot somewhere
9111 com::ErrorInfo info;
9112 return setError(E_FAIL,
9113 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
9114 puuidSnapshot->raw(),
9115 info.getText().raw());
9116 }
9117 else
9118 return rc;
9119 }
9120
9121 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
9122
9123 if (medium->getType() == MediumType_Immutable)
9124 {
9125 if (isSnapshotMachine())
9126 return setError(E_FAIL,
9127 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9128 "of the virtual machine '%s' ('%s')"),
9129 medium->getLocationFull().c_str(),
9130 dev.uuid.raw(),
9131 puuidSnapshot->raw(),
9132 mUserData->s.strName.c_str(),
9133 mData->m_strConfigFileFull.c_str());
9134
9135 return setError(E_FAIL,
9136 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9137 medium->getLocationFull().c_str(),
9138 dev.uuid.raw(),
9139 mUserData->s.strName.c_str(),
9140 mData->m_strConfigFileFull.c_str());
9141 }
9142
9143 if (medium->getType() == MediumType_MultiAttach)
9144 {
9145 if (isSnapshotMachine())
9146 return setError(E_FAIL,
9147 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
9148 "of the virtual machine '%s' ('%s')"),
9149 medium->getLocationFull().c_str(),
9150 dev.uuid.raw(),
9151 puuidSnapshot->raw(),
9152 mUserData->s.strName.c_str(),
9153 mData->m_strConfigFileFull.c_str());
9154
9155 return setError(E_FAIL,
9156 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
9157 medium->getLocationFull().c_str(),
9158 dev.uuid.raw(),
9159 mUserData->s.strName.c_str(),
9160 mData->m_strConfigFileFull.c_str());
9161 }
9162
9163 if ( !isSnapshotMachine()
9164 && medium->getChildren().size() != 0
9165 )
9166 return setError(E_FAIL,
9167 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
9168 "because it has %d differencing child hard disks"),
9169 medium->getLocationFull().c_str(),
9170 dev.uuid.raw(),
9171 mUserData->s.strName.c_str(),
9172 mData->m_strConfigFileFull.c_str(),
9173 medium->getChildren().size());
9174
9175 if (findAttachment(mMediaData->mAttachments,
9176 medium))
9177 return setError(E_FAIL,
9178 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
9179 medium->getLocationFull().c_str(),
9180 dev.uuid.raw(),
9181 mUserData->s.strName.c_str(),
9182 mData->m_strConfigFileFull.c_str());
9183
9184 break;
9185 }
9186
9187 default:
9188 return setError(E_FAIL,
9189 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
9190 medium->getLocationFull().c_str(),
9191 mUserData->s.strName.c_str(),
9192 mData->m_strConfigFileFull.c_str());
9193 }
9194
9195 if (FAILED(rc))
9196 break;
9197
9198 /* Bandwidth groups are loaded at this point. */
9199 ComObjPtr<BandwidthGroup> pBwGroup;
9200
9201 if (!dev.strBwGroup.isEmpty())
9202 {
9203 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
9204 if (FAILED(rc))
9205 return setError(E_FAIL,
9206 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
9207 medium->getLocationFull().c_str(),
9208 dev.strBwGroup.c_str(),
9209 mUserData->s.strName.c_str(),
9210 mData->m_strConfigFileFull.c_str());
9211 pBwGroup->reference();
9212 }
9213
9214 const Bstr controllerName = aStorageController->getName();
9215 ComObjPtr<MediumAttachment> pAttachment;
9216 pAttachment.createObject();
9217 rc = pAttachment->init(this,
9218 medium,
9219 controllerName,
9220 dev.lPort,
9221 dev.lDevice,
9222 dev.deviceType,
9223 false,
9224 dev.fPassThrough,
9225 dev.fTempEject,
9226 dev.fNonRotational,
9227 dev.fDiscard,
9228 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
9229 if (FAILED(rc)) break;
9230
9231 /* associate the medium with this machine and snapshot */
9232 if (!medium.isNull())
9233 {
9234 AutoCaller medCaller(medium);
9235 if (FAILED(medCaller.rc())) return medCaller.rc();
9236 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
9237
9238 if (isSnapshotMachine())
9239 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
9240 else
9241 rc = medium->addBackReference(mData->mUuid);
9242 /* If the medium->addBackReference fails it sets an appropriate
9243 * error message, so no need to do any guesswork here. */
9244
9245 if (puuidRegistry)
9246 // caller wants registry ID to be set on all attached media (OVF import case)
9247 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
9248 }
9249
9250 if (FAILED(rc))
9251 break;
9252
9253 /* back up mMediaData to let registeredInit() properly rollback on failure
9254 * (= limited accessibility) */
9255 setModified(IsModified_Storage);
9256 mMediaData.backup();
9257 mMediaData->mAttachments.push_back(pAttachment);
9258 }
9259
9260 return rc;
9261}
9262
9263/**
9264 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
9265 *
9266 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
9267 * @param aSnapshot where to return the found snapshot
9268 * @param aSetError true to set extended error info on failure
9269 */
9270HRESULT Machine::findSnapshotById(const Guid &aId,
9271 ComObjPtr<Snapshot> &aSnapshot,
9272 bool aSetError /* = false */)
9273{
9274 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9275
9276 if (!mData->mFirstSnapshot)
9277 {
9278 if (aSetError)
9279 return setError(E_FAIL, tr("This machine does not have any snapshots"));
9280 return E_FAIL;
9281 }
9282
9283 if (aId.isZero())
9284 aSnapshot = mData->mFirstSnapshot;
9285 else
9286 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
9287
9288 if (!aSnapshot)
9289 {
9290 if (aSetError)
9291 return setError(E_FAIL,
9292 tr("Could not find a snapshot with UUID {%s}"),
9293 aId.toString().c_str());
9294 return E_FAIL;
9295 }
9296
9297 return S_OK;
9298}
9299
9300/**
9301 * Returns the snapshot with the given name or fails of no such snapshot.
9302 *
9303 * @param aName snapshot name to find
9304 * @param aSnapshot where to return the found snapshot
9305 * @param aSetError true to set extended error info on failure
9306 */
9307HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
9308 ComObjPtr<Snapshot> &aSnapshot,
9309 bool aSetError /* = false */)
9310{
9311 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
9312
9313 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
9314
9315 if (!mData->mFirstSnapshot)
9316 {
9317 if (aSetError)
9318 return setError(VBOX_E_OBJECT_NOT_FOUND,
9319 tr("This machine does not have any snapshots"));
9320 return VBOX_E_OBJECT_NOT_FOUND;
9321 }
9322
9323 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
9324
9325 if (!aSnapshot)
9326 {
9327 if (aSetError)
9328 return setError(VBOX_E_OBJECT_NOT_FOUND,
9329 tr("Could not find a snapshot named '%s'"), strName.c_str());
9330 return VBOX_E_OBJECT_NOT_FOUND;
9331 }
9332
9333 return S_OK;
9334}
9335
9336/**
9337 * Returns a storage controller object with the given name.
9338 *
9339 * @param aName storage controller name to find
9340 * @param aStorageController where to return the found storage controller
9341 * @param aSetError true to set extended error info on failure
9342 */
9343HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
9344 ComObjPtr<StorageController> &aStorageController,
9345 bool aSetError /* = false */)
9346{
9347 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
9348
9349 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
9350 it != mStorageControllers->end();
9351 ++it)
9352 {
9353 if ((*it)->getName() == aName)
9354 {
9355 aStorageController = (*it);
9356 return S_OK;
9357 }
9358 }
9359
9360 if (aSetError)
9361 return setError(VBOX_E_OBJECT_NOT_FOUND,
9362 tr("Could not find a storage controller named '%s'"),
9363 aName.c_str());
9364 return VBOX_E_OBJECT_NOT_FOUND;
9365}
9366
9367HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
9368 MediaData::AttachmentList &atts)
9369{
9370 AutoCaller autoCaller(this);
9371 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9372
9373 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9374
9375 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
9376 it != mMediaData->mAttachments.end();
9377 ++it)
9378 {
9379 const ComObjPtr<MediumAttachment> &pAtt = *it;
9380
9381 // should never happen, but deal with NULL pointers in the list.
9382 AssertStmt(!pAtt.isNull(), continue);
9383
9384 // getControllerName() needs caller+read lock
9385 AutoCaller autoAttCaller(pAtt);
9386 if (FAILED(autoAttCaller.rc()))
9387 {
9388 atts.clear();
9389 return autoAttCaller.rc();
9390 }
9391 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
9392
9393 if (pAtt->getControllerName() == aName)
9394 atts.push_back(pAtt);
9395 }
9396
9397 return S_OK;
9398}
9399
9400/**
9401 * Helper for #saveSettings. Cares about renaming the settings directory and
9402 * file if the machine name was changed and about creating a new settings file
9403 * if this is a new machine.
9404 *
9405 * @note Must be never called directly but only from #saveSettings().
9406 */
9407HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
9408{
9409 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9410
9411 HRESULT rc = S_OK;
9412
9413 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
9414
9415 /// @todo need to handle primary group change, too
9416
9417 /* attempt to rename the settings file if machine name is changed */
9418 if ( mUserData->s.fNameSync
9419 && mUserData.isBackedUp()
9420 && ( mUserData.backedUpData()->s.strName != mUserData->s.strName
9421 || mUserData.backedUpData()->s.llGroups.front() != mUserData->s.llGroups.front())
9422 )
9423 {
9424 bool dirRenamed = false;
9425 bool fileRenamed = false;
9426
9427 Utf8Str configFile, newConfigFile;
9428 Utf8Str configFilePrev, newConfigFilePrev;
9429 Utf8Str configDir, newConfigDir;
9430
9431 do
9432 {
9433 int vrc = VINF_SUCCESS;
9434
9435 Utf8Str name = mUserData.backedUpData()->s.strName;
9436 Utf8Str newName = mUserData->s.strName;
9437 Utf8Str group = mUserData.backedUpData()->s.llGroups.front();
9438 if (group == "/")
9439 group.setNull();
9440 Utf8Str newGroup = mUserData->s.llGroups.front();
9441 if (newGroup == "/")
9442 newGroup.setNull();
9443
9444 configFile = mData->m_strConfigFileFull;
9445
9446 /* first, rename the directory if it matches the group and machine name */
9447 Utf8Str groupPlusName = Utf8StrFmt("%s%c%s",
9448 group.c_str(), RTPATH_DELIMITER, name.c_str());
9449 /** @todo hack, make somehow use of ComposeMachineFilename */
9450 if (mUserData->s.fDirectoryIncludesUUID)
9451 groupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9452 Utf8Str newGroupPlusName = Utf8StrFmt("%s%c%s",
9453 newGroup.c_str(), RTPATH_DELIMITER, newName.c_str());
9454 /** @todo hack, make somehow use of ComposeMachineFilename */
9455 if (mUserData->s.fDirectoryIncludesUUID)
9456 newGroupPlusName += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
9457 configDir = configFile;
9458 configDir.stripFilename();
9459 newConfigDir = configDir;
9460 if ( configDir.length() >= groupPlusName.length()
9461 && !RTPathCompare(configDir.substr(configDir.length() - groupPlusName.length(), groupPlusName.length()).c_str(), groupPlusName.c_str()))
9462 {
9463 newConfigDir = newConfigDir.substr(0, configDir.length() - groupPlusName.length());
9464 Utf8Str newConfigBaseDir(newConfigDir);
9465 newConfigDir.append(newGroupPlusName);
9466 /* consistency: use \ if appropriate on the platform */
9467 RTPathChangeToDosSlashes(newConfigDir.mutableRaw(), false);
9468 /* new dir and old dir cannot be equal here because of 'if'
9469 * above and because name != newName */
9470 Assert(configDir != newConfigDir);
9471 if (!fSettingsFileIsNew)
9472 {
9473 /* perform real rename only if the machine is not new */
9474 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9475 if ( vrc == VERR_FILE_NOT_FOUND
9476 || vrc == VERR_PATH_NOT_FOUND)
9477 {
9478 /* create the parent directory, then retry renaming */
9479 Utf8Str parent(newConfigDir);
9480 parent.stripFilename();
9481 (void)RTDirCreateFullPath(parent.c_str(), 0700);
9482 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
9483 }
9484 if (RT_FAILURE(vrc))
9485 {
9486 rc = setError(E_FAIL,
9487 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
9488 configDir.c_str(),
9489 newConfigDir.c_str(),
9490 vrc);
9491 break;
9492 }
9493 /* delete subdirectories which are no longer needed */
9494 Utf8Str dir(configDir);
9495 dir.stripFilename();
9496 while (dir != newConfigBaseDir && dir != ".")
9497 {
9498 vrc = RTDirRemove(dir.c_str());
9499 if (RT_FAILURE(vrc))
9500 break;
9501 dir.stripFilename();
9502 }
9503 dirRenamed = true;
9504 }
9505 }
9506
9507 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
9508 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
9509
9510 /* then try to rename the settings file itself */
9511 if (newConfigFile != configFile)
9512 {
9513 /* get the path to old settings file in renamed directory */
9514 configFile = Utf8StrFmt("%s%c%s",
9515 newConfigDir.c_str(),
9516 RTPATH_DELIMITER,
9517 RTPathFilename(configFile.c_str()));
9518 if (!fSettingsFileIsNew)
9519 {
9520 /* perform real rename only if the machine is not new */
9521 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
9522 if (RT_FAILURE(vrc))
9523 {
9524 rc = setError(E_FAIL,
9525 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
9526 configFile.c_str(),
9527 newConfigFile.c_str(),
9528 vrc);
9529 break;
9530 }
9531 fileRenamed = true;
9532 configFilePrev = configFile;
9533 configFilePrev += "-prev";
9534 newConfigFilePrev = newConfigFile;
9535 newConfigFilePrev += "-prev";
9536 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
9537 }
9538 }
9539
9540 // update m_strConfigFileFull amd mConfigFile
9541 mData->m_strConfigFileFull = newConfigFile;
9542 // compute the relative path too
9543 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
9544
9545 // store the old and new so that VirtualBox::saveSettings() can update
9546 // the media registry
9547 if ( mData->mRegistered
9548 && configDir != newConfigDir)
9549 {
9550 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
9551
9552 if (pfNeedsGlobalSaveSettings)
9553 *pfNeedsGlobalSaveSettings = true;
9554 }
9555
9556 // in the saved state file path, replace the old directory with the new directory
9557 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
9558 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
9559
9560 // and do the same thing for the saved state file paths of all the online snapshots
9561 if (mData->mFirstSnapshot)
9562 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
9563 newConfigDir.c_str());
9564 }
9565 while (0);
9566
9567 if (FAILED(rc))
9568 {
9569 /* silently try to rename everything back */
9570 if (fileRenamed)
9571 {
9572 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
9573 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
9574 }
9575 if (dirRenamed)
9576 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
9577 }
9578
9579 if (FAILED(rc)) return rc;
9580 }
9581
9582 if (fSettingsFileIsNew)
9583 {
9584 /* create a virgin config file */
9585 int vrc = VINF_SUCCESS;
9586
9587 /* ensure the settings directory exists */
9588 Utf8Str path(mData->m_strConfigFileFull);
9589 path.stripFilename();
9590 if (!RTDirExists(path.c_str()))
9591 {
9592 vrc = RTDirCreateFullPath(path.c_str(), 0700);
9593 if (RT_FAILURE(vrc))
9594 {
9595 return setError(E_FAIL,
9596 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
9597 path.c_str(),
9598 vrc);
9599 }
9600 }
9601
9602 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
9603 path = Utf8Str(mData->m_strConfigFileFull);
9604 RTFILE f = NIL_RTFILE;
9605 vrc = RTFileOpen(&f, path.c_str(),
9606 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
9607 if (RT_FAILURE(vrc))
9608 return setError(E_FAIL,
9609 tr("Could not create the settings file '%s' (%Rrc)"),
9610 path.c_str(),
9611 vrc);
9612 RTFileClose(f);
9613 }
9614
9615 return rc;
9616}
9617
9618/**
9619 * Saves and commits machine data, user data and hardware data.
9620 *
9621 * Note that on failure, the data remains uncommitted.
9622 *
9623 * @a aFlags may combine the following flags:
9624 *
9625 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
9626 * Used when saving settings after an operation that makes them 100%
9627 * correspond to the settings from the current snapshot.
9628 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
9629 * #isReallyModified() returns false. This is necessary for cases when we
9630 * change machine data directly, not through the backup()/commit() mechanism.
9631 * - SaveS_Force: settings will be saved without doing a deep compare of the
9632 * settings structures. This is used when this is called because snapshots
9633 * have changed to avoid the overhead of the deep compare.
9634 *
9635 * @note Must be called from under this object's write lock. Locks children for
9636 * writing.
9637 *
9638 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
9639 * initialized to false and that will be set to true by this function if
9640 * the caller must invoke VirtualBox::saveSettings() because the global
9641 * settings have changed. This will happen if a machine rename has been
9642 * saved and the global machine and media registries will therefore need
9643 * updating.
9644 */
9645HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
9646 int aFlags /*= 0*/)
9647{
9648 LogFlowThisFuncEnter();
9649
9650 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9651
9652 /* make sure child objects are unable to modify the settings while we are
9653 * saving them */
9654 ensureNoStateDependencies();
9655
9656 AssertReturn(!isSnapshotMachine(),
9657 E_FAIL);
9658
9659 HRESULT rc = S_OK;
9660 bool fNeedsWrite = false;
9661
9662 /* First, prepare to save settings. It will care about renaming the
9663 * settings directory and file if the machine name was changed and about
9664 * creating a new settings file if this is a new machine. */
9665 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
9666 if (FAILED(rc)) return rc;
9667
9668 // keep a pointer to the current settings structures
9669 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
9670 settings::MachineConfigFile *pNewConfig = NULL;
9671
9672 try
9673 {
9674 // make a fresh one to have everyone write stuff into
9675 pNewConfig = new settings::MachineConfigFile(NULL);
9676 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
9677
9678 // now go and copy all the settings data from COM to the settings structures
9679 // (this calles saveSettings() on all the COM objects in the machine)
9680 copyMachineDataToSettings(*pNewConfig);
9681
9682 if (aFlags & SaveS_ResetCurStateModified)
9683 {
9684 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
9685 mData->mCurrentStateModified = FALSE;
9686 fNeedsWrite = true; // always, no need to compare
9687 }
9688 else if (aFlags & SaveS_Force)
9689 {
9690 fNeedsWrite = true; // always, no need to compare
9691 }
9692 else
9693 {
9694 if (!mData->mCurrentStateModified)
9695 {
9696 // do a deep compare of the settings that we just saved with the settings
9697 // previously stored in the config file; this invokes MachineConfigFile::operator==
9698 // which does a deep compare of all the settings, which is expensive but less expensive
9699 // than writing out XML in vain
9700 bool fAnySettingsChanged = !(*pNewConfig == *pOldConfig);
9701
9702 // could still be modified if any settings changed
9703 mData->mCurrentStateModified = fAnySettingsChanged;
9704
9705 fNeedsWrite = fAnySettingsChanged;
9706 }
9707 else
9708 fNeedsWrite = true;
9709 }
9710
9711 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
9712
9713 if (fNeedsWrite)
9714 // now spit it all out!
9715 pNewConfig->write(mData->m_strConfigFileFull);
9716
9717 mData->pMachineConfigFile = pNewConfig;
9718 delete pOldConfig;
9719 commit();
9720
9721 // after saving settings, we are no longer different from the XML on disk
9722 mData->flModifications = 0;
9723 }
9724 catch (HRESULT err)
9725 {
9726 // we assume that error info is set by the thrower
9727 rc = err;
9728
9729 // restore old config
9730 delete pNewConfig;
9731 mData->pMachineConfigFile = pOldConfig;
9732 }
9733 catch (...)
9734 {
9735 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
9736 }
9737
9738 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
9739 {
9740 /* Fire the data change event, even on failure (since we've already
9741 * committed all data). This is done only for SessionMachines because
9742 * mutable Machine instances are always not registered (i.e. private
9743 * to the client process that creates them) and thus don't need to
9744 * inform callbacks. */
9745 if (isSessionMachine())
9746 mParent->onMachineDataChange(mData->mUuid);
9747 }
9748
9749 LogFlowThisFunc(("rc=%08X\n", rc));
9750 LogFlowThisFuncLeave();
9751 return rc;
9752}
9753
9754/**
9755 * Implementation for saving the machine settings into the given
9756 * settings::MachineConfigFile instance. This copies machine extradata
9757 * from the previous machine config file in the instance data, if any.
9758 *
9759 * This gets called from two locations:
9760 *
9761 * -- Machine::saveSettings(), during the regular XML writing;
9762 *
9763 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
9764 * exported to OVF and we write the VirtualBox proprietary XML
9765 * into a <vbox:Machine> tag.
9766 *
9767 * This routine fills all the fields in there, including snapshots, *except*
9768 * for the following:
9769 *
9770 * -- fCurrentStateModified. There is some special logic associated with that.
9771 *
9772 * The caller can then call MachineConfigFile::write() or do something else
9773 * with it.
9774 *
9775 * Caller must hold the machine lock!
9776 *
9777 * This throws XML errors and HRESULT, so the caller must have a catch block!
9778 */
9779void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
9780{
9781 // deep copy extradata
9782 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
9783
9784 config.uuid = mData->mUuid;
9785
9786 // copy name, description, OS type, teleport, UTC etc.
9787 config.machineUserData = mUserData->s;
9788
9789 if ( mData->mMachineState == MachineState_Saved
9790 || mData->mMachineState == MachineState_Restoring
9791 // when deleting a snapshot we may or may not have a saved state in the current state,
9792 // so let's not assert here please
9793 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
9794 || mData->mMachineState == MachineState_DeletingSnapshotOnline
9795 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
9796 && (!mSSData->strStateFilePath.isEmpty())
9797 )
9798 )
9799 {
9800 Assert(!mSSData->strStateFilePath.isEmpty());
9801 /* try to make the file name relative to the settings file dir */
9802 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
9803 }
9804 else
9805 {
9806 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
9807 config.strStateFile.setNull();
9808 }
9809
9810 if (mData->mCurrentSnapshot)
9811 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
9812 else
9813 config.uuidCurrentSnapshot.clear();
9814
9815 config.timeLastStateChange = mData->mLastStateChange;
9816 config.fAborted = (mData->mMachineState == MachineState_Aborted);
9817 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
9818
9819 HRESULT rc = saveHardware(config.hardwareMachine, &config.debugging, &config.autostart);
9820 if (FAILED(rc)) throw rc;
9821
9822 rc = saveStorageControllers(config.storageMachine);
9823 if (FAILED(rc)) throw rc;
9824
9825 // save machine's media registry if this is VirtualBox 4.0 or later
9826 if (config.canHaveOwnMediaRegistry())
9827 {
9828 // determine machine folder
9829 Utf8Str strMachineFolder = getSettingsFileFull();
9830 strMachineFolder.stripFilename();
9831 mParent->saveMediaRegistry(config.mediaRegistry,
9832 getId(), // only media with registry ID == machine UUID
9833 strMachineFolder);
9834 // this throws HRESULT
9835 }
9836
9837 // save snapshots
9838 rc = saveAllSnapshots(config);
9839 if (FAILED(rc)) throw rc;
9840}
9841
9842/**
9843 * Saves all snapshots of the machine into the given machine config file. Called
9844 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
9845 * @param config
9846 * @return
9847 */
9848HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
9849{
9850 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9851
9852 HRESULT rc = S_OK;
9853
9854 try
9855 {
9856 config.llFirstSnapshot.clear();
9857
9858 if (mData->mFirstSnapshot)
9859 {
9860 settings::Snapshot snapNew;
9861 config.llFirstSnapshot.push_back(snapNew);
9862
9863 // get reference to the fresh copy of the snapshot on the list and
9864 // work on that copy directly to avoid excessive copying later
9865 settings::Snapshot &snap = config.llFirstSnapshot.front();
9866
9867 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
9868 if (FAILED(rc)) throw rc;
9869 }
9870
9871// if (mType == IsSessionMachine)
9872// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
9873
9874 }
9875 catch (HRESULT err)
9876 {
9877 /* we assume that error info is set by the thrower */
9878 rc = err;
9879 }
9880 catch (...)
9881 {
9882 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
9883 }
9884
9885 return rc;
9886}
9887
9888/**
9889 * Saves the VM hardware configuration. It is assumed that the
9890 * given node is empty.
9891 *
9892 * @param data Reference to the settings object for the hardware config.
9893 * @param pDbg Pointer to the settings object for the debugging config
9894 * which happens to live in mHWData.
9895 * @param pAutostart Pointer to the settings object for the autostart config
9896 * which happens to live in mHWData.
9897 */
9898HRESULT Machine::saveHardware(settings::Hardware &data, settings::Debugging *pDbg,
9899 settings::Autostart *pAutostart)
9900{
9901 HRESULT rc = S_OK;
9902
9903 try
9904 {
9905 /* The hardware version attribute (optional).
9906 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
9907 if ( mHWData->mHWVersion == "1"
9908 && mSSData->strStateFilePath.isEmpty()
9909 )
9910 mHWData->mHWVersion = "2"; /** @todo Is this safe, to update mHWVersion here? If not some other point needs to be found where this can be done. */
9911
9912 data.strVersion = mHWData->mHWVersion;
9913 data.uuid = mHWData->mHardwareUUID;
9914
9915 // CPU
9916 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
9917 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
9918 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
9919 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
9920 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
9921 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
9922 data.fPAE = !!mHWData->mPAEEnabled;
9923 data.enmLongMode = mHWData->mLongMode;
9924 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
9925
9926 /* Standard and Extended CPUID leafs. */
9927 data.llCpuIdLeafs.clear();
9928 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
9929 {
9930 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
9931 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
9932 }
9933 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
9934 {
9935 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
9936 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
9937 }
9938
9939 data.cCPUs = mHWData->mCPUCount;
9940 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
9941 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
9942
9943 data.llCpus.clear();
9944 if (data.fCpuHotPlug)
9945 {
9946 for (unsigned idx = 0; idx < data.cCPUs; idx++)
9947 {
9948 if (mHWData->mCPUAttached[idx])
9949 {
9950 settings::Cpu cpu;
9951 cpu.ulId = idx;
9952 data.llCpus.push_back(cpu);
9953 }
9954 }
9955 }
9956
9957 // memory
9958 data.ulMemorySizeMB = mHWData->mMemorySize;
9959 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
9960
9961 // firmware
9962 data.firmwareType = mHWData->mFirmwareType;
9963
9964 // HID
9965 data.pointingHIDType = mHWData->mPointingHIDType;
9966 data.keyboardHIDType = mHWData->mKeyboardHIDType;
9967
9968 // chipset
9969 data.chipsetType = mHWData->mChipsetType;
9970
9971 data.fEmulatedUSBWebcam = !!mHWData->mEmulatedUSBWebcamEnabled;
9972 data.fEmulatedUSBCardReader = !!mHWData->mEmulatedUSBCardReaderEnabled;
9973
9974 // HPET
9975 data.fHPETEnabled = !!mHWData->mHPETEnabled;
9976
9977 // boot order
9978 data.mapBootOrder.clear();
9979 for (size_t i = 0;
9980 i < RT_ELEMENTS(mHWData->mBootOrder);
9981 ++i)
9982 data.mapBootOrder[i] = mHWData->mBootOrder[i];
9983
9984 // display
9985 data.graphicsControllerType = mHWData->mGraphicsControllerType;
9986 data.ulVRAMSizeMB = mHWData->mVRAMSize;
9987 data.cMonitors = mHWData->mMonitorCount;
9988 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
9989 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
9990 data.ulVideoCaptureHorzRes = mHWData->mVideoCaptureWidth;
9991 data.ulVideoCaptureVertRes = mHWData->mVideoCaptureHeight;
9992 data.fVideoCaptureEnabled = !!mHWData->mVideoCaptureEnabled;
9993 data.strVideoCaptureFile = mHWData->mVideoCaptureFile;
9994
9995 /* VRDEServer settings (optional) */
9996 rc = mVRDEServer->saveSettings(data.vrdeSettings);
9997 if (FAILED(rc)) throw rc;
9998
9999 /* BIOS (required) */
10000 rc = mBIOSSettings->saveSettings(data.biosSettings);
10001 if (FAILED(rc)) throw rc;
10002
10003 /* USB Controller (required) */
10004 rc = mUSBController->saveSettings(data.usbController);
10005 if (FAILED(rc)) throw rc;
10006
10007 /* Network adapters (required) */
10008 uint32_t uMaxNICs = RT_MIN(Global::getMaxNetworkAdapters(mHWData->mChipsetType), mNetworkAdapters.size());
10009 data.llNetworkAdapters.clear();
10010 /* Write out only the nominal number of network adapters for this
10011 * chipset type. Since Machine::commit() hasn't been called there
10012 * may be extra NIC settings in the vector. */
10013 for (ULONG slot = 0; slot < uMaxNICs; ++slot)
10014 {
10015 settings::NetworkAdapter nic;
10016 nic.ulSlot = slot;
10017 /* paranoia check... must not be NULL, but must not crash either. */
10018 if (mNetworkAdapters[slot])
10019 {
10020 rc = mNetworkAdapters[slot]->saveSettings(nic);
10021 if (FAILED(rc)) throw rc;
10022
10023 data.llNetworkAdapters.push_back(nic);
10024 }
10025 }
10026
10027 /* Serial ports */
10028 data.llSerialPorts.clear();
10029 for (ULONG slot = 0;
10030 slot < RT_ELEMENTS(mSerialPorts);
10031 ++slot)
10032 {
10033 settings::SerialPort s;
10034 s.ulSlot = slot;
10035 rc = mSerialPorts[slot]->saveSettings(s);
10036 if (FAILED(rc)) return rc;
10037
10038 data.llSerialPorts.push_back(s);
10039 }
10040
10041 /* Parallel ports */
10042 data.llParallelPorts.clear();
10043 for (ULONG slot = 0;
10044 slot < RT_ELEMENTS(mParallelPorts);
10045 ++slot)
10046 {
10047 settings::ParallelPort p;
10048 p.ulSlot = slot;
10049 rc = mParallelPorts[slot]->saveSettings(p);
10050 if (FAILED(rc)) return rc;
10051
10052 data.llParallelPorts.push_back(p);
10053 }
10054
10055 /* Audio adapter */
10056 rc = mAudioAdapter->saveSettings(data.audioAdapter);
10057 if (FAILED(rc)) return rc;
10058
10059 /* Shared folders */
10060 data.llSharedFolders.clear();
10061 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
10062 it != mHWData->mSharedFolders.end();
10063 ++it)
10064 {
10065 SharedFolder *pSF = *it;
10066 AutoCaller sfCaller(pSF);
10067 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
10068 settings::SharedFolder sf;
10069 sf.strName = pSF->getName();
10070 sf.strHostPath = pSF->getHostPath();
10071 sf.fWritable = !!pSF->isWritable();
10072 sf.fAutoMount = !!pSF->isAutoMounted();
10073
10074 data.llSharedFolders.push_back(sf);
10075 }
10076
10077 // clipboard
10078 data.clipboardMode = mHWData->mClipboardMode;
10079
10080 // drag'n'drop
10081 data.dragAndDropMode = mHWData->mDragAndDropMode;
10082
10083 /* Guest */
10084 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
10085
10086 // IO settings
10087 data.ioSettings.fIOCacheEnabled = !!mHWData->mIOCacheEnabled;
10088 data.ioSettings.ulIOCacheSize = mHWData->mIOCacheSize;
10089
10090 /* BandwidthControl (required) */
10091 rc = mBandwidthControl->saveSettings(data.ioSettings);
10092 if (FAILED(rc)) throw rc;
10093
10094 /* Host PCI devices */
10095 for (HWData::PCIDeviceAssignmentList::const_iterator it = mHWData->mPCIDeviceAssignments.begin();
10096 it != mHWData->mPCIDeviceAssignments.end();
10097 ++it)
10098 {
10099 ComObjPtr<PCIDeviceAttachment> pda = *it;
10100 settings::HostPCIDeviceAttachment hpda;
10101
10102 rc = pda->saveSettings(hpda);
10103 if (FAILED(rc)) throw rc;
10104
10105 data.pciAttachments.push_back(hpda);
10106 }
10107
10108
10109 // guest properties
10110 data.llGuestProperties.clear();
10111#ifdef VBOX_WITH_GUEST_PROPS
10112 for (HWData::GuestPropertyMap::const_iterator it = mHWData->mGuestProperties.begin();
10113 it != mHWData->mGuestProperties.end();
10114 ++it)
10115 {
10116 HWData::GuestProperty property = it->second;
10117
10118 /* Remove transient guest properties at shutdown unless we
10119 * are saving state */
10120 if ( ( mData->mMachineState == MachineState_PoweredOff
10121 || mData->mMachineState == MachineState_Aborted
10122 || mData->mMachineState == MachineState_Teleported)
10123 && ( property.mFlags & guestProp::TRANSIENT
10124 || property.mFlags & guestProp::TRANSRESET))
10125 continue;
10126 settings::GuestProperty prop;
10127 prop.strName = it->first;
10128 prop.strValue = property.strValue;
10129 prop.timestamp = property.mTimestamp;
10130 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
10131 guestProp::writeFlags(property.mFlags, szFlags);
10132 prop.strFlags = szFlags;
10133
10134 data.llGuestProperties.push_back(prop);
10135 }
10136
10137 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
10138 /* I presume this doesn't require a backup(). */
10139 mData->mGuestPropertiesModified = FALSE;
10140#endif /* VBOX_WITH_GUEST_PROPS defined */
10141
10142 *pDbg = mHWData->mDebugging;
10143 *pAutostart = mHWData->mAutostart;
10144
10145 data.strDefaultFrontend = mHWData->mDefaultFrontend;
10146 }
10147 catch(std::bad_alloc &)
10148 {
10149 return E_OUTOFMEMORY;
10150 }
10151
10152 AssertComRC(rc);
10153 return rc;
10154}
10155
10156/**
10157 * Saves the storage controller configuration.
10158 *
10159 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
10160 */
10161HRESULT Machine::saveStorageControllers(settings::Storage &data)
10162{
10163 data.llStorageControllers.clear();
10164
10165 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
10166 it != mStorageControllers->end();
10167 ++it)
10168 {
10169 HRESULT rc;
10170 ComObjPtr<StorageController> pCtl = *it;
10171
10172 settings::StorageController ctl;
10173 ctl.strName = pCtl->getName();
10174 ctl.controllerType = pCtl->getControllerType();
10175 ctl.storageBus = pCtl->getStorageBus();
10176 ctl.ulInstance = pCtl->getInstance();
10177 ctl.fBootable = pCtl->getBootable();
10178
10179 /* Save the port count. */
10180 ULONG portCount;
10181 rc = pCtl->COMGETTER(PortCount)(&portCount);
10182 ComAssertComRCRet(rc, rc);
10183 ctl.ulPortCount = portCount;
10184
10185 /* Save fUseHostIOCache */
10186 BOOL fUseHostIOCache;
10187 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
10188 ComAssertComRCRet(rc, rc);
10189 ctl.fUseHostIOCache = !!fUseHostIOCache;
10190
10191 /* Save IDE emulation settings. */
10192 if (ctl.controllerType == StorageControllerType_IntelAhci)
10193 {
10194 if ( (FAILED(rc = pCtl->getIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
10195 || (FAILED(rc = pCtl->getIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
10196 || (FAILED(rc = pCtl->getIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
10197 || (FAILED(rc = pCtl->getIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
10198 )
10199 ComAssertComRCRet(rc, rc);
10200 }
10201
10202 /* save the devices now. */
10203 rc = saveStorageDevices(pCtl, ctl);
10204 ComAssertComRCRet(rc, rc);
10205
10206 data.llStorageControllers.push_back(ctl);
10207 }
10208
10209 return S_OK;
10210}
10211
10212/**
10213 * Saves the hard disk configuration.
10214 */
10215HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
10216 settings::StorageController &data)
10217{
10218 MediaData::AttachmentList atts;
10219
10220 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
10221 if (FAILED(rc)) return rc;
10222
10223 data.llAttachedDevices.clear();
10224 for (MediaData::AttachmentList::const_iterator it = atts.begin();
10225 it != atts.end();
10226 ++it)
10227 {
10228 settings::AttachedDevice dev;
10229
10230 MediumAttachment *pAttach = *it;
10231 Medium *pMedium = pAttach->getMedium();
10232
10233 dev.deviceType = pAttach->getType();
10234 dev.lPort = pAttach->getPort();
10235 dev.lDevice = pAttach->getDevice();
10236 if (pMedium)
10237 {
10238 if (pMedium->isHostDrive())
10239 dev.strHostDriveSrc = pMedium->getLocationFull();
10240 else
10241 dev.uuid = pMedium->getId();
10242 dev.fPassThrough = pAttach->getPassthrough();
10243 dev.fTempEject = pAttach->getTempEject();
10244 dev.fNonRotational = pAttach->getNonRotational();
10245 dev.fDiscard = pAttach->getDiscard();
10246 }
10247
10248 dev.strBwGroup = pAttach->getBandwidthGroup();
10249
10250 data.llAttachedDevices.push_back(dev);
10251 }
10252
10253 return S_OK;
10254}
10255
10256/**
10257 * Saves machine state settings as defined by aFlags
10258 * (SaveSTS_* values).
10259 *
10260 * @param aFlags Combination of SaveSTS_* flags.
10261 *
10262 * @note Locks objects for writing.
10263 */
10264HRESULT Machine::saveStateSettings(int aFlags)
10265{
10266 if (aFlags == 0)
10267 return S_OK;
10268
10269 AutoCaller autoCaller(this);
10270 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10271
10272 /* This object's write lock is also necessary to serialize file access
10273 * (prevent concurrent reads and writes) */
10274 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10275
10276 HRESULT rc = S_OK;
10277
10278 Assert(mData->pMachineConfigFile);
10279
10280 try
10281 {
10282 if (aFlags & SaveSTS_CurStateModified)
10283 mData->pMachineConfigFile->fCurrentStateModified = true;
10284
10285 if (aFlags & SaveSTS_StateFilePath)
10286 {
10287 if (!mSSData->strStateFilePath.isEmpty())
10288 /* try to make the file name relative to the settings file dir */
10289 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
10290 else
10291 mData->pMachineConfigFile->strStateFile.setNull();
10292 }
10293
10294 if (aFlags & SaveSTS_StateTimeStamp)
10295 {
10296 Assert( mData->mMachineState != MachineState_Aborted
10297 || mSSData->strStateFilePath.isEmpty());
10298
10299 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
10300
10301 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
10302//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
10303 }
10304
10305 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
10306 }
10307 catch (...)
10308 {
10309 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
10310 }
10311
10312 return rc;
10313}
10314
10315/**
10316 * Ensures that the given medium is added to a media registry. If this machine
10317 * was created with 4.0 or later, then the machine registry is used. Otherwise
10318 * the global VirtualBox media registry is used.
10319 *
10320 * Caller must NOT hold machine lock, media tree or any medium locks!
10321 *
10322 * @param pMedium
10323 */
10324void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium)
10325{
10326 /* Paranoia checks: do not hold machine or media tree locks. */
10327 AssertReturnVoid(!isWriteLockOnCurrentThread());
10328 AssertReturnVoid(!mParent->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
10329
10330 ComObjPtr<Medium> pBase;
10331 {
10332 AutoReadLock treeLock(&mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10333 pBase = pMedium->getBase();
10334 }
10335
10336 /* Paranoia checks: do not hold medium locks. */
10337 AssertReturnVoid(!pMedium->isWriteLockOnCurrentThread());
10338 AssertReturnVoid(!pBase->isWriteLockOnCurrentThread());
10339
10340 // decide which medium registry to use now that the medium is attached:
10341 Guid uuid;
10342 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
10343 // machine XML is VirtualBox 4.0 or higher:
10344 uuid = getId(); // machine UUID
10345 else
10346 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
10347
10348 if (pMedium->addRegistry(uuid, false /* fRecurse */))
10349 mParent->markRegistryModified(uuid);
10350
10351 /* For more complex hard disk structures it can happen that the base
10352 * medium isn't yet associated with any medium registry. Do that now. */
10353 if (pMedium != pBase)
10354 {
10355 if (pBase->addRegistry(uuid, true /* fRecurse */))
10356 mParent->markRegistryModified(uuid);
10357 }
10358}
10359
10360/**
10361 * Creates differencing hard disks for all normal hard disks attached to this
10362 * machine and a new set of attachments to refer to created disks.
10363 *
10364 * Used when taking a snapshot or when deleting the current state. Gets called
10365 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
10366 *
10367 * This method assumes that mMediaData contains the original hard disk attachments
10368 * it needs to create diffs for. On success, these attachments will be replaced
10369 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
10370 * called to delete created diffs which will also rollback mMediaData and restore
10371 * whatever was backed up before calling this method.
10372 *
10373 * Attachments with non-normal hard disks are left as is.
10374 *
10375 * If @a aOnline is @c false then the original hard disks that require implicit
10376 * diffs will be locked for reading. Otherwise it is assumed that they are
10377 * already locked for writing (when the VM was started). Note that in the latter
10378 * case it is responsibility of the caller to lock the newly created diffs for
10379 * writing if this method succeeds.
10380 *
10381 * @param aProgress Progress object to run (must contain at least as
10382 * many operations left as the number of hard disks
10383 * attached).
10384 * @param aOnline Whether the VM was online prior to this operation.
10385 *
10386 * @note The progress object is not marked as completed, neither on success nor
10387 * on failure. This is a responsibility of the caller.
10388 *
10389 * @note Locks this object and the media tree for writing.
10390 */
10391HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
10392 ULONG aWeight,
10393 bool aOnline)
10394{
10395 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10396
10397 AutoCaller autoCaller(this);
10398 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10399
10400 AutoMultiWriteLock2 alock(this->lockHandle(),
10401 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10402
10403 /* must be in a protective state because we release the lock below */
10404 AssertReturn( mData->mMachineState == MachineState_Saving
10405 || mData->mMachineState == MachineState_LiveSnapshotting
10406 || mData->mMachineState == MachineState_RestoringSnapshot
10407 || mData->mMachineState == MachineState_DeletingSnapshot
10408 , E_FAIL);
10409
10410 HRESULT rc = S_OK;
10411
10412 // use appropriate locked media map (online or offline)
10413 MediumLockListMap lockedMediaOffline;
10414 MediumLockListMap *lockedMediaMap;
10415 if (aOnline)
10416 lockedMediaMap = &mData->mSession.mLockedMedia;
10417 else
10418 lockedMediaMap = &lockedMediaOffline;
10419
10420 try
10421 {
10422 if (!aOnline)
10423 {
10424 /* lock all attached hard disks early to detect "in use"
10425 * situations before creating actual diffs */
10426 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10427 it != mMediaData->mAttachments.end();
10428 ++it)
10429 {
10430 MediumAttachment* pAtt = *it;
10431 if (pAtt->getType() == DeviceType_HardDisk)
10432 {
10433 Medium* pMedium = pAtt->getMedium();
10434 Assert(pMedium);
10435
10436 MediumLockList *pMediumLockList(new MediumLockList());
10437 alock.release();
10438 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
10439 false /* fMediumLockWrite */,
10440 NULL,
10441 *pMediumLockList);
10442 alock.acquire();
10443 if (FAILED(rc))
10444 {
10445 delete pMediumLockList;
10446 throw rc;
10447 }
10448 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10449 if (FAILED(rc))
10450 {
10451 throw setError(rc,
10452 tr("Collecting locking information for all attached media failed"));
10453 }
10454 }
10455 }
10456
10457 /* Now lock all media. If this fails, nothing is locked. */
10458 alock.release();
10459 rc = lockedMediaMap->Lock();
10460 alock.acquire();
10461 if (FAILED(rc))
10462 {
10463 throw setError(rc,
10464 tr("Locking of attached media failed"));
10465 }
10466 }
10467
10468 /* remember the current list (note that we don't use backup() since
10469 * mMediaData may be already backed up) */
10470 MediaData::AttachmentList atts = mMediaData->mAttachments;
10471
10472 /* start from scratch */
10473 mMediaData->mAttachments.clear();
10474
10475 /* go through remembered attachments and create diffs for normal hard
10476 * disks and attach them */
10477 for (MediaData::AttachmentList::const_iterator it = atts.begin();
10478 it != atts.end();
10479 ++it)
10480 {
10481 MediumAttachment* pAtt = *it;
10482
10483 DeviceType_T devType = pAtt->getType();
10484 Medium* pMedium = pAtt->getMedium();
10485
10486 if ( devType != DeviceType_HardDisk
10487 || pMedium == NULL
10488 || pMedium->getType() != MediumType_Normal)
10489 {
10490 /* copy the attachment as is */
10491
10492 /** @todo the progress object created in Console::TakeSnaphot
10493 * only expects operations for hard disks. Later other
10494 * device types need to show up in the progress as well. */
10495 if (devType == DeviceType_HardDisk)
10496 {
10497 if (pMedium == NULL)
10498 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
10499 aWeight); // weight
10500 else
10501 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
10502 pMedium->getBase()->getName().c_str()).raw(),
10503 aWeight); // weight
10504 }
10505
10506 mMediaData->mAttachments.push_back(pAtt);
10507 continue;
10508 }
10509
10510 /* need a diff */
10511 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
10512 pMedium->getBase()->getName().c_str()).raw(),
10513 aWeight); // weight
10514
10515 Utf8Str strFullSnapshotFolder;
10516 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10517
10518 ComObjPtr<Medium> diff;
10519 diff.createObject();
10520 // store the diff in the same registry as the parent
10521 // (this cannot fail here because we can't create implicit diffs for
10522 // unregistered images)
10523 Guid uuidRegistryParent;
10524 bool fInRegistry = pMedium->getFirstRegistryMachineId(uuidRegistryParent);
10525 Assert(fInRegistry); NOREF(fInRegistry);
10526 rc = diff->init(mParent,
10527 pMedium->getPreferredDiffFormat(),
10528 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
10529 uuidRegistryParent);
10530 if (FAILED(rc)) throw rc;
10531
10532 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
10533 * the push_back? Looks like we're going to release medium with the
10534 * wrong kind of lock (general issue with if we fail anywhere at all)
10535 * and an orphaned VDI in the snapshots folder. */
10536
10537 /* update the appropriate lock list */
10538 MediumLockList *pMediumLockList;
10539 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
10540 AssertComRCThrowRC(rc);
10541 if (aOnline)
10542 {
10543 alock.release();
10544 /* The currently attached medium will be read-only, change
10545 * the lock type to read. */
10546 rc = pMediumLockList->Update(pMedium, false);
10547 alock.acquire();
10548 AssertComRCThrowRC(rc);
10549 }
10550
10551 /* release the locks before the potentially lengthy operation */
10552 alock.release();
10553 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
10554 pMediumLockList,
10555 NULL /* aProgress */,
10556 true /* aWait */);
10557 alock.acquire();
10558 if (FAILED(rc)) throw rc;
10559
10560 rc = lockedMediaMap->Unlock();
10561 AssertComRCThrowRC(rc);
10562 alock.release();
10563 rc = pMediumLockList->Append(diff, true);
10564 alock.acquire();
10565 AssertComRCThrowRC(rc);
10566 alock.release();
10567 rc = lockedMediaMap->Lock();
10568 alock.acquire();
10569 AssertComRCThrowRC(rc);
10570
10571 rc = diff->addBackReference(mData->mUuid);
10572 AssertComRCThrowRC(rc);
10573
10574 /* add a new attachment */
10575 ComObjPtr<MediumAttachment> attachment;
10576 attachment.createObject();
10577 rc = attachment->init(this,
10578 diff,
10579 pAtt->getControllerName(),
10580 pAtt->getPort(),
10581 pAtt->getDevice(),
10582 DeviceType_HardDisk,
10583 true /* aImplicit */,
10584 false /* aPassthrough */,
10585 false /* aTempEject */,
10586 pAtt->getNonRotational(),
10587 pAtt->getDiscard(),
10588 pAtt->getBandwidthGroup());
10589 if (FAILED(rc)) throw rc;
10590
10591 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
10592 AssertComRCThrowRC(rc);
10593 mMediaData->mAttachments.push_back(attachment);
10594 }
10595 }
10596 catch (HRESULT aRC) { rc = aRC; }
10597
10598 /* unlock all hard disks we locked when there is no VM */
10599 if (!aOnline)
10600 {
10601 ErrorInfoKeeper eik;
10602
10603 HRESULT rc1 = lockedMediaMap->Clear();
10604 AssertComRC(rc1);
10605 }
10606
10607 return rc;
10608}
10609
10610/**
10611 * Deletes implicit differencing hard disks created either by
10612 * #createImplicitDiffs() or by #AttachDevice() and rolls back mMediaData.
10613 *
10614 * Note that to delete hard disks created by #AttachDevice() this method is
10615 * called from #fixupMedia() when the changes are rolled back.
10616 *
10617 * @note Locks this object and the media tree for writing.
10618 */
10619HRESULT Machine::deleteImplicitDiffs(bool aOnline)
10620{
10621 LogFlowThisFunc(("aOnline=%d\n", aOnline));
10622
10623 AutoCaller autoCaller(this);
10624 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10625
10626 AutoMultiWriteLock2 alock(this->lockHandle(),
10627 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10628
10629 /* We absolutely must have backed up state. */
10630 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
10631
10632 /* Check if there are any implicitly created diff images. */
10633 bool fImplicitDiffs = false;
10634 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10635 it != mMediaData->mAttachments.end();
10636 ++it)
10637 {
10638 const ComObjPtr<MediumAttachment> &pAtt = *it;
10639 if (pAtt->isImplicit())
10640 {
10641 fImplicitDiffs = true;
10642 break;
10643 }
10644 }
10645 /* If there is nothing to do, leave early. This saves lots of image locking
10646 * effort. It also avoids a MachineStateChanged event without real reason.
10647 * This is important e.g. when loading a VM config, because there should be
10648 * no events. Otherwise API clients can become thoroughly confused for
10649 * inaccessible VMs (the code for loading VM configs uses this method for
10650 * cleanup if the config makes no sense), as they take such events as an
10651 * indication that the VM is alive, and they would force the VM config to
10652 * be reread, leading to an endless loop. */
10653 if (!fImplicitDiffs)
10654 return S_OK;
10655
10656 HRESULT rc = S_OK;
10657 MachineState_T oldState = mData->mMachineState;
10658
10659 /* will release the lock before the potentially lengthy operation,
10660 * so protect with the special state (unless already protected) */
10661 if ( oldState != MachineState_Saving
10662 && oldState != MachineState_LiveSnapshotting
10663 && oldState != MachineState_RestoringSnapshot
10664 && oldState != MachineState_DeletingSnapshot
10665 && oldState != MachineState_DeletingSnapshotOnline
10666 && oldState != MachineState_DeletingSnapshotPaused
10667 )
10668 setMachineState(MachineState_SettingUp);
10669
10670 // use appropriate locked media map (online or offline)
10671 MediumLockListMap lockedMediaOffline;
10672 MediumLockListMap *lockedMediaMap;
10673 if (aOnline)
10674 lockedMediaMap = &mData->mSession.mLockedMedia;
10675 else
10676 lockedMediaMap = &lockedMediaOffline;
10677
10678 try
10679 {
10680 if (!aOnline)
10681 {
10682 /* lock all attached hard disks early to detect "in use"
10683 * situations before deleting actual diffs */
10684 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10685 it != mMediaData->mAttachments.end();
10686 ++it)
10687 {
10688 MediumAttachment* pAtt = *it;
10689 if (pAtt->getType() == DeviceType_HardDisk)
10690 {
10691 Medium* pMedium = pAtt->getMedium();
10692 Assert(pMedium);
10693
10694 MediumLockList *pMediumLockList(new MediumLockList());
10695 alock.release();
10696 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
10697 false /* fMediumLockWrite */,
10698 NULL,
10699 *pMediumLockList);
10700 alock.acquire();
10701
10702 if (FAILED(rc))
10703 {
10704 delete pMediumLockList;
10705 throw rc;
10706 }
10707
10708 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
10709 if (FAILED(rc))
10710 throw rc;
10711 }
10712 }
10713
10714 if (FAILED(rc))
10715 throw rc;
10716 } // end of offline
10717
10718 /* Lock lists are now up to date and include implicitly created media */
10719
10720 /* Go through remembered attachments and delete all implicitly created
10721 * diffs and fix up the attachment information */
10722 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
10723 MediaData::AttachmentList implicitAtts;
10724 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10725 it != mMediaData->mAttachments.end();
10726 ++it)
10727 {
10728 ComObjPtr<MediumAttachment> pAtt = *it;
10729 ComObjPtr<Medium> pMedium = pAtt->getMedium();
10730 if (pMedium.isNull())
10731 continue;
10732
10733 // Implicit attachments go on the list for deletion and back references are removed.
10734 if (pAtt->isImplicit())
10735 {
10736 /* Deassociate and mark for deletion */
10737 LogFlowThisFunc(("Detaching '%s', pending deletion\n", pAtt->getLogName()));
10738 rc = pMedium->removeBackReference(mData->mUuid);
10739 if (FAILED(rc))
10740 throw rc;
10741 implicitAtts.push_back(pAtt);
10742 continue;
10743 }
10744
10745 /* Was this medium attached before? */
10746 if (!findAttachment(oldAtts, pMedium))
10747 {
10748 /* no: de-associate */
10749 LogFlowThisFunc(("Detaching '%s', no deletion\n", pAtt->getLogName()));
10750 rc = pMedium->removeBackReference(mData->mUuid);
10751 if (FAILED(rc))
10752 throw rc;
10753 continue;
10754 }
10755 LogFlowThisFunc(("Not detaching '%s'\n", pAtt->getLogName()));
10756 }
10757
10758 /* If there are implicit attachments to delete, throw away the lock
10759 * map contents (which will unlock all media) since the medium
10760 * attachments will be rolled back. Below we need to completely
10761 * recreate the lock map anyway since it is infinitely complex to
10762 * do this incrementally (would need reconstructing each attachment
10763 * change, which would be extremely hairy). */
10764 if (implicitAtts.size() != 0)
10765 {
10766 ErrorInfoKeeper eik;
10767
10768 HRESULT rc1 = lockedMediaMap->Clear();
10769 AssertComRC(rc1);
10770 }
10771
10772 /* rollback hard disk changes */
10773 mMediaData.rollback();
10774
10775 MultiResult mrc(S_OK);
10776
10777 // Delete unused implicit diffs.
10778 if (implicitAtts.size() != 0)
10779 {
10780 alock.release();
10781
10782 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
10783 it != implicitAtts.end();
10784 ++it)
10785 {
10786 // Remove medium associated with this attachment.
10787 ComObjPtr<MediumAttachment> pAtt = *it;
10788 Assert(pAtt);
10789 LogFlowThisFunc(("Deleting '%s'\n", pAtt->getLogName()));
10790 ComObjPtr<Medium> pMedium = pAtt->getMedium();
10791 Assert(pMedium);
10792
10793 rc = pMedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/);
10794 // continue on delete failure, just collect error messages
10795 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, pAtt->getLogName(), pMedium->getLocationFull().c_str() ));
10796 mrc = rc;
10797 }
10798
10799 alock.acquire();
10800
10801 /* if there is a VM recreate media lock map as mentioned above,
10802 * otherwise it is a waste of time and we leave things unlocked */
10803 if (aOnline)
10804 {
10805 const ComObjPtr<SessionMachine> pMachine = mData->mSession.mMachine;
10806 /* must never be NULL, but better safe than sorry */
10807 if (!pMachine.isNull())
10808 {
10809 alock.release();
10810 rc = mData->mSession.mMachine->lockMedia();
10811 alock.acquire();
10812 if (FAILED(rc))
10813 throw rc;
10814 }
10815 }
10816 }
10817 }
10818 catch (HRESULT aRC) {rc = aRC;}
10819
10820 if (mData->mMachineState == MachineState_SettingUp)
10821 setMachineState(oldState);
10822
10823 /* unlock all hard disks we locked when there is no VM */
10824 if (!aOnline)
10825 {
10826 ErrorInfoKeeper eik;
10827
10828 HRESULT rc1 = lockedMediaMap->Clear();
10829 AssertComRC(rc1);
10830 }
10831
10832 return rc;
10833}
10834
10835
10836/**
10837 * Looks through the given list of media attachments for one with the given parameters
10838 * and returns it, or NULL if not found. The list is a parameter so that backup lists
10839 * can be searched as well if needed.
10840 *
10841 * @param list
10842 * @param aControllerName
10843 * @param aControllerPort
10844 * @param aDevice
10845 * @return
10846 */
10847MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
10848 IN_BSTR aControllerName,
10849 LONG aControllerPort,
10850 LONG aDevice)
10851{
10852 for (MediaData::AttachmentList::const_iterator it = ll.begin();
10853 it != ll.end();
10854 ++it)
10855 {
10856 MediumAttachment *pAttach = *it;
10857 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
10858 return pAttach;
10859 }
10860
10861 return NULL;
10862}
10863
10864/**
10865 * Looks through the given list of media attachments for one with the given parameters
10866 * and returns it, or NULL if not found. The list is a parameter so that backup lists
10867 * can be searched as well if needed.
10868 *
10869 * @param list
10870 * @param aControllerName
10871 * @param aControllerPort
10872 * @param aDevice
10873 * @return
10874 */
10875MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
10876 ComObjPtr<Medium> pMedium)
10877{
10878 for (MediaData::AttachmentList::const_iterator it = ll.begin();
10879 it != ll.end();
10880 ++it)
10881 {
10882 MediumAttachment *pAttach = *it;
10883 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
10884 if (pMediumThis == pMedium)
10885 return pAttach;
10886 }
10887
10888 return NULL;
10889}
10890
10891/**
10892 * Looks through the given list of media attachments for one with the given parameters
10893 * and returns it, or NULL if not found. The list is a parameter so that backup lists
10894 * can be searched as well if needed.
10895 *
10896 * @param list
10897 * @param aControllerName
10898 * @param aControllerPort
10899 * @param aDevice
10900 * @return
10901 */
10902MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
10903 Guid &id)
10904{
10905 for (MediaData::AttachmentList::const_iterator it = ll.begin();
10906 it != ll.end();
10907 ++it)
10908 {
10909 MediumAttachment *pAttach = *it;
10910 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
10911 if (pMediumThis->getId() == id)
10912 return pAttach;
10913 }
10914
10915 return NULL;
10916}
10917
10918/**
10919 * Main implementation for Machine::DetachDevice. This also gets called
10920 * from Machine::prepareUnregister() so it has been taken out for simplicity.
10921 *
10922 * @param pAttach Medium attachment to detach.
10923 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
10924 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
10925 * @return
10926 */
10927HRESULT Machine::detachDevice(MediumAttachment *pAttach,
10928 AutoWriteLock &writeLock,
10929 Snapshot *pSnapshot)
10930{
10931 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
10932 DeviceType_T mediumType = pAttach->getType();
10933
10934 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
10935
10936 if (pAttach->isImplicit())
10937 {
10938 /* attempt to implicitly delete the implicitly created diff */
10939
10940 /// @todo move the implicit flag from MediumAttachment to Medium
10941 /// and forbid any hard disk operation when it is implicit. Or maybe
10942 /// a special media state for it to make it even more simple.
10943
10944 Assert(mMediaData.isBackedUp());
10945
10946 /* will release the lock before the potentially lengthy operation, so
10947 * protect with the special state */
10948 MachineState_T oldState = mData->mMachineState;
10949 setMachineState(MachineState_SettingUp);
10950
10951 writeLock.release();
10952
10953 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
10954 true /*aWait*/);
10955
10956 writeLock.acquire();
10957
10958 setMachineState(oldState);
10959
10960 if (FAILED(rc)) return rc;
10961 }
10962
10963 setModified(IsModified_Storage);
10964 mMediaData.backup();
10965 mMediaData->mAttachments.remove(pAttach);
10966
10967 if (!oldmedium.isNull())
10968 {
10969 // if this is from a snapshot, do not defer detachment to commitMedia()
10970 if (pSnapshot)
10971 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
10972 // else if non-hard disk media, do not defer detachment to commitMedia() either
10973 else if (mediumType != DeviceType_HardDisk)
10974 oldmedium->removeBackReference(mData->mUuid);
10975 }
10976
10977 return S_OK;
10978}
10979
10980/**
10981 * Goes thru all media of the given list and
10982 *
10983 * 1) calls detachDevice() on each of them for this machine and
10984 * 2) adds all Medium objects found in the process to the given list,
10985 * depending on cleanupMode.
10986 *
10987 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
10988 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
10989 * media to the list.
10990 *
10991 * This gets called from Machine::Unregister, both for the actual Machine and
10992 * the SnapshotMachine objects that might be found in the snapshots.
10993 *
10994 * Requires caller and locking. The machine lock must be passed in because it
10995 * will be passed on to detachDevice which needs it for temporary unlocking.
10996 *
10997 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
10998 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
10999 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
11000 * otherwise no media get added.
11001 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
11002 * @return
11003 */
11004HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
11005 Snapshot *pSnapshot,
11006 CleanupMode_T cleanupMode,
11007 MediaList &llMedia)
11008{
11009 Assert(isWriteLockOnCurrentThread());
11010
11011 HRESULT rc;
11012
11013 // make a temporary list because detachDevice invalidates iterators into
11014 // mMediaData->mAttachments
11015 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
11016
11017 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
11018 it != llAttachments2.end();
11019 ++it)
11020 {
11021 ComObjPtr<MediumAttachment> &pAttach = *it;
11022 ComObjPtr<Medium> pMedium = pAttach->getMedium();
11023
11024 if (!pMedium.isNull())
11025 {
11026 AutoCaller mac(pMedium);
11027 if (FAILED(mac.rc())) return mac.rc();
11028 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
11029 DeviceType_T devType = pMedium->getDeviceType();
11030 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
11031 && devType == DeviceType_HardDisk)
11032 || (cleanupMode == CleanupMode_Full)
11033 )
11034 {
11035 llMedia.push_back(pMedium);
11036 ComObjPtr<Medium> pParent = pMedium->getParent();
11037 /*
11038 * Search for medias which are not attached to any machine, but
11039 * in the chain to an attached disk. Mediums are only consided
11040 * if they are:
11041 * - have only one child
11042 * - no references to any machines
11043 * - are of normal medium type
11044 */
11045 while (!pParent.isNull())
11046 {
11047 AutoCaller mac1(pParent);
11048 if (FAILED(mac1.rc())) return mac1.rc();
11049 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
11050 if (pParent->getChildren().size() == 1)
11051 {
11052 if ( pParent->getMachineBackRefCount() == 0
11053 && pParent->getType() == MediumType_Normal
11054 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
11055 llMedia.push_back(pParent);
11056 }
11057 else
11058 break;
11059 pParent = pParent->getParent();
11060 }
11061 }
11062 }
11063
11064 // real machine: then we need to use the proper method
11065 rc = detachDevice(pAttach, writeLock, pSnapshot);
11066
11067 if (FAILED(rc))
11068 return rc;
11069 }
11070
11071 return S_OK;
11072}
11073
11074/**
11075 * Perform deferred hard disk detachments.
11076 *
11077 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
11078 * backed up).
11079 *
11080 * If @a aOnline is @c true then this method will also unlock the old hard disks
11081 * for which the new implicit diffs were created and will lock these new diffs for
11082 * writing.
11083 *
11084 * @param aOnline Whether the VM was online prior to this operation.
11085 *
11086 * @note Locks this object for writing!
11087 */
11088void Machine::commitMedia(bool aOnline /*= false*/)
11089{
11090 AutoCaller autoCaller(this);
11091 AssertComRCReturnVoid(autoCaller.rc());
11092
11093 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11094
11095 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
11096
11097 HRESULT rc = S_OK;
11098
11099 /* no attach/detach operations -- nothing to do */
11100 if (!mMediaData.isBackedUp())
11101 return;
11102
11103 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
11104 bool fMediaNeedsLocking = false;
11105
11106 /* enumerate new attachments */
11107 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11108 it != mMediaData->mAttachments.end();
11109 ++it)
11110 {
11111 MediumAttachment *pAttach = *it;
11112
11113 pAttach->commit();
11114
11115 Medium* pMedium = pAttach->getMedium();
11116 bool fImplicit = pAttach->isImplicit();
11117
11118 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
11119 (pMedium) ? pMedium->getName().c_str() : "NULL",
11120 fImplicit));
11121
11122 /** @todo convert all this Machine-based voodoo to MediumAttachment
11123 * based commit logic. */
11124 if (fImplicit)
11125 {
11126 /* convert implicit attachment to normal */
11127 pAttach->setImplicit(false);
11128
11129 if ( aOnline
11130 && pMedium
11131 && pAttach->getType() == DeviceType_HardDisk
11132 )
11133 {
11134 ComObjPtr<Medium> parent = pMedium->getParent();
11135 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
11136
11137 /* update the appropriate lock list */
11138 MediumLockList *pMediumLockList;
11139 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11140 AssertComRC(rc);
11141 if (pMediumLockList)
11142 {
11143 /* unlock if there's a need to change the locking */
11144 if (!fMediaNeedsLocking)
11145 {
11146 rc = mData->mSession.mLockedMedia.Unlock();
11147 AssertComRC(rc);
11148 fMediaNeedsLocking = true;
11149 }
11150 rc = pMediumLockList->Update(parent, false);
11151 AssertComRC(rc);
11152 rc = pMediumLockList->Append(pMedium, true);
11153 AssertComRC(rc);
11154 }
11155 }
11156
11157 continue;
11158 }
11159
11160 if (pMedium)
11161 {
11162 /* was this medium attached before? */
11163 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
11164 oldIt != oldAtts.end();
11165 ++oldIt)
11166 {
11167 MediumAttachment *pOldAttach = *oldIt;
11168 if (pOldAttach->getMedium() == pMedium)
11169 {
11170 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
11171
11172 /* yes: remove from old to avoid de-association */
11173 oldAtts.erase(oldIt);
11174 break;
11175 }
11176 }
11177 }
11178 }
11179
11180 /* enumerate remaining old attachments and de-associate from the
11181 * current machine state */
11182 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
11183 it != oldAtts.end();
11184 ++it)
11185 {
11186 MediumAttachment *pAttach = *it;
11187 Medium* pMedium = pAttach->getMedium();
11188
11189 /* Detach only hard disks, since DVD/floppy media is detached
11190 * instantly in MountMedium. */
11191 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
11192 {
11193 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
11194
11195 /* now de-associate from the current machine state */
11196 rc = pMedium->removeBackReference(mData->mUuid);
11197 AssertComRC(rc);
11198
11199 if (aOnline)
11200 {
11201 /* unlock since medium is not used anymore */
11202 MediumLockList *pMediumLockList;
11203 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
11204 AssertComRC(rc);
11205 if (pMediumLockList)
11206 {
11207 rc = mData->mSession.mLockedMedia.Remove(pAttach);
11208 AssertComRC(rc);
11209 }
11210 }
11211 }
11212 }
11213
11214 /* take media locks again so that the locking state is consistent */
11215 if (fMediaNeedsLocking)
11216 {
11217 Assert(aOnline);
11218 rc = mData->mSession.mLockedMedia.Lock();
11219 AssertComRC(rc);
11220 }
11221
11222 /* commit the hard disk changes */
11223 mMediaData.commit();
11224
11225 if (isSessionMachine())
11226 {
11227 /*
11228 * Update the parent machine to point to the new owner.
11229 * This is necessary because the stored parent will point to the
11230 * session machine otherwise and cause crashes or errors later
11231 * when the session machine gets invalid.
11232 */
11233 /** @todo Change the MediumAttachment class to behave like any other
11234 * class in this regard by creating peer MediumAttachment
11235 * objects for session machines and share the data with the peer
11236 * machine.
11237 */
11238 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11239 it != mMediaData->mAttachments.end();
11240 ++it)
11241 {
11242 (*it)->updateParentMachine(mPeer);
11243 }
11244
11245 /* attach new data to the primary machine and reshare it */
11246 mPeer->mMediaData.attach(mMediaData);
11247 }
11248
11249 return;
11250}
11251
11252/**
11253 * Perform deferred deletion of implicitly created diffs.
11254 *
11255 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
11256 * backed up).
11257 *
11258 * @note Locks this object for writing!
11259 */
11260void Machine::rollbackMedia()
11261{
11262 AutoCaller autoCaller(this);
11263 AssertComRCReturnVoid(autoCaller.rc());
11264
11265 // AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11266 LogFlowThisFunc(("Entering rollbackMedia\n"));
11267
11268 HRESULT rc = S_OK;
11269
11270 /* no attach/detach operations -- nothing to do */
11271 if (!mMediaData.isBackedUp())
11272 return;
11273
11274 /* enumerate new attachments */
11275 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11276 it != mMediaData->mAttachments.end();
11277 ++it)
11278 {
11279 MediumAttachment *pAttach = *it;
11280 /* Fix up the backrefs for DVD/floppy media. */
11281 if (pAttach->getType() != DeviceType_HardDisk)
11282 {
11283 Medium* pMedium = pAttach->getMedium();
11284 if (pMedium)
11285 {
11286 rc = pMedium->removeBackReference(mData->mUuid);
11287 AssertComRC(rc);
11288 }
11289 }
11290
11291 (*it)->rollback();
11292
11293 pAttach = *it;
11294 /* Fix up the backrefs for DVD/floppy media. */
11295 if (pAttach->getType() != DeviceType_HardDisk)
11296 {
11297 Medium* pMedium = pAttach->getMedium();
11298 if (pMedium)
11299 {
11300 rc = pMedium->addBackReference(mData->mUuid);
11301 AssertComRC(rc);
11302 }
11303 }
11304 }
11305
11306 /** @todo convert all this Machine-based voodoo to MediumAttachment
11307 * based rollback logic. */
11308 deleteImplicitDiffs(Global::IsOnline(mData->mMachineState));
11309
11310 return;
11311}
11312
11313/**
11314 * Returns true if the settings file is located in the directory named exactly
11315 * as the machine; this means, among other things, that the machine directory
11316 * should be auto-renamed.
11317 *
11318 * @param aSettingsDir if not NULL, the full machine settings file directory
11319 * name will be assigned there.
11320 *
11321 * @note Doesn't lock anything.
11322 * @note Not thread safe (must be called from this object's lock).
11323 */
11324bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
11325{
11326 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11327 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
11328 if (aSettingsDir)
11329 *aSettingsDir = strMachineDirName;
11330 strMachineDirName.stripPath(); // vmname
11331 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
11332 strConfigFileOnly.stripPath() // vmname.vbox
11333 .stripExt(); // vmname
11334 /** @todo hack, make somehow use of ComposeMachineFilename */
11335 if (mUserData->s.fDirectoryIncludesUUID)
11336 strConfigFileOnly += Utf8StrFmt(" (%RTuuid)", mData->mUuid.raw());
11337
11338 AssertReturn(!strMachineDirName.isEmpty(), false);
11339 AssertReturn(!strConfigFileOnly.isEmpty(), false);
11340
11341 return strMachineDirName == strConfigFileOnly;
11342}
11343
11344/**
11345 * Discards all changes to machine settings.
11346 *
11347 * @param aNotify Whether to notify the direct session about changes or not.
11348 *
11349 * @note Locks objects for writing!
11350 */
11351void Machine::rollback(bool aNotify)
11352{
11353 AutoCaller autoCaller(this);
11354 AssertComRCReturn(autoCaller.rc(), (void)0);
11355
11356 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11357
11358 if (!mStorageControllers.isNull())
11359 {
11360 if (mStorageControllers.isBackedUp())
11361 {
11362 /* unitialize all new devices (absent in the backed up list). */
11363 StorageControllerList::const_iterator it = mStorageControllers->begin();
11364 StorageControllerList *backedList = mStorageControllers.backedUpData();
11365 while (it != mStorageControllers->end())
11366 {
11367 if ( std::find(backedList->begin(), backedList->end(), *it)
11368 == backedList->end()
11369 )
11370 {
11371 (*it)->uninit();
11372 }
11373 ++it;
11374 }
11375
11376 /* restore the list */
11377 mStorageControllers.rollback();
11378 }
11379
11380 /* rollback any changes to devices after restoring the list */
11381 if (mData->flModifications & IsModified_Storage)
11382 {
11383 StorageControllerList::const_iterator it = mStorageControllers->begin();
11384 while (it != mStorageControllers->end())
11385 {
11386 (*it)->rollback();
11387 ++it;
11388 }
11389 }
11390 }
11391
11392 mUserData.rollback();
11393
11394 mHWData.rollback();
11395
11396 if (mData->flModifications & IsModified_Storage)
11397 rollbackMedia();
11398
11399 if (mBIOSSettings)
11400 mBIOSSettings->rollback();
11401
11402 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
11403 mVRDEServer->rollback();
11404
11405 if (mAudioAdapter)
11406 mAudioAdapter->rollback();
11407
11408 if (mUSBController && (mData->flModifications & IsModified_USB))
11409 mUSBController->rollback();
11410
11411 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
11412 mBandwidthControl->rollback();
11413
11414 if (!mHWData.isNull())
11415 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
11416 NetworkAdapterVector networkAdapters(mNetworkAdapters.size());
11417 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
11418 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
11419
11420 if (mData->flModifications & IsModified_NetworkAdapters)
11421 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
11422 if ( mNetworkAdapters[slot]
11423 && mNetworkAdapters[slot]->isModified())
11424 {
11425 mNetworkAdapters[slot]->rollback();
11426 networkAdapters[slot] = mNetworkAdapters[slot];
11427 }
11428
11429 if (mData->flModifications & IsModified_SerialPorts)
11430 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
11431 if ( mSerialPorts[slot]
11432 && mSerialPorts[slot]->isModified())
11433 {
11434 mSerialPorts[slot]->rollback();
11435 serialPorts[slot] = mSerialPorts[slot];
11436 }
11437
11438 if (mData->flModifications & IsModified_ParallelPorts)
11439 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
11440 if ( mParallelPorts[slot]
11441 && mParallelPorts[slot]->isModified())
11442 {
11443 mParallelPorts[slot]->rollback();
11444 parallelPorts[slot] = mParallelPorts[slot];
11445 }
11446
11447 if (aNotify)
11448 {
11449 /* inform the direct session about changes */
11450
11451 ComObjPtr<Machine> that = this;
11452 uint32_t flModifications = mData->flModifications;
11453 alock.release();
11454
11455 if (flModifications & IsModified_SharedFolders)
11456 that->onSharedFolderChange();
11457
11458 if (flModifications & IsModified_VRDEServer)
11459 that->onVRDEServerChange(/* aRestart */ TRUE);
11460 if (flModifications & IsModified_USB)
11461 that->onUSBControllerChange();
11462
11463 for (ULONG slot = 0; slot < networkAdapters.size(); slot++)
11464 if (networkAdapters[slot])
11465 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
11466 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot++)
11467 if (serialPorts[slot])
11468 that->onSerialPortChange(serialPorts[slot]);
11469 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot++)
11470 if (parallelPorts[slot])
11471 that->onParallelPortChange(parallelPorts[slot]);
11472
11473 if (flModifications & IsModified_Storage)
11474 that->onStorageControllerChange();
11475
11476#if 0
11477 if (flModifications & IsModified_BandwidthControl)
11478 that->onBandwidthControlChange();
11479#endif
11480 }
11481}
11482
11483/**
11484 * Commits all the changes to machine settings.
11485 *
11486 * Note that this operation is supposed to never fail.
11487 *
11488 * @note Locks this object and children for writing.
11489 */
11490void Machine::commit()
11491{
11492 AutoCaller autoCaller(this);
11493 AssertComRCReturnVoid(autoCaller.rc());
11494
11495 AutoCaller peerCaller(mPeer);
11496 AssertComRCReturnVoid(peerCaller.rc());
11497
11498 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
11499
11500 /*
11501 * use safe commit to ensure Snapshot machines (that share mUserData)
11502 * will still refer to a valid memory location
11503 */
11504 mUserData.commitCopy();
11505
11506 mHWData.commit();
11507
11508 if (mMediaData.isBackedUp())
11509 commitMedia(Global::IsOnline(mData->mMachineState));
11510
11511 mBIOSSettings->commit();
11512 mVRDEServer->commit();
11513 mAudioAdapter->commit();
11514 mUSBController->commit();
11515 mBandwidthControl->commit();
11516
11517 /* Since mNetworkAdapters is a list which might have been changed (resized)
11518 * without using the Backupable<> template we need to handle the copying
11519 * of the list entries manually, including the creation of peers for the
11520 * new objects. */
11521 bool commitNetworkAdapters = false;
11522 size_t newSize = Global::getMaxNetworkAdapters(mHWData->mChipsetType);
11523 if (mPeer)
11524 {
11525 /* commit everything, even the ones which will go away */
11526 for (size_t slot = 0; slot < mNetworkAdapters.size(); slot++)
11527 mNetworkAdapters[slot]->commit();
11528 /* copy over the new entries, creating a peer and uninit the original */
11529 mPeer->mNetworkAdapters.resize(RT_MAX(newSize, mPeer->mNetworkAdapters.size()));
11530 for (size_t slot = 0; slot < newSize; slot++)
11531 {
11532 /* look if this adapter has a peer device */
11533 ComObjPtr<NetworkAdapter> peer = mNetworkAdapters[slot]->getPeer();
11534 if (!peer)
11535 {
11536 /* no peer means the adapter is a newly created one;
11537 * create a peer owning data this data share it with */
11538 peer.createObject();
11539 peer->init(mPeer, mNetworkAdapters[slot], true /* aReshare */);
11540 }
11541 mPeer->mNetworkAdapters[slot] = peer;
11542 }
11543 /* uninit any no longer needed network adapters */
11544 for (size_t slot = newSize; slot < mNetworkAdapters.size(); slot++)
11545 mNetworkAdapters[slot]->uninit();
11546 for (size_t slot = newSize; slot < mPeer->mNetworkAdapters.size(); slot++)
11547 {
11548 if (mPeer->mNetworkAdapters[slot])
11549 mPeer->mNetworkAdapters[slot]->uninit();
11550 }
11551 /* Keep the original network adapter count until this point, so that
11552 * discarding a chipset type change will not lose settings. */
11553 mNetworkAdapters.resize(newSize);
11554 mPeer->mNetworkAdapters.resize(newSize);
11555 }
11556 else
11557 {
11558 /* we have no peer (our parent is the newly created machine);
11559 * just commit changes to the network adapters */
11560 commitNetworkAdapters = true;
11561 }
11562 if (commitNetworkAdapters)
11563 {
11564 for (size_t slot = 0; slot < mNetworkAdapters.size(); slot++)
11565 mNetworkAdapters[slot]->commit();
11566 }
11567
11568 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
11569 mSerialPorts[slot]->commit();
11570 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
11571 mParallelPorts[slot]->commit();
11572
11573 bool commitStorageControllers = false;
11574
11575 if (mStorageControllers.isBackedUp())
11576 {
11577 mStorageControllers.commit();
11578
11579 if (mPeer)
11580 {
11581 /* Commit all changes to new controllers (this will reshare data with
11582 * peers for those who have peers) */
11583 StorageControllerList *newList = new StorageControllerList();
11584 StorageControllerList::const_iterator it = mStorageControllers->begin();
11585 while (it != mStorageControllers->end())
11586 {
11587 (*it)->commit();
11588
11589 /* look if this controller has a peer device */
11590 ComObjPtr<StorageController> peer = (*it)->getPeer();
11591 if (!peer)
11592 {
11593 /* no peer means the device is a newly created one;
11594 * create a peer owning data this device share it with */
11595 peer.createObject();
11596 peer->init(mPeer, *it, true /* aReshare */);
11597 }
11598 else
11599 {
11600 /* remove peer from the old list */
11601 mPeer->mStorageControllers->remove(peer);
11602 }
11603 /* and add it to the new list */
11604 newList->push_back(peer);
11605
11606 ++it;
11607 }
11608
11609 /* uninit old peer's controllers that are left */
11610 it = mPeer->mStorageControllers->begin();
11611 while (it != mPeer->mStorageControllers->end())
11612 {
11613 (*it)->uninit();
11614 ++it;
11615 }
11616
11617 /* attach new list of controllers to our peer */
11618 mPeer->mStorageControllers.attach(newList);
11619 }
11620 else
11621 {
11622 /* we have no peer (our parent is the newly created machine);
11623 * just commit changes to devices */
11624 commitStorageControllers = true;
11625 }
11626 }
11627 else
11628 {
11629 /* the list of controllers itself is not changed,
11630 * just commit changes to controllers themselves */
11631 commitStorageControllers = true;
11632 }
11633
11634 if (commitStorageControllers)
11635 {
11636 StorageControllerList::const_iterator it = mStorageControllers->begin();
11637 while (it != mStorageControllers->end())
11638 {
11639 (*it)->commit();
11640 ++it;
11641 }
11642 }
11643
11644 if (isSessionMachine())
11645 {
11646 /* attach new data to the primary machine and reshare it */
11647 mPeer->mUserData.attach(mUserData);
11648 mPeer->mHWData.attach(mHWData);
11649 /* mMediaData is reshared by fixupMedia */
11650 // mPeer->mMediaData.attach(mMediaData);
11651 Assert(mPeer->mMediaData.data() == mMediaData.data());
11652 }
11653}
11654
11655/**
11656 * Copies all the hardware data from the given machine.
11657 *
11658 * Currently, only called when the VM is being restored from a snapshot. In
11659 * particular, this implies that the VM is not running during this method's
11660 * call.
11661 *
11662 * @note This method must be called from under this object's lock.
11663 *
11664 * @note This method doesn't call #commit(), so all data remains backed up and
11665 * unsaved.
11666 */
11667void Machine::copyFrom(Machine *aThat)
11668{
11669 AssertReturnVoid(!isSnapshotMachine());
11670 AssertReturnVoid(aThat->isSnapshotMachine());
11671
11672 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
11673
11674 mHWData.assignCopy(aThat->mHWData);
11675
11676 // create copies of all shared folders (mHWData after attaching a copy
11677 // contains just references to original objects)
11678 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
11679 it != mHWData->mSharedFolders.end();
11680 ++it)
11681 {
11682 ComObjPtr<SharedFolder> folder;
11683 folder.createObject();
11684 HRESULT rc = folder->initCopy(getMachine(), *it);
11685 AssertComRC(rc);
11686 *it = folder;
11687 }
11688
11689 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
11690 mVRDEServer->copyFrom(aThat->mVRDEServer);
11691 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
11692 mUSBController->copyFrom(aThat->mUSBController);
11693 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
11694
11695 /* create private copies of all controllers */
11696 mStorageControllers.backup();
11697 mStorageControllers->clear();
11698 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
11699 it != aThat->mStorageControllers->end();
11700 ++it)
11701 {
11702 ComObjPtr<StorageController> ctrl;
11703 ctrl.createObject();
11704 ctrl->initCopy(this, *it);
11705 mStorageControllers->push_back(ctrl);
11706 }
11707
11708 mNetworkAdapters.resize(aThat->mNetworkAdapters.size());
11709 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
11710 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
11711 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
11712 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
11713 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
11714 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
11715}
11716
11717/**
11718 * Returns whether the given storage controller is hotplug capable.
11719 *
11720 * @returns true if the controller supports hotplugging
11721 * false otherwise.
11722 * @param enmCtrlType The controller type to check for.
11723 */
11724bool Machine::isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
11725{
11726 switch (enmCtrlType)
11727 {
11728 case StorageControllerType_IntelAhci:
11729 return true;
11730 case StorageControllerType_LsiLogic:
11731 case StorageControllerType_LsiLogicSas:
11732 case StorageControllerType_BusLogic:
11733 case StorageControllerType_PIIX3:
11734 case StorageControllerType_PIIX4:
11735 case StorageControllerType_ICH6:
11736 case StorageControllerType_I82078:
11737 default:
11738 return false;
11739 }
11740}
11741
11742#ifdef VBOX_WITH_RESOURCE_USAGE_API
11743
11744void Machine::getDiskList(MediaList &list)
11745{
11746 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11747 it != mMediaData->mAttachments.end();
11748 ++it)
11749 {
11750 MediumAttachment* pAttach = *it;
11751 /* just in case */
11752 AssertStmt(pAttach, continue);
11753
11754 AutoCaller localAutoCallerA(pAttach);
11755 if (FAILED(localAutoCallerA.rc())) continue;
11756
11757 AutoReadLock local_alockA(pAttach COMMA_LOCKVAL_SRC_POS);
11758
11759 if (pAttach->getType() == DeviceType_HardDisk)
11760 list.push_back(pAttach->getMedium());
11761 }
11762}
11763
11764void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
11765{
11766 AssertReturnVoid(isWriteLockOnCurrentThread());
11767 AssertPtrReturnVoid(aCollector);
11768
11769 pm::CollectorHAL *hal = aCollector->getHAL();
11770 /* Create sub metrics */
11771 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
11772 "Percentage of processor time spent in user mode by the VM process.");
11773 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
11774 "Percentage of processor time spent in kernel mode by the VM process.");
11775 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
11776 "Size of resident portion of VM process in memory.");
11777 pm::SubMetric *diskUsageUsed = new pm::SubMetric("Disk/Usage/Used",
11778 "Actual size of all VM disks combined.");
11779 pm::SubMetric *machineNetRx = new pm::SubMetric("Net/Rate/Rx",
11780 "Network receive rate.");
11781 pm::SubMetric *machineNetTx = new pm::SubMetric("Net/Rate/Tx",
11782 "Network transmit rate.");
11783 /* Create and register base metrics */
11784 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
11785 cpuLoadUser, cpuLoadKernel);
11786 aCollector->registerBaseMetric(cpuLoad);
11787 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
11788 ramUsageUsed);
11789 aCollector->registerBaseMetric(ramUsage);
11790 MediaList disks;
11791 getDiskList(disks);
11792 pm::BaseMetric *diskUsage = new pm::MachineDiskUsage(hal, aMachine, disks,
11793 diskUsageUsed);
11794 aCollector->registerBaseMetric(diskUsage);
11795
11796 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
11797 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
11798 new pm::AggregateAvg()));
11799 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
11800 new pm::AggregateMin()));
11801 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
11802 new pm::AggregateMax()));
11803 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
11804 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
11805 new pm::AggregateAvg()));
11806 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
11807 new pm::AggregateMin()));
11808 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
11809 new pm::AggregateMax()));
11810
11811 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
11812 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
11813 new pm::AggregateAvg()));
11814 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
11815 new pm::AggregateMin()));
11816 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
11817 new pm::AggregateMax()));
11818
11819 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed, 0));
11820 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
11821 new pm::AggregateAvg()));
11822 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
11823 new pm::AggregateMin()));
11824 aCollector->registerMetric(new pm::Metric(diskUsage, diskUsageUsed,
11825 new pm::AggregateMax()));
11826
11827
11828 /* Guest metrics collector */
11829 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
11830 aCollector->registerGuest(mCollectorGuest);
11831 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
11832 this, __PRETTY_FUNCTION__, mCollectorGuest));
11833
11834 /* Create sub metrics */
11835 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
11836 "Percentage of processor time spent in user mode as seen by the guest.");
11837 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
11838 "Percentage of processor time spent in kernel mode as seen by the guest.");
11839 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
11840 "Percentage of processor time spent idling as seen by the guest.");
11841
11842 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
11843 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
11844 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
11845 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
11846 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
11847 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
11848
11849 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
11850
11851 /* Create and register base metrics */
11852 pm::BaseMetric *machineNetRate = new pm::MachineNetRate(mCollectorGuest, aMachine,
11853 machineNetRx, machineNetTx);
11854 aCollector->registerBaseMetric(machineNetRate);
11855
11856 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
11857 guestLoadUser, guestLoadKernel, guestLoadIdle);
11858 aCollector->registerBaseMetric(guestCpuLoad);
11859
11860 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
11861 guestMemTotal, guestMemFree,
11862 guestMemBalloon, guestMemShared,
11863 guestMemCache, guestPagedTotal);
11864 aCollector->registerBaseMetric(guestCpuMem);
11865
11866 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, 0));
11867 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateAvg()));
11868 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMin()));
11869 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetRx, new pm::AggregateMax()));
11870
11871 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, 0));
11872 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateAvg()));
11873 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMin()));
11874 aCollector->registerMetric(new pm::Metric(machineNetRate, machineNetTx, new pm::AggregateMax()));
11875
11876 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
11877 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
11878 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
11879 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
11880
11881 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
11882 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
11883 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
11884 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
11885
11886 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
11887 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
11888 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
11889 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
11890
11891 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
11892 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
11893 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
11894 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
11895
11896 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
11897 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
11898 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
11899 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
11900
11901 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
11902 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
11903 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
11904 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
11905
11906 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
11907 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
11908 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
11909 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
11910
11911 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
11912 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
11913 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
11914 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
11915
11916 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
11917 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
11918 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
11919 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
11920}
11921
11922void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
11923{
11924 AssertReturnVoid(isWriteLockOnCurrentThread());
11925
11926 if (aCollector)
11927 {
11928 aCollector->unregisterMetricsFor(aMachine);
11929 aCollector->unregisterBaseMetricsFor(aMachine);
11930 }
11931}
11932
11933#endif /* VBOX_WITH_RESOURCE_USAGE_API */
11934
11935
11936////////////////////////////////////////////////////////////////////////////////
11937
11938DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
11939
11940HRESULT SessionMachine::FinalConstruct()
11941{
11942 LogFlowThisFunc(("\n"));
11943
11944#if defined(RT_OS_WINDOWS)
11945 mIPCSem = NULL;
11946#elif defined(RT_OS_OS2)
11947 mIPCSem = NULLHANDLE;
11948#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11949 mIPCSem = -1;
11950#else
11951# error "Port me!"
11952#endif
11953
11954 return BaseFinalConstruct();
11955}
11956
11957void SessionMachine::FinalRelease()
11958{
11959 LogFlowThisFunc(("\n"));
11960
11961 uninit(Uninit::Unexpected);
11962
11963 BaseFinalRelease();
11964}
11965
11966/**
11967 * @note Must be called only by Machine::openSession() from its own write lock.
11968 */
11969HRESULT SessionMachine::init(Machine *aMachine)
11970{
11971 LogFlowThisFuncEnter();
11972 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
11973
11974 AssertReturn(aMachine, E_INVALIDARG);
11975
11976 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
11977
11978 /* Enclose the state transition NotReady->InInit->Ready */
11979 AutoInitSpan autoInitSpan(this);
11980 AssertReturn(autoInitSpan.isOk(), E_FAIL);
11981
11982 /* create the interprocess semaphore */
11983#if defined(RT_OS_WINDOWS)
11984 mIPCSemName = aMachine->mData->m_strConfigFileFull;
11985 for (size_t i = 0; i < mIPCSemName.length(); i++)
11986 if (mIPCSemName.raw()[i] == '\\')
11987 mIPCSemName.raw()[i] = '/';
11988 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
11989 ComAssertMsgRet(mIPCSem,
11990 ("Cannot create IPC mutex '%ls', err=%d",
11991 mIPCSemName.raw(), ::GetLastError()),
11992 E_FAIL);
11993#elif defined(RT_OS_OS2)
11994 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
11995 aMachine->mData->mUuid.raw());
11996 mIPCSemName = ipcSem;
11997 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
11998 ComAssertMsgRet(arc == NO_ERROR,
11999 ("Cannot create IPC mutex '%s', arc=%ld",
12000 ipcSem.c_str(), arc),
12001 E_FAIL);
12002#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
12003# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
12004# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
12005 /** @todo Check that this still works correctly. */
12006 AssertCompileSize(key_t, 8);
12007# else
12008 AssertCompileSize(key_t, 4);
12009# endif
12010 key_t key;
12011 mIPCSem = -1;
12012 mIPCKey = "0";
12013 for (uint32_t i = 0; i < 1 << 24; i++)
12014 {
12015 key = ((uint32_t)'V' << 24) | i;
12016 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
12017 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
12018 {
12019 mIPCSem = sem;
12020 if (sem >= 0)
12021 mIPCKey = BstrFmt("%u", key);
12022 break;
12023 }
12024 }
12025# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
12026 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
12027 char *pszSemName = NULL;
12028 RTStrUtf8ToCurrentCP(&pszSemName, semName);
12029 key_t key = ::ftok(pszSemName, 'V');
12030 RTStrFree(pszSemName);
12031
12032 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
12033# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
12034
12035 int errnoSave = errno;
12036 if (mIPCSem < 0 && errnoSave == ENOSYS)
12037 {
12038 setError(E_FAIL,
12039 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
12040 "support for SysV IPC. Check the host kernel configuration for "
12041 "CONFIG_SYSVIPC=y"));
12042 return E_FAIL;
12043 }
12044 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
12045 * the IPC semaphores */
12046 if (mIPCSem < 0 && errnoSave == ENOSPC)
12047 {
12048#ifdef RT_OS_LINUX
12049 setError(E_FAIL,
12050 tr("Cannot create IPC semaphore because the system limit for the "
12051 "maximum number of semaphore sets (SEMMNI), or the system wide "
12052 "maximum number of semaphores (SEMMNS) would be exceeded. The "
12053 "current set of SysV IPC semaphores can be determined from "
12054 "the file /proc/sysvipc/sem"));
12055#else
12056 setError(E_FAIL,
12057 tr("Cannot create IPC semaphore because the system-imposed limit "
12058 "on the maximum number of allowed semaphores or semaphore "
12059 "identifiers system-wide would be exceeded"));
12060#endif
12061 return E_FAIL;
12062 }
12063 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
12064 E_FAIL);
12065 /* set the initial value to 1 */
12066 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
12067 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
12068 E_FAIL);
12069#else
12070# error "Port me!"
12071#endif
12072
12073 /* memorize the peer Machine */
12074 unconst(mPeer) = aMachine;
12075 /* share the parent pointer */
12076 unconst(mParent) = aMachine->mParent;
12077
12078 /* take the pointers to data to share */
12079 mData.share(aMachine->mData);
12080 mSSData.share(aMachine->mSSData);
12081
12082 mUserData.share(aMachine->mUserData);
12083 mHWData.share(aMachine->mHWData);
12084 mMediaData.share(aMachine->mMediaData);
12085
12086 mStorageControllers.allocate();
12087 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
12088 it != aMachine->mStorageControllers->end();
12089 ++it)
12090 {
12091 ComObjPtr<StorageController> ctl;
12092 ctl.createObject();
12093 ctl->init(this, *it);
12094 mStorageControllers->push_back(ctl);
12095 }
12096
12097 unconst(mBIOSSettings).createObject();
12098 mBIOSSettings->init(this, aMachine->mBIOSSettings);
12099 /* create another VRDEServer object that will be mutable */
12100 unconst(mVRDEServer).createObject();
12101 mVRDEServer->init(this, aMachine->mVRDEServer);
12102 /* create another audio adapter object that will be mutable */
12103 unconst(mAudioAdapter).createObject();
12104 mAudioAdapter->init(this, aMachine->mAudioAdapter);
12105 /* create a list of serial ports that will be mutable */
12106 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
12107 {
12108 unconst(mSerialPorts[slot]).createObject();
12109 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
12110 }
12111 /* create a list of parallel ports that will be mutable */
12112 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
12113 {
12114 unconst(mParallelPorts[slot]).createObject();
12115 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
12116 }
12117 /* create another USB controller object that will be mutable */
12118 unconst(mUSBController).createObject();
12119 mUSBController->init(this, aMachine->mUSBController);
12120
12121 /* create a list of network adapters that will be mutable */
12122 mNetworkAdapters.resize(aMachine->mNetworkAdapters.size());
12123 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
12124 {
12125 unconst(mNetworkAdapters[slot]).createObject();
12126 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
12127 }
12128
12129 /* create another bandwidth control object that will be mutable */
12130 unconst(mBandwidthControl).createObject();
12131 mBandwidthControl->init(this, aMachine->mBandwidthControl);
12132
12133 /* default is to delete saved state on Saved -> PoweredOff transition */
12134 mRemoveSavedState = true;
12135
12136 /* Confirm a successful initialization when it's the case */
12137 autoInitSpan.setSucceeded();
12138
12139 LogFlowThisFuncLeave();
12140 return S_OK;
12141}
12142
12143/**
12144 * Uninitializes this session object. If the reason is other than
12145 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
12146 *
12147 * @param aReason uninitialization reason
12148 *
12149 * @note Locks mParent + this object for writing.
12150 */
12151void SessionMachine::uninit(Uninit::Reason aReason)
12152{
12153 LogFlowThisFuncEnter();
12154 LogFlowThisFunc(("reason=%d\n", aReason));
12155
12156 /*
12157 * Strongly reference ourselves to prevent this object deletion after
12158 * mData->mSession.mMachine.setNull() below (which can release the last
12159 * reference and call the destructor). Important: this must be done before
12160 * accessing any members (and before AutoUninitSpan that does it as well).
12161 * This self reference will be released as the very last step on return.
12162 */
12163 ComObjPtr<SessionMachine> selfRef = this;
12164
12165 /* Enclose the state transition Ready->InUninit->NotReady */
12166 AutoUninitSpan autoUninitSpan(this);
12167 if (autoUninitSpan.uninitDone())
12168 {
12169 LogFlowThisFunc(("Already uninitialized\n"));
12170 LogFlowThisFuncLeave();
12171 return;
12172 }
12173
12174 if (autoUninitSpan.initFailed())
12175 {
12176 /* We've been called by init() because it's failed. It's not really
12177 * necessary (nor it's safe) to perform the regular uninit sequence
12178 * below, the following is enough.
12179 */
12180 LogFlowThisFunc(("Initialization failed.\n"));
12181#if defined(RT_OS_WINDOWS)
12182 if (mIPCSem)
12183 ::CloseHandle(mIPCSem);
12184 mIPCSem = NULL;
12185#elif defined(RT_OS_OS2)
12186 if (mIPCSem != NULLHANDLE)
12187 ::DosCloseMutexSem(mIPCSem);
12188 mIPCSem = NULLHANDLE;
12189#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
12190 if (mIPCSem >= 0)
12191 ::semctl(mIPCSem, 0, IPC_RMID);
12192 mIPCSem = -1;
12193# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
12194 mIPCKey = "0";
12195# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
12196#else
12197# error "Port me!"
12198#endif
12199 uninitDataAndChildObjects();
12200 mData.free();
12201 unconst(mParent) = NULL;
12202 unconst(mPeer) = NULL;
12203 LogFlowThisFuncLeave();
12204 return;
12205 }
12206
12207 MachineState_T lastState;
12208 {
12209 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
12210 lastState = mData->mMachineState;
12211 }
12212 NOREF(lastState);
12213
12214#ifdef VBOX_WITH_USB
12215 // release all captured USB devices, but do this before requesting the locks below
12216 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
12217 {
12218 /* Console::captureUSBDevices() is called in the VM process only after
12219 * setting the machine state to Starting or Restoring.
12220 * Console::detachAllUSBDevices() will be called upon successful
12221 * termination. So, we need to release USB devices only if there was
12222 * an abnormal termination of a running VM.
12223 *
12224 * This is identical to SessionMachine::DetachAllUSBDevices except
12225 * for the aAbnormal argument. */
12226 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
12227 AssertComRC(rc);
12228 NOREF(rc);
12229
12230 USBProxyService *service = mParent->host()->usbProxyService();
12231 if (service)
12232 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
12233 }
12234#endif /* VBOX_WITH_USB */
12235
12236 // we need to lock this object in uninit() because the lock is shared
12237 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
12238 // and others need mParent lock, and USB needs host lock.
12239 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
12240
12241#if 0
12242 // Trigger async cleanup tasks, avoid doing things here which are not
12243 // vital to be done immediately and maybe need more locks. This calls
12244 // Machine::unregisterMetrics().
12245 mParent->onMachineUninit(mPeer);
12246#else
12247 /*
12248 * It is safe to call Machine::unregisterMetrics() here because
12249 * PerformanceCollector::samplerCallback no longer accesses guest methods
12250 * holding the lock.
12251 */
12252 unregisterMetrics(mParent->performanceCollector(), mPeer);
12253#endif
12254 /* The guest must be unregistered after its metrics (@bugref{5949}). */
12255 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
12256 this, __PRETTY_FUNCTION__, mCollectorGuest));
12257 if (mCollectorGuest)
12258 {
12259 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
12260 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
12261 mCollectorGuest = NULL;
12262 }
12263
12264 if (aReason == Uninit::Abnormal)
12265 {
12266 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
12267 Global::IsOnlineOrTransient(lastState)));
12268
12269 /* reset the state to Aborted */
12270 if (mData->mMachineState != MachineState_Aborted)
12271 setMachineState(MachineState_Aborted);
12272 }
12273
12274 // any machine settings modified?
12275 if (mData->flModifications)
12276 {
12277 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
12278 rollback(false /* aNotify */);
12279 }
12280
12281 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
12282 || !mConsoleTaskData.mSnapshot);
12283 if (!mConsoleTaskData.strStateFilePath.isEmpty())
12284 {
12285 LogWarningThisFunc(("canceling failed save state request!\n"));
12286 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
12287 }
12288 else if (!mConsoleTaskData.mSnapshot.isNull())
12289 {
12290 LogWarningThisFunc(("canceling untaken snapshot!\n"));
12291
12292 /* delete all differencing hard disks created (this will also attach
12293 * their parents back by rolling back mMediaData) */
12294 rollbackMedia();
12295
12296 // delete the saved state file (it might have been already created)
12297 // AFTER killing the snapshot so that releaseSavedStateFile() won't
12298 // think it's still in use
12299 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
12300 mConsoleTaskData.mSnapshot->uninit();
12301 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
12302 }
12303
12304 if (!mData->mSession.mType.isEmpty())
12305 {
12306 /* mType is not null when this machine's process has been started by
12307 * Machine::LaunchVMProcess(), therefore it is our child. We
12308 * need to queue the PID to reap the process (and avoid zombies on
12309 * Linux). */
12310 Assert(mData->mSession.mPID != NIL_RTPROCESS);
12311 mParent->addProcessToReap(mData->mSession.mPID);
12312 }
12313
12314 mData->mSession.mPID = NIL_RTPROCESS;
12315
12316 if (aReason == Uninit::Unexpected)
12317 {
12318 /* Uninitialization didn't come from #checkForDeath(), so tell the
12319 * client watcher thread to update the set of machines that have open
12320 * sessions. */
12321 mParent->updateClientWatcher();
12322 }
12323
12324 /* uninitialize all remote controls */
12325 if (mData->mSession.mRemoteControls.size())
12326 {
12327 LogFlowThisFunc(("Closing remote sessions (%d):\n",
12328 mData->mSession.mRemoteControls.size()));
12329
12330 Data::Session::RemoteControlList::iterator it =
12331 mData->mSession.mRemoteControls.begin();
12332 while (it != mData->mSession.mRemoteControls.end())
12333 {
12334 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
12335 HRESULT rc = (*it)->Uninitialize();
12336 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
12337 if (FAILED(rc))
12338 LogWarningThisFunc(("Forgot to close the remote session?\n"));
12339 ++it;
12340 }
12341 mData->mSession.mRemoteControls.clear();
12342 }
12343
12344 /*
12345 * An expected uninitialization can come only from #checkForDeath().
12346 * Otherwise it means that something's gone really wrong (for example,
12347 * the Session implementation has released the VirtualBox reference
12348 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
12349 * etc). However, it's also possible, that the client releases the IPC
12350 * semaphore correctly (i.e. before it releases the VirtualBox reference),
12351 * but the VirtualBox release event comes first to the server process.
12352 * This case is practically possible, so we should not assert on an
12353 * unexpected uninit, just log a warning.
12354 */
12355
12356 if ((aReason == Uninit::Unexpected))
12357 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
12358
12359 if (aReason != Uninit::Normal)
12360 {
12361 mData->mSession.mDirectControl.setNull();
12362 }
12363 else
12364 {
12365 /* this must be null here (see #OnSessionEnd()) */
12366 Assert(mData->mSession.mDirectControl.isNull());
12367 Assert(mData->mSession.mState == SessionState_Unlocking);
12368 Assert(!mData->mSession.mProgress.isNull());
12369 }
12370 if (mData->mSession.mProgress)
12371 {
12372 if (aReason == Uninit::Normal)
12373 mData->mSession.mProgress->notifyComplete(S_OK);
12374 else
12375 mData->mSession.mProgress->notifyComplete(E_FAIL,
12376 COM_IIDOF(ISession),
12377 getComponentName(),
12378 tr("The VM session was aborted"));
12379 mData->mSession.mProgress.setNull();
12380 }
12381
12382 /* remove the association between the peer machine and this session machine */
12383 Assert( (SessionMachine*)mData->mSession.mMachine == this
12384 || aReason == Uninit::Unexpected);
12385
12386 /* reset the rest of session data */
12387 mData->mSession.mMachine.setNull();
12388 mData->mSession.mState = SessionState_Unlocked;
12389 mData->mSession.mType.setNull();
12390
12391 /* close the interprocess semaphore before leaving the exclusive lock */
12392#if defined(RT_OS_WINDOWS)
12393 if (mIPCSem)
12394 ::CloseHandle(mIPCSem);
12395 mIPCSem = NULL;
12396#elif defined(RT_OS_OS2)
12397 if (mIPCSem != NULLHANDLE)
12398 ::DosCloseMutexSem(mIPCSem);
12399 mIPCSem = NULLHANDLE;
12400#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
12401 if (mIPCSem >= 0)
12402 ::semctl(mIPCSem, 0, IPC_RMID);
12403 mIPCSem = -1;
12404# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
12405 mIPCKey = "0";
12406# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
12407#else
12408# error "Port me!"
12409#endif
12410
12411 /* fire an event */
12412 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
12413
12414 uninitDataAndChildObjects();
12415
12416 /* free the essential data structure last */
12417 mData.free();
12418
12419 /* release the exclusive lock before setting the below two to NULL */
12420 multilock.release();
12421
12422 unconst(mParent) = NULL;
12423 unconst(mPeer) = NULL;
12424
12425 LogFlowThisFuncLeave();
12426}
12427
12428// util::Lockable interface
12429////////////////////////////////////////////////////////////////////////////////
12430
12431/**
12432 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
12433 * with the primary Machine instance (mPeer).
12434 */
12435RWLockHandle *SessionMachine::lockHandle() const
12436{
12437 AssertReturn(mPeer != NULL, NULL);
12438 return mPeer->lockHandle();
12439}
12440
12441// IInternalMachineControl methods
12442////////////////////////////////////////////////////////////////////////////////
12443
12444/**
12445 * Passes collected guest statistics to performance collector object
12446 */
12447STDMETHODIMP SessionMachine::ReportVmStatistics(ULONG aValidStats, ULONG aCpuUser,
12448 ULONG aCpuKernel, ULONG aCpuIdle,
12449 ULONG aMemTotal, ULONG aMemFree,
12450 ULONG aMemBalloon, ULONG aMemShared,
12451 ULONG aMemCache, ULONG aPageTotal,
12452 ULONG aAllocVMM, ULONG aFreeVMM,
12453 ULONG aBalloonedVMM, ULONG aSharedVMM,
12454 ULONG aVmNetRx, ULONG aVmNetTx)
12455{
12456 if (mCollectorGuest)
12457 mCollectorGuest->updateStats(aValidStats, aCpuUser, aCpuKernel, aCpuIdle,
12458 aMemTotal, aMemFree, aMemBalloon, aMemShared,
12459 aMemCache, aPageTotal, aAllocVMM, aFreeVMM,
12460 aBalloonedVMM, aSharedVMM, aVmNetRx, aVmNetTx);
12461
12462 return S_OK;
12463}
12464
12465/**
12466 * @note Locks this object for writing.
12467 */
12468STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
12469{
12470 AutoCaller autoCaller(this);
12471 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12472
12473 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12474
12475 mRemoveSavedState = aRemove;
12476
12477 return S_OK;
12478}
12479
12480/**
12481 * @note Locks the same as #setMachineState() does.
12482 */
12483STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
12484{
12485 return setMachineState(aMachineState);
12486}
12487
12488/**
12489 * @note Locks this object for reading.
12490 */
12491STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
12492{
12493 AutoCaller autoCaller(this);
12494 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12495
12496 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12497
12498#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
12499 mIPCSemName.cloneTo(aId);
12500 return S_OK;
12501#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
12502# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
12503 mIPCKey.cloneTo(aId);
12504# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
12505 mData->m_strConfigFileFull.cloneTo(aId);
12506# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
12507 return S_OK;
12508#else
12509# error "Port me!"
12510#endif
12511}
12512
12513/**
12514 * @note Locks this object for writing.
12515 */
12516STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
12517{
12518 LogFlowThisFunc(("aProgress=%p\n", aProgress));
12519 AutoCaller autoCaller(this);
12520 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12521
12522 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12523
12524 if (mData->mSession.mState != SessionState_Locked)
12525 return VBOX_E_INVALID_OBJECT_STATE;
12526
12527 if (!mData->mSession.mProgress.isNull())
12528 mData->mSession.mProgress->setOtherProgressObject(aProgress);
12529
12530 LogFlowThisFunc(("returns S_OK.\n"));
12531 return S_OK;
12532}
12533
12534/**
12535 * @note Locks this object for writing.
12536 */
12537STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
12538{
12539 AutoCaller autoCaller(this);
12540 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12541
12542 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12543
12544 if (mData->mSession.mState != SessionState_Locked)
12545 return VBOX_E_INVALID_OBJECT_STATE;
12546
12547 /* Finalize the LaunchVMProcess progress object. */
12548 if (mData->mSession.mProgress)
12549 {
12550 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
12551 mData->mSession.mProgress.setNull();
12552 }
12553
12554 if (SUCCEEDED((HRESULT)iResult))
12555 {
12556#ifdef VBOX_WITH_RESOURCE_USAGE_API
12557 /* The VM has been powered up successfully, so it makes sense
12558 * now to offer the performance metrics for a running machine
12559 * object. Doing it earlier wouldn't be safe. */
12560 registerMetrics(mParent->performanceCollector(), mPeer,
12561 mData->mSession.mPID);
12562#endif /* VBOX_WITH_RESOURCE_USAGE_API */
12563 }
12564
12565 return S_OK;
12566}
12567
12568/**
12569 * @note Locks this object for writing.
12570 */
12571STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
12572{
12573 LogFlowThisFuncEnter();
12574
12575 CheckComArgOutPointerValid(aProgress);
12576
12577 AutoCaller autoCaller(this);
12578 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12579
12580 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12581
12582 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
12583 E_FAIL);
12584
12585 /* create a progress object to track operation completion */
12586 ComObjPtr<Progress> pProgress;
12587 pProgress.createObject();
12588 pProgress->init(getVirtualBox(),
12589 static_cast<IMachine *>(this) /* aInitiator */,
12590 Bstr(tr("Stopping the virtual machine")).raw(),
12591 FALSE /* aCancelable */);
12592
12593 /* fill in the console task data */
12594 mConsoleTaskData.mLastState = mData->mMachineState;
12595 mConsoleTaskData.mProgress = pProgress;
12596
12597 /* set the state to Stopping (this is expected by Console::PowerDown()) */
12598 setMachineState(MachineState_Stopping);
12599
12600 pProgress.queryInterfaceTo(aProgress);
12601
12602 return S_OK;
12603}
12604
12605/**
12606 * @note Locks this object for writing.
12607 */
12608STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
12609{
12610 LogFlowThisFuncEnter();
12611
12612 AutoCaller autoCaller(this);
12613 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12614
12615 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12616
12617 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
12618 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
12619 && mConsoleTaskData.mLastState != MachineState_Null,
12620 E_FAIL);
12621
12622 /*
12623 * On failure, set the state to the state we had when BeginPoweringDown()
12624 * was called (this is expected by Console::PowerDown() and the associated
12625 * task). On success the VM process already changed the state to
12626 * MachineState_PoweredOff, so no need to do anything.
12627 */
12628 if (FAILED(iResult))
12629 setMachineState(mConsoleTaskData.mLastState);
12630
12631 /* notify the progress object about operation completion */
12632 Assert(mConsoleTaskData.mProgress);
12633 if (SUCCEEDED(iResult))
12634 mConsoleTaskData.mProgress->notifyComplete(S_OK);
12635 else
12636 {
12637 Utf8Str strErrMsg(aErrMsg);
12638 if (strErrMsg.length())
12639 mConsoleTaskData.mProgress->notifyComplete(iResult,
12640 COM_IIDOF(ISession),
12641 getComponentName(),
12642 strErrMsg.c_str());
12643 else
12644 mConsoleTaskData.mProgress->notifyComplete(iResult);
12645 }
12646
12647 /* clear out the temporary saved state data */
12648 mConsoleTaskData.mLastState = MachineState_Null;
12649 mConsoleTaskData.mProgress.setNull();
12650
12651 LogFlowThisFuncLeave();
12652 return S_OK;
12653}
12654
12655
12656/**
12657 * Goes through the USB filters of the given machine to see if the given
12658 * device matches any filter or not.
12659 *
12660 * @note Locks the same as USBController::hasMatchingFilter() does.
12661 */
12662STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
12663 BOOL *aMatched,
12664 ULONG *aMaskedIfs)
12665{
12666 LogFlowThisFunc(("\n"));
12667
12668 CheckComArgNotNull(aUSBDevice);
12669 CheckComArgOutPointerValid(aMatched);
12670
12671 AutoCaller autoCaller(this);
12672 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12673
12674#ifdef VBOX_WITH_USB
12675 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
12676#else
12677 NOREF(aUSBDevice);
12678 NOREF(aMaskedIfs);
12679 *aMatched = FALSE;
12680#endif
12681
12682 return S_OK;
12683}
12684
12685/**
12686 * @note Locks the same as Host::captureUSBDevice() does.
12687 */
12688STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
12689{
12690 LogFlowThisFunc(("\n"));
12691
12692 AutoCaller autoCaller(this);
12693 AssertComRCReturnRC(autoCaller.rc());
12694
12695#ifdef VBOX_WITH_USB
12696 /* if captureDeviceForVM() fails, it must have set extended error info */
12697 clearError();
12698 MultiResult rc = mParent->host()->checkUSBProxyService();
12699 if (FAILED(rc)) return rc;
12700
12701 USBProxyService *service = mParent->host()->usbProxyService();
12702 AssertReturn(service, E_FAIL);
12703 return service->captureDeviceForVM(this, Guid(aId).ref());
12704#else
12705 NOREF(aId);
12706 return E_NOTIMPL;
12707#endif
12708}
12709
12710/**
12711 * @note Locks the same as Host::detachUSBDevice() does.
12712 */
12713STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
12714{
12715 LogFlowThisFunc(("\n"));
12716
12717 AutoCaller autoCaller(this);
12718 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12719
12720#ifdef VBOX_WITH_USB
12721 USBProxyService *service = mParent->host()->usbProxyService();
12722 AssertReturn(service, E_FAIL);
12723 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
12724#else
12725 NOREF(aId);
12726 NOREF(aDone);
12727 return E_NOTIMPL;
12728#endif
12729}
12730
12731/**
12732 * Inserts all machine filters to the USB proxy service and then calls
12733 * Host::autoCaptureUSBDevices().
12734 *
12735 * Called by Console from the VM process upon VM startup.
12736 *
12737 * @note Locks what called methods lock.
12738 */
12739STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
12740{
12741 LogFlowThisFunc(("\n"));
12742
12743 AutoCaller autoCaller(this);
12744 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12745
12746#ifdef VBOX_WITH_USB
12747 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
12748 AssertComRC(rc);
12749 NOREF(rc);
12750
12751 USBProxyService *service = mParent->host()->usbProxyService();
12752 AssertReturn(service, E_FAIL);
12753 return service->autoCaptureDevicesForVM(this);
12754#else
12755 return S_OK;
12756#endif
12757}
12758
12759/**
12760 * Removes all machine filters from the USB proxy service and then calls
12761 * Host::detachAllUSBDevices().
12762 *
12763 * Called by Console from the VM process upon normal VM termination or by
12764 * SessionMachine::uninit() upon abnormal VM termination (from under the
12765 * Machine/SessionMachine lock).
12766 *
12767 * @note Locks what called methods lock.
12768 */
12769STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
12770{
12771 LogFlowThisFunc(("\n"));
12772
12773 AutoCaller autoCaller(this);
12774 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12775
12776#ifdef VBOX_WITH_USB
12777 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
12778 AssertComRC(rc);
12779 NOREF(rc);
12780
12781 USBProxyService *service = mParent->host()->usbProxyService();
12782 AssertReturn(service, E_FAIL);
12783 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
12784#else
12785 NOREF(aDone);
12786 return S_OK;
12787#endif
12788}
12789
12790/**
12791 * @note Locks this object for writing.
12792 */
12793STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
12794 IProgress **aProgress)
12795{
12796 LogFlowThisFuncEnter();
12797
12798 AssertReturn(aSession, E_INVALIDARG);
12799 AssertReturn(aProgress, E_INVALIDARG);
12800
12801 AutoCaller autoCaller(this);
12802
12803 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
12804 /*
12805 * We don't assert below because it might happen that a non-direct session
12806 * informs us it is closed right after we've been uninitialized -- it's ok.
12807 */
12808 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12809
12810 /* get IInternalSessionControl interface */
12811 ComPtr<IInternalSessionControl> control(aSession);
12812
12813 ComAssertRet(!control.isNull(), E_INVALIDARG);
12814
12815 /* Creating a Progress object requires the VirtualBox lock, and
12816 * thus locking it here is required by the lock order rules. */
12817 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
12818
12819 if (control == mData->mSession.mDirectControl)
12820 {
12821 ComAssertRet(aProgress, E_POINTER);
12822
12823 /* The direct session is being normally closed by the client process
12824 * ----------------------------------------------------------------- */
12825
12826 /* go to the closing state (essential for all open*Session() calls and
12827 * for #checkForDeath()) */
12828 Assert(mData->mSession.mState == SessionState_Locked);
12829 mData->mSession.mState = SessionState_Unlocking;
12830
12831 /* set direct control to NULL to release the remote instance */
12832 mData->mSession.mDirectControl.setNull();
12833 LogFlowThisFunc(("Direct control is set to NULL\n"));
12834
12835 if (mData->mSession.mProgress)
12836 {
12837 /* finalize the progress, someone might wait if a frontend
12838 * closes the session before powering on the VM. */
12839 mData->mSession.mProgress->notifyComplete(E_FAIL,
12840 COM_IIDOF(ISession),
12841 getComponentName(),
12842 tr("The VM session was closed before any attempt to power it on"));
12843 mData->mSession.mProgress.setNull();
12844 }
12845
12846 /* Create the progress object the client will use to wait until
12847 * #checkForDeath() is called to uninitialize this session object after
12848 * it releases the IPC semaphore.
12849 * Note! Because we're "reusing" mProgress here, this must be a proxy
12850 * object just like for LaunchVMProcess. */
12851 Assert(mData->mSession.mProgress.isNull());
12852 ComObjPtr<ProgressProxy> progress;
12853 progress.createObject();
12854 ComPtr<IUnknown> pPeer(mPeer);
12855 progress->init(mParent, pPeer,
12856 Bstr(tr("Closing session")).raw(),
12857 FALSE /* aCancelable */);
12858 progress.queryInterfaceTo(aProgress);
12859 mData->mSession.mProgress = progress;
12860 }
12861 else
12862 {
12863 /* the remote session is being normally closed */
12864 Data::Session::RemoteControlList::iterator it =
12865 mData->mSession.mRemoteControls.begin();
12866 while (it != mData->mSession.mRemoteControls.end())
12867 {
12868 if (control == *it)
12869 break;
12870 ++it;
12871 }
12872 BOOL found = it != mData->mSession.mRemoteControls.end();
12873 ComAssertMsgRet(found, ("The session is not found in the session list!"),
12874 E_INVALIDARG);
12875 // This MUST be erase(it), not remove(*it) as the latter triggers a
12876 // very nasty use after free due to the place where the value "lives".
12877 mData->mSession.mRemoteControls.erase(it);
12878 }
12879
12880 /* signal the client watcher thread, because the client is going away */
12881 mParent->updateClientWatcher();
12882
12883 LogFlowThisFuncLeave();
12884 return S_OK;
12885}
12886
12887/**
12888 * @note Locks this object for writing.
12889 */
12890STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
12891{
12892 LogFlowThisFuncEnter();
12893
12894 CheckComArgOutPointerValid(aProgress);
12895 CheckComArgOutPointerValid(aStateFilePath);
12896
12897 AutoCaller autoCaller(this);
12898 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12899
12900 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12901
12902 AssertReturn( mData->mMachineState == MachineState_Paused
12903 && mConsoleTaskData.mLastState == MachineState_Null
12904 && mConsoleTaskData.strStateFilePath.isEmpty(),
12905 E_FAIL);
12906
12907 /* create a progress object to track operation completion */
12908 ComObjPtr<Progress> pProgress;
12909 pProgress.createObject();
12910 pProgress->init(getVirtualBox(),
12911 static_cast<IMachine *>(this) /* aInitiator */,
12912 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
12913 FALSE /* aCancelable */);
12914
12915 Utf8Str strStateFilePath;
12916 /* stateFilePath is null when the machine is not running */
12917 if (mData->mMachineState == MachineState_Paused)
12918 composeSavedStateFilename(strStateFilePath);
12919
12920 /* fill in the console task data */
12921 mConsoleTaskData.mLastState = mData->mMachineState;
12922 mConsoleTaskData.strStateFilePath = strStateFilePath;
12923 mConsoleTaskData.mProgress = pProgress;
12924
12925 /* set the state to Saving (this is expected by Console::SaveState()) */
12926 setMachineState(MachineState_Saving);
12927
12928 strStateFilePath.cloneTo(aStateFilePath);
12929 pProgress.queryInterfaceTo(aProgress);
12930
12931 return S_OK;
12932}
12933
12934/**
12935 * @note Locks mParent + this object for writing.
12936 */
12937STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
12938{
12939 LogFlowThisFunc(("\n"));
12940
12941 AutoCaller autoCaller(this);
12942 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12943
12944 /* endSavingState() need mParent lock */
12945 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
12946
12947 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
12948 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
12949 && mConsoleTaskData.mLastState != MachineState_Null
12950 && !mConsoleTaskData.strStateFilePath.isEmpty(),
12951 E_FAIL);
12952
12953 /*
12954 * On failure, set the state to the state we had when BeginSavingState()
12955 * was called (this is expected by Console::SaveState() and the associated
12956 * task). On success the VM process already changed the state to
12957 * MachineState_Saved, so no need to do anything.
12958 */
12959 if (FAILED(iResult))
12960 setMachineState(mConsoleTaskData.mLastState);
12961
12962 return endSavingState(iResult, aErrMsg);
12963}
12964
12965/**
12966 * @note Locks this object for writing.
12967 */
12968STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
12969{
12970 LogFlowThisFunc(("\n"));
12971
12972 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
12973
12974 AutoCaller autoCaller(this);
12975 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12976
12977 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12978
12979 AssertReturn( mData->mMachineState == MachineState_PoweredOff
12980 || mData->mMachineState == MachineState_Teleported
12981 || mData->mMachineState == MachineState_Aborted
12982 , E_FAIL); /** @todo setError. */
12983
12984 Utf8Str stateFilePathFull = aSavedStateFile;
12985 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
12986 if (RT_FAILURE(vrc))
12987 return setError(VBOX_E_FILE_ERROR,
12988 tr("Invalid saved state file path '%ls' (%Rrc)"),
12989 aSavedStateFile,
12990 vrc);
12991
12992 mSSData->strStateFilePath = stateFilePathFull;
12993
12994 /* The below setMachineState() will detect the state transition and will
12995 * update the settings file */
12996
12997 return setMachineState(MachineState_Saved);
12998}
12999
13000STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
13001 ComSafeArrayOut(BSTR, aValues),
13002 ComSafeArrayOut(LONG64, aTimestamps),
13003 ComSafeArrayOut(BSTR, aFlags))
13004{
13005 LogFlowThisFunc(("\n"));
13006
13007#ifdef VBOX_WITH_GUEST_PROPS
13008 using namespace guestProp;
13009
13010 AutoCaller autoCaller(this);
13011 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13012
13013 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13014
13015 CheckComArgOutSafeArrayPointerValid(aNames);
13016 CheckComArgOutSafeArrayPointerValid(aValues);
13017 CheckComArgOutSafeArrayPointerValid(aTimestamps);
13018 CheckComArgOutSafeArrayPointerValid(aFlags);
13019
13020 size_t cEntries = mHWData->mGuestProperties.size();
13021 com::SafeArray<BSTR> names(cEntries);
13022 com::SafeArray<BSTR> values(cEntries);
13023 com::SafeArray<LONG64> timestamps(cEntries);
13024 com::SafeArray<BSTR> flags(cEntries);
13025 unsigned i = 0;
13026 for (HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.begin();
13027 it != mHWData->mGuestProperties.end();
13028 ++it)
13029 {
13030 char szFlags[MAX_FLAGS_LEN + 1];
13031 it->first.cloneTo(&names[i]);
13032 it->second.strValue.cloneTo(&values[i]);
13033 timestamps[i] = it->second.mTimestamp;
13034 /* If it is NULL, keep it NULL. */
13035 if (it->second.mFlags)
13036 {
13037 writeFlags(it->second.mFlags, szFlags);
13038 Bstr(szFlags).cloneTo(&flags[i]);
13039 }
13040 else
13041 flags[i] = NULL;
13042 ++i;
13043 }
13044 names.detachTo(ComSafeArrayOutArg(aNames));
13045 values.detachTo(ComSafeArrayOutArg(aValues));
13046 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
13047 flags.detachTo(ComSafeArrayOutArg(aFlags));
13048 return S_OK;
13049#else
13050 ReturnComNotImplemented();
13051#endif
13052}
13053
13054STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
13055 IN_BSTR aValue,
13056 LONG64 aTimestamp,
13057 IN_BSTR aFlags)
13058{
13059 LogFlowThisFunc(("\n"));
13060
13061#ifdef VBOX_WITH_GUEST_PROPS
13062 using namespace guestProp;
13063
13064 CheckComArgStrNotEmptyOrNull(aName);
13065 CheckComArgNotNull(aValue);
13066 CheckComArgNotNull(aFlags);
13067
13068 try
13069 {
13070 /*
13071 * Convert input up front.
13072 */
13073 Utf8Str utf8Name(aName);
13074 uint32_t fFlags = NILFLAG;
13075 if (aFlags)
13076 {
13077 Utf8Str utf8Flags(aFlags);
13078 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
13079 AssertRCReturn(vrc, E_INVALIDARG);
13080 }
13081
13082 /*
13083 * Now grab the object lock, validate the state and do the update.
13084 */
13085 AutoCaller autoCaller(this);
13086 if (FAILED(autoCaller.rc())) return autoCaller.rc();
13087
13088 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13089
13090 switch (mData->mMachineState)
13091 {
13092 case MachineState_Paused:
13093 case MachineState_Running:
13094 case MachineState_Teleporting:
13095 case MachineState_TeleportingPausedVM:
13096 case MachineState_LiveSnapshotting:
13097 case MachineState_DeletingSnapshotOnline:
13098 case MachineState_DeletingSnapshotPaused:
13099 case MachineState_Saving:
13100 case MachineState_Stopping:
13101 break;
13102
13103 default:
13104 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
13105 VBOX_E_INVALID_VM_STATE);
13106 }
13107
13108 setModified(IsModified_MachineData);
13109 mHWData.backup();
13110
13111 HWData::GuestPropertyMap::iterator it = mHWData->mGuestProperties.find(utf8Name);
13112 if (it != mHWData->mGuestProperties.end())
13113 {
13114 if (RT_VALID_PTR(aValue) && *(aValue) != '\0')
13115 {
13116 it->second.strValue = aValue;
13117 it->second.mFlags = fFlags;
13118 it->second.mTimestamp = aTimestamp;
13119 }
13120 else
13121 mHWData->mGuestProperties.erase(it);
13122
13123 mData->mGuestPropertiesModified = TRUE;
13124 }
13125
13126 /*
13127 * Send a callback notification if appropriate
13128 */
13129 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
13130 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
13131 RTSTR_MAX,
13132 utf8Name.c_str(),
13133 RTSTR_MAX, NULL)
13134 )
13135 {
13136 alock.release();
13137
13138 mParent->onGuestPropertyChange(mData->mUuid,
13139 aName,
13140 aValue,
13141 aFlags);
13142 }
13143 }
13144 catch (...)
13145 {
13146 return VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
13147 }
13148 return S_OK;
13149#else
13150 ReturnComNotImplemented();
13151#endif
13152}
13153
13154STDMETHODIMP SessionMachine::LockMedia()
13155{
13156 AutoCaller autoCaller(this);
13157 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13158
13159 AutoMultiWriteLock2 alock(this->lockHandle(),
13160 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13161
13162 AssertReturn( mData->mMachineState == MachineState_Starting
13163 || mData->mMachineState == MachineState_Restoring
13164 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
13165
13166 clearError();
13167 alock.release();
13168 return lockMedia();
13169}
13170
13171STDMETHODIMP SessionMachine::UnlockMedia()
13172{
13173 unlockMedia();
13174 return S_OK;
13175}
13176
13177STDMETHODIMP SessionMachine::EjectMedium(IMediumAttachment *aAttachment,
13178 IMediumAttachment **aNewAttachment)
13179{
13180 CheckComArgNotNull(aAttachment);
13181 CheckComArgOutPointerValid(aNewAttachment);
13182
13183 AutoCaller autoCaller(this);
13184 if (FAILED(autoCaller.rc())) return autoCaller.rc();
13185
13186 // request the host lock first, since might be calling Host methods for getting host drives;
13187 // next, protect the media tree all the while we're in here, as well as our member variables
13188 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
13189 this->lockHandle(),
13190 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13191
13192 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(aAttachment);
13193
13194 Bstr ctrlName;
13195 LONG lPort;
13196 LONG lDevice;
13197 bool fTempEject;
13198 {
13199 AutoCaller autoAttachCaller(this);
13200 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
13201
13202 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13203
13204 /* Need to query the details first, as the IMediumAttachment reference
13205 * might be to the original settings, which we are going to change. */
13206 ctrlName = pAttach->getControllerName();
13207 lPort = pAttach->getPort();
13208 lDevice = pAttach->getDevice();
13209 fTempEject = pAttach->getTempEject();
13210 }
13211
13212 if (!fTempEject)
13213 {
13214 /* Remember previously mounted medium. The medium before taking the
13215 * backup is not necessarily the same thing. */
13216 ComObjPtr<Medium> oldmedium;
13217 oldmedium = pAttach->getMedium();
13218
13219 setModified(IsModified_Storage);
13220 mMediaData.backup();
13221
13222 // The backup operation makes the pAttach reference point to the
13223 // old settings. Re-get the correct reference.
13224 pAttach = findAttachment(mMediaData->mAttachments,
13225 ctrlName.raw(),
13226 lPort,
13227 lDevice);
13228
13229 {
13230 AutoCaller autoAttachCaller(this);
13231 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
13232
13233 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13234 if (!oldmedium.isNull())
13235 oldmedium->removeBackReference(mData->mUuid);
13236
13237 pAttach->updateMedium(NULL);
13238 pAttach->updateEjected();
13239 }
13240
13241 setModified(IsModified_Storage);
13242 }
13243 else
13244 {
13245 {
13246 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
13247 pAttach->updateEjected();
13248 }
13249 }
13250
13251 pAttach.queryInterfaceTo(aNewAttachment);
13252
13253 return S_OK;
13254}
13255
13256// public methods only for internal purposes
13257/////////////////////////////////////////////////////////////////////////////
13258
13259/**
13260 * Called from the client watcher thread to check for expected or unexpected
13261 * death of the client process that has a direct session to this machine.
13262 *
13263 * On Win32 and on OS/2, this method is called only when we've got the
13264 * mutex (i.e. the client has either died or terminated normally) so it always
13265 * returns @c true (the client is terminated, the session machine is
13266 * uninitialized).
13267 *
13268 * On other platforms, the method returns @c true if the client process has
13269 * terminated normally or abnormally and the session machine was uninitialized,
13270 * and @c false if the client process is still alive.
13271 *
13272 * @note Locks this object for writing.
13273 */
13274bool SessionMachine::checkForDeath()
13275{
13276 Uninit::Reason reason;
13277 bool terminated = false;
13278
13279 /* Enclose autoCaller with a block because calling uninit() from under it
13280 * will deadlock. */
13281 {
13282 AutoCaller autoCaller(this);
13283 if (!autoCaller.isOk())
13284 {
13285 /* return true if not ready, to cause the client watcher to exclude
13286 * the corresponding session from watching */
13287 LogFlowThisFunc(("Already uninitialized!\n"));
13288 return true;
13289 }
13290
13291 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13292
13293 /* Determine the reason of death: if the session state is Closing here,
13294 * everything is fine. Otherwise it means that the client did not call
13295 * OnSessionEnd() before it released the IPC semaphore. This may happen
13296 * either because the client process has abnormally terminated, or
13297 * because it simply forgot to call ISession::Close() before exiting. We
13298 * threat the latter also as an abnormal termination (see
13299 * Session::uninit() for details). */
13300 reason = mData->mSession.mState == SessionState_Unlocking ?
13301 Uninit::Normal :
13302 Uninit::Abnormal;
13303
13304#if defined(RT_OS_WINDOWS)
13305
13306 AssertMsg(mIPCSem, ("semaphore must be created"));
13307
13308 /* release the IPC mutex */
13309 ::ReleaseMutex(mIPCSem);
13310
13311 terminated = true;
13312
13313#elif defined(RT_OS_OS2)
13314
13315 AssertMsg(mIPCSem, ("semaphore must be created"));
13316
13317 /* release the IPC mutex */
13318 ::DosReleaseMutexSem(mIPCSem);
13319
13320 terminated = true;
13321
13322#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
13323
13324 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
13325
13326 int val = ::semctl(mIPCSem, 0, GETVAL);
13327 if (val > 0)
13328 {
13329 /* the semaphore is signaled, meaning the session is terminated */
13330 terminated = true;
13331 }
13332
13333#else
13334# error "Port me!"
13335#endif
13336
13337 } /* AutoCaller block */
13338
13339 if (terminated)
13340 uninit(reason);
13341
13342 return terminated;
13343}
13344
13345/**
13346 * @note Locks this object for reading.
13347 */
13348HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
13349{
13350 LogFlowThisFunc(("\n"));
13351
13352 AutoCaller autoCaller(this);
13353 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13354
13355 ComPtr<IInternalSessionControl> directControl;
13356 {
13357 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13358 directControl = mData->mSession.mDirectControl;
13359 }
13360
13361 /* ignore notifications sent after #OnSessionEnd() is called */
13362 if (!directControl)
13363 return S_OK;
13364
13365 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
13366}
13367
13368/**
13369 * @note Locks this object for reading.
13370 */
13371HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
13372 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
13373{
13374 LogFlowThisFunc(("\n"));
13375
13376 AutoCaller autoCaller(this);
13377 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13378
13379 ComPtr<IInternalSessionControl> directControl;
13380 {
13381 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13382 directControl = mData->mSession.mDirectControl;
13383 }
13384
13385 /* ignore notifications sent after #OnSessionEnd() is called */
13386 if (!directControl)
13387 return S_OK;
13388 /*
13389 * instead acting like callback we ask IVirtualBox deliver corresponding event
13390 */
13391
13392 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, (uint16_t)aHostPort, aGuestIp, (uint16_t)aGuestPort);
13393 return S_OK;
13394}
13395
13396/**
13397 * @note Locks this object for reading.
13398 */
13399HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
13400{
13401 LogFlowThisFunc(("\n"));
13402
13403 AutoCaller autoCaller(this);
13404 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13405
13406 ComPtr<IInternalSessionControl> directControl;
13407 {
13408 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13409 directControl = mData->mSession.mDirectControl;
13410 }
13411
13412 /* ignore notifications sent after #OnSessionEnd() is called */
13413 if (!directControl)
13414 return S_OK;
13415
13416 return directControl->OnSerialPortChange(serialPort);
13417}
13418
13419/**
13420 * @note Locks this object for reading.
13421 */
13422HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
13423{
13424 LogFlowThisFunc(("\n"));
13425
13426 AutoCaller autoCaller(this);
13427 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13428
13429 ComPtr<IInternalSessionControl> directControl;
13430 {
13431 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13432 directControl = mData->mSession.mDirectControl;
13433 }
13434
13435 /* ignore notifications sent after #OnSessionEnd() is called */
13436 if (!directControl)
13437 return S_OK;
13438
13439 return directControl->OnParallelPortChange(parallelPort);
13440}
13441
13442/**
13443 * @note Locks this object for reading.
13444 */
13445HRESULT SessionMachine::onStorageControllerChange()
13446{
13447 LogFlowThisFunc(("\n"));
13448
13449 AutoCaller autoCaller(this);
13450 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13451
13452 ComPtr<IInternalSessionControl> directControl;
13453 {
13454 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13455 directControl = mData->mSession.mDirectControl;
13456 }
13457
13458 /* ignore notifications sent after #OnSessionEnd() is called */
13459 if (!directControl)
13460 return S_OK;
13461
13462 return directControl->OnStorageControllerChange();
13463}
13464
13465/**
13466 * @note Locks this object for reading.
13467 */
13468HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
13469{
13470 LogFlowThisFunc(("\n"));
13471
13472 AutoCaller autoCaller(this);
13473 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13474
13475 ComPtr<IInternalSessionControl> directControl;
13476 {
13477 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13478 directControl = mData->mSession.mDirectControl;
13479 }
13480
13481 /* ignore notifications sent after #OnSessionEnd() is called */
13482 if (!directControl)
13483 return S_OK;
13484
13485 return directControl->OnMediumChange(aAttachment, aForce);
13486}
13487
13488/**
13489 * @note Locks this object for reading.
13490 */
13491HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
13492{
13493 LogFlowThisFunc(("\n"));
13494
13495 AutoCaller autoCaller(this);
13496 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13497
13498 ComPtr<IInternalSessionControl> directControl;
13499 {
13500 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13501 directControl = mData->mSession.mDirectControl;
13502 }
13503
13504 /* ignore notifications sent after #OnSessionEnd() is called */
13505 if (!directControl)
13506 return S_OK;
13507
13508 return directControl->OnCPUChange(aCPU, aRemove);
13509}
13510
13511HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
13512{
13513 LogFlowThisFunc(("\n"));
13514
13515 AutoCaller autoCaller(this);
13516 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13517
13518 ComPtr<IInternalSessionControl> directControl;
13519 {
13520 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13521 directControl = mData->mSession.mDirectControl;
13522 }
13523
13524 /* ignore notifications sent after #OnSessionEnd() is called */
13525 if (!directControl)
13526 return S_OK;
13527
13528 return directControl->OnCPUExecutionCapChange(aExecutionCap);
13529}
13530
13531/**
13532 * @note Locks this object for reading.
13533 */
13534HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
13535{
13536 LogFlowThisFunc(("\n"));
13537
13538 AutoCaller autoCaller(this);
13539 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13540
13541 ComPtr<IInternalSessionControl> directControl;
13542 {
13543 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13544 directControl = mData->mSession.mDirectControl;
13545 }
13546
13547 /* ignore notifications sent after #OnSessionEnd() is called */
13548 if (!directControl)
13549 return S_OK;
13550
13551 return directControl->OnVRDEServerChange(aRestart);
13552}
13553
13554/**
13555 * @note Locks this object for reading.
13556 */
13557HRESULT SessionMachine::onUSBControllerChange()
13558{
13559 LogFlowThisFunc(("\n"));
13560
13561 AutoCaller autoCaller(this);
13562 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13563
13564 ComPtr<IInternalSessionControl> directControl;
13565 {
13566 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13567 directControl = mData->mSession.mDirectControl;
13568 }
13569
13570 /* ignore notifications sent after #OnSessionEnd() is called */
13571 if (!directControl)
13572 return S_OK;
13573
13574 return directControl->OnUSBControllerChange();
13575}
13576
13577/**
13578 * @note Locks this object for reading.
13579 */
13580HRESULT SessionMachine::onSharedFolderChange()
13581{
13582 LogFlowThisFunc(("\n"));
13583
13584 AutoCaller autoCaller(this);
13585 AssertComRCReturnRC(autoCaller.rc());
13586
13587 ComPtr<IInternalSessionControl> directControl;
13588 {
13589 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13590 directControl = mData->mSession.mDirectControl;
13591 }
13592
13593 /* ignore notifications sent after #OnSessionEnd() is called */
13594 if (!directControl)
13595 return S_OK;
13596
13597 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
13598}
13599
13600/**
13601 * @note Locks this object for reading.
13602 */
13603HRESULT SessionMachine::onClipboardModeChange(ClipboardMode_T aClipboardMode)
13604{
13605 LogFlowThisFunc(("\n"));
13606
13607 AutoCaller autoCaller(this);
13608 AssertComRCReturnRC(autoCaller.rc());
13609
13610 ComPtr<IInternalSessionControl> directControl;
13611 {
13612 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13613 directControl = mData->mSession.mDirectControl;
13614 }
13615
13616 /* ignore notifications sent after #OnSessionEnd() is called */
13617 if (!directControl)
13618 return S_OK;
13619
13620 return directControl->OnClipboardModeChange(aClipboardMode);
13621}
13622
13623/**
13624 * @note Locks this object for reading.
13625 */
13626HRESULT SessionMachine::onDragAndDropModeChange(DragAndDropMode_T aDragAndDropMode)
13627{
13628 LogFlowThisFunc(("\n"));
13629
13630 AutoCaller autoCaller(this);
13631 AssertComRCReturnRC(autoCaller.rc());
13632
13633 ComPtr<IInternalSessionControl> directControl;
13634 {
13635 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13636 directControl = mData->mSession.mDirectControl;
13637 }
13638
13639 /* ignore notifications sent after #OnSessionEnd() is called */
13640 if (!directControl)
13641 return S_OK;
13642
13643 return directControl->OnDragAndDropModeChange(aDragAndDropMode);
13644}
13645
13646/**
13647 * @note Locks this object for reading.
13648 */
13649HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
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 directControl = mData->mSession.mDirectControl;
13660 }
13661
13662 /* ignore notifications sent after #OnSessionEnd() is called */
13663 if (!directControl)
13664 return S_OK;
13665
13666 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
13667}
13668
13669/**
13670 * @note Locks this object for reading.
13671 */
13672HRESULT SessionMachine::onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove, BOOL aSilent)
13673{
13674 LogFlowThisFunc(("\n"));
13675
13676 AutoCaller autoCaller(this);
13677 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13678
13679 ComPtr<IInternalSessionControl> directControl;
13680 {
13681 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13682 directControl = mData->mSession.mDirectControl;
13683 }
13684
13685 /* ignore notifications sent after #OnSessionEnd() is called */
13686 if (!directControl)
13687 return S_OK;
13688
13689 return directControl->OnStorageDeviceChange(aAttachment, aRemove, aSilent);
13690}
13691
13692/**
13693 * Returns @c true if this machine's USB controller reports it has a matching
13694 * filter for the given USB device and @c false otherwise.
13695 *
13696 * @note locks this object for reading.
13697 */
13698bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
13699{
13700 AutoCaller autoCaller(this);
13701 /* silently return if not ready -- this method may be called after the
13702 * direct machine session has been called */
13703 if (!autoCaller.isOk())
13704 return false;
13705
13706#ifdef VBOX_WITH_USB
13707 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13708
13709 switch (mData->mMachineState)
13710 {
13711 case MachineState_Starting:
13712 case MachineState_Restoring:
13713 case MachineState_TeleportingIn:
13714 case MachineState_Paused:
13715 case MachineState_Running:
13716 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
13717 * elsewhere... */
13718 alock.release();
13719 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
13720 default: break;
13721 }
13722#else
13723 NOREF(aDevice);
13724 NOREF(aMaskedIfs);
13725#endif
13726 return false;
13727}
13728
13729/**
13730 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
13731 */
13732HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
13733 IVirtualBoxErrorInfo *aError,
13734 ULONG aMaskedIfs)
13735{
13736 LogFlowThisFunc(("\n"));
13737
13738 AutoCaller autoCaller(this);
13739
13740 /* This notification may happen after the machine object has been
13741 * uninitialized (the session was closed), so don't assert. */
13742 if (FAILED(autoCaller.rc())) return autoCaller.rc();
13743
13744 ComPtr<IInternalSessionControl> directControl;
13745 {
13746 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13747 directControl = mData->mSession.mDirectControl;
13748 }
13749
13750 /* fail on notifications sent after #OnSessionEnd() is called, it is
13751 * expected by the caller */
13752 if (!directControl)
13753 return E_FAIL;
13754
13755 /* No locks should be held at this point. */
13756 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
13757 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
13758
13759 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
13760}
13761
13762/**
13763 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
13764 */
13765HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
13766 IVirtualBoxErrorInfo *aError)
13767{
13768 LogFlowThisFunc(("\n"));
13769
13770 AutoCaller autoCaller(this);
13771
13772 /* This notification may happen after the machine object has been
13773 * uninitialized (the session was closed), so don't assert. */
13774 if (FAILED(autoCaller.rc())) return autoCaller.rc();
13775
13776 ComPtr<IInternalSessionControl> directControl;
13777 {
13778 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13779 directControl = mData->mSession.mDirectControl;
13780 }
13781
13782 /* fail on notifications sent after #OnSessionEnd() is called, it is
13783 * expected by the caller */
13784 if (!directControl)
13785 return E_FAIL;
13786
13787 /* No locks should be held at this point. */
13788 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
13789 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
13790
13791 return directControl->OnUSBDeviceDetach(aId, aError);
13792}
13793
13794// protected methods
13795/////////////////////////////////////////////////////////////////////////////
13796
13797/**
13798 * Helper method to finalize saving the state.
13799 *
13800 * @note Must be called from under this object's lock.
13801 *
13802 * @param aRc S_OK if the snapshot has been taken successfully
13803 * @param aErrMsg human readable error message for failure
13804 *
13805 * @note Locks mParent + this objects for writing.
13806 */
13807HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
13808{
13809 LogFlowThisFuncEnter();
13810
13811 AutoCaller autoCaller(this);
13812 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13813
13814 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13815
13816 HRESULT rc = S_OK;
13817
13818 if (SUCCEEDED(aRc))
13819 {
13820 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
13821
13822 /* save all VM settings */
13823 rc = saveSettings(NULL);
13824 // no need to check whether VirtualBox.xml needs saving also since
13825 // we can't have a name change pending at this point
13826 }
13827 else
13828 {
13829 // delete the saved state file (it might have been already created);
13830 // we need not check whether this is shared with a snapshot here because
13831 // we certainly created this saved state file here anew
13832 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
13833 }
13834
13835 /* notify the progress object about operation completion */
13836 Assert(mConsoleTaskData.mProgress);
13837 if (SUCCEEDED(aRc))
13838 mConsoleTaskData.mProgress->notifyComplete(S_OK);
13839 else
13840 {
13841 if (aErrMsg.length())
13842 mConsoleTaskData.mProgress->notifyComplete(aRc,
13843 COM_IIDOF(ISession),
13844 getComponentName(),
13845 aErrMsg.c_str());
13846 else
13847 mConsoleTaskData.mProgress->notifyComplete(aRc);
13848 }
13849
13850 /* clear out the temporary saved state data */
13851 mConsoleTaskData.mLastState = MachineState_Null;
13852 mConsoleTaskData.strStateFilePath.setNull();
13853 mConsoleTaskData.mProgress.setNull();
13854
13855 LogFlowThisFuncLeave();
13856 return rc;
13857}
13858
13859/**
13860 * Deletes the given file if it is no longer in use by either the current machine state
13861 * (if the machine is "saved") or any of the machine's snapshots.
13862 *
13863 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
13864 * but is different for each SnapshotMachine. When calling this, the order of calling this
13865 * function on the one hand and changing that variable OR the snapshots tree on the other hand
13866 * is therefore critical. I know, it's all rather messy.
13867 *
13868 * @param strStateFile
13869 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
13870 */
13871void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
13872 Snapshot *pSnapshotToIgnore)
13873{
13874 // it is safe to delete this saved state file if it is not currently in use by the machine ...
13875 if ( (strStateFile.isNotEmpty())
13876 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
13877 )
13878 // ... and it must also not be shared with other snapshots
13879 if ( !mData->mFirstSnapshot
13880 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
13881 // this checks the SnapshotMachine's state file paths
13882 )
13883 RTFileDelete(strStateFile.c_str());
13884}
13885
13886/**
13887 * Locks the attached media.
13888 *
13889 * All attached hard disks are locked for writing and DVD/floppy are locked for
13890 * reading. Parents of attached hard disks (if any) are locked for reading.
13891 *
13892 * This method also performs accessibility check of all media it locks: if some
13893 * media is inaccessible, the method will return a failure and a bunch of
13894 * extended error info objects per each inaccessible medium.
13895 *
13896 * Note that this method is atomic: if it returns a success, all media are
13897 * locked as described above; on failure no media is locked at all (all
13898 * succeeded individual locks will be undone).
13899 *
13900 * The caller is responsible for doing the necessary state sanity checks.
13901 *
13902 * The locks made by this method must be undone by calling #unlockMedia() when
13903 * no more needed.
13904 */
13905HRESULT SessionMachine::lockMedia()
13906{
13907 AutoCaller autoCaller(this);
13908 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13909
13910 AutoMultiWriteLock2 alock(this->lockHandle(),
13911 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
13912
13913 /* bail out if trying to lock things with already set up locking */
13914 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
13915
13916 MultiResult mrc(S_OK);
13917
13918 /* Collect locking information for all medium objects attached to the VM. */
13919 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
13920 it != mMediaData->mAttachments.end();
13921 ++it)
13922 {
13923 MediumAttachment* pAtt = *it;
13924 DeviceType_T devType = pAtt->getType();
13925 Medium *pMedium = pAtt->getMedium();
13926
13927 MediumLockList *pMediumLockList(new MediumLockList());
13928 // There can be attachments without a medium (floppy/dvd), and thus
13929 // it's impossible to create a medium lock list. It still makes sense
13930 // to have the empty medium lock list in the map in case a medium is
13931 // attached later.
13932 if (pMedium != NULL)
13933 {
13934 MediumType_T mediumType = pMedium->getType();
13935 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
13936 || mediumType == MediumType_Shareable;
13937 bool fIsVitalImage = (devType == DeviceType_HardDisk);
13938
13939 alock.release();
13940 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
13941 !fIsReadOnlyLock /* fMediumLockWrite */,
13942 NULL,
13943 *pMediumLockList);
13944 alock.acquire();
13945 if (FAILED(mrc))
13946 {
13947 delete pMediumLockList;
13948 mData->mSession.mLockedMedia.Clear();
13949 break;
13950 }
13951 }
13952
13953 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
13954 if (FAILED(rc))
13955 {
13956 mData->mSession.mLockedMedia.Clear();
13957 mrc = setError(rc,
13958 tr("Collecting locking information for all attached media failed"));
13959 break;
13960 }
13961 }
13962
13963 if (SUCCEEDED(mrc))
13964 {
13965 /* Now lock all media. If this fails, nothing is locked. */
13966 alock.release();
13967 HRESULT rc = mData->mSession.mLockedMedia.Lock();
13968 alock.acquire();
13969 if (FAILED(rc))
13970 {
13971 mrc = setError(rc,
13972 tr("Locking of attached media failed"));
13973 }
13974 }
13975
13976 return mrc;
13977}
13978
13979/**
13980 * Undoes the locks made by by #lockMedia().
13981 */
13982void SessionMachine::unlockMedia()
13983{
13984 AutoCaller autoCaller(this);
13985 AssertComRCReturnVoid(autoCaller.rc());
13986
13987 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
13988
13989 /* we may be holding important error info on the current thread;
13990 * preserve it */
13991 ErrorInfoKeeper eik;
13992
13993 HRESULT rc = mData->mSession.mLockedMedia.Clear();
13994 AssertComRC(rc);
13995}
13996
13997/**
13998 * Helper to change the machine state (reimplementation).
13999 *
14000 * @note Locks this object for writing.
14001 * @note This method must not call saveSettings or SaveSettings, otherwise
14002 * it can cause crashes in random places due to unexpectedly committing
14003 * the current settings. The caller is responsible for that. The call
14004 * to saveStateSettings is fine, because this method does not commit.
14005 */
14006HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
14007{
14008 LogFlowThisFuncEnter();
14009 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
14010
14011 AutoCaller autoCaller(this);
14012 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14013
14014 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
14015
14016 MachineState_T oldMachineState = mData->mMachineState;
14017
14018 AssertMsgReturn(oldMachineState != aMachineState,
14019 ("oldMachineState=%s, aMachineState=%s\n",
14020 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
14021 E_FAIL);
14022
14023 HRESULT rc = S_OK;
14024
14025 int stsFlags = 0;
14026 bool deleteSavedState = false;
14027
14028 /* detect some state transitions */
14029
14030 if ( ( oldMachineState == MachineState_Saved
14031 && aMachineState == MachineState_Restoring)
14032 || ( ( oldMachineState == MachineState_PoweredOff
14033 || oldMachineState == MachineState_Teleported
14034 || oldMachineState == MachineState_Aborted
14035 )
14036 && ( aMachineState == MachineState_TeleportingIn
14037 || aMachineState == MachineState_Starting
14038 )
14039 )
14040 )
14041 {
14042 /* The EMT thread is about to start */
14043
14044 /* Nothing to do here for now... */
14045
14046 /// @todo NEWMEDIA don't let mDVDDrive and other children
14047 /// change anything when in the Starting/Restoring state
14048 }
14049 else if ( ( oldMachineState == MachineState_Running
14050 || oldMachineState == MachineState_Paused
14051 || oldMachineState == MachineState_Teleporting
14052 || oldMachineState == MachineState_LiveSnapshotting
14053 || oldMachineState == MachineState_Stuck
14054 || oldMachineState == MachineState_Starting
14055 || oldMachineState == MachineState_Stopping
14056 || oldMachineState == MachineState_Saving
14057 || oldMachineState == MachineState_Restoring
14058 || oldMachineState == MachineState_TeleportingPausedVM
14059 || oldMachineState == MachineState_TeleportingIn
14060 )
14061 && ( aMachineState == MachineState_PoweredOff
14062 || aMachineState == MachineState_Saved
14063 || aMachineState == MachineState_Teleported
14064 || aMachineState == MachineState_Aborted
14065 )
14066 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
14067 * snapshot */
14068 && ( mConsoleTaskData.mSnapshot.isNull()
14069 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
14070 )
14071 )
14072 {
14073 /* The EMT thread has just stopped, unlock attached media. Note that as
14074 * opposed to locking that is done from Console, we do unlocking here
14075 * because the VM process may have aborted before having a chance to
14076 * properly unlock all media it locked. */
14077
14078 unlockMedia();
14079 }
14080
14081 if (oldMachineState == MachineState_Restoring)
14082 {
14083 if (aMachineState != MachineState_Saved)
14084 {
14085 /*
14086 * delete the saved state file once the machine has finished
14087 * restoring from it (note that Console sets the state from
14088 * Restoring to Saved if the VM couldn't restore successfully,
14089 * to give the user an ability to fix an error and retry --
14090 * we keep the saved state file in this case)
14091 */
14092 deleteSavedState = true;
14093 }
14094 }
14095 else if ( oldMachineState == MachineState_Saved
14096 && ( aMachineState == MachineState_PoweredOff
14097 || aMachineState == MachineState_Aborted
14098 || aMachineState == MachineState_Teleported
14099 )
14100 )
14101 {
14102 /*
14103 * delete the saved state after Console::ForgetSavedState() is called
14104 * or if the VM process (owning a direct VM session) crashed while the
14105 * VM was Saved
14106 */
14107
14108 /// @todo (dmik)
14109 // Not sure that deleting the saved state file just because of the
14110 // client death before it attempted to restore the VM is a good
14111 // thing. But when it crashes we need to go to the Aborted state
14112 // which cannot have the saved state file associated... The only
14113 // way to fix this is to make the Aborted condition not a VM state
14114 // but a bool flag: i.e., when a crash occurs, set it to true and
14115 // change the state to PoweredOff or Saved depending on the
14116 // saved state presence.
14117
14118 deleteSavedState = true;
14119 mData->mCurrentStateModified = TRUE;
14120 stsFlags |= SaveSTS_CurStateModified;
14121 }
14122
14123 if ( aMachineState == MachineState_Starting
14124 || aMachineState == MachineState_Restoring
14125 || aMachineState == MachineState_TeleportingIn
14126 )
14127 {
14128 /* set the current state modified flag to indicate that the current
14129 * state is no more identical to the state in the
14130 * current snapshot */
14131 if (!mData->mCurrentSnapshot.isNull())
14132 {
14133 mData->mCurrentStateModified = TRUE;
14134 stsFlags |= SaveSTS_CurStateModified;
14135 }
14136 }
14137
14138 if (deleteSavedState)
14139 {
14140 if (mRemoveSavedState)
14141 {
14142 Assert(!mSSData->strStateFilePath.isEmpty());
14143
14144 // it is safe to delete the saved state file if ...
14145 if ( !mData->mFirstSnapshot // ... we have no snapshots or
14146 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
14147 // ... none of the snapshots share the saved state file
14148 )
14149 RTFileDelete(mSSData->strStateFilePath.c_str());
14150 }
14151
14152 mSSData->strStateFilePath.setNull();
14153 stsFlags |= SaveSTS_StateFilePath;
14154 }
14155
14156 /* redirect to the underlying peer machine */
14157 mPeer->setMachineState(aMachineState);
14158
14159 if ( aMachineState == MachineState_PoweredOff
14160 || aMachineState == MachineState_Teleported
14161 || aMachineState == MachineState_Aborted
14162 || aMachineState == MachineState_Saved)
14163 {
14164 /* the machine has stopped execution
14165 * (or the saved state file was adopted) */
14166 stsFlags |= SaveSTS_StateTimeStamp;
14167 }
14168
14169 if ( ( oldMachineState == MachineState_PoweredOff
14170 || oldMachineState == MachineState_Aborted
14171 || oldMachineState == MachineState_Teleported
14172 )
14173 && aMachineState == MachineState_Saved)
14174 {
14175 /* the saved state file was adopted */
14176 Assert(!mSSData->strStateFilePath.isEmpty());
14177 stsFlags |= SaveSTS_StateFilePath;
14178 }
14179
14180#ifdef VBOX_WITH_GUEST_PROPS
14181 if ( aMachineState == MachineState_PoweredOff
14182 || aMachineState == MachineState_Aborted
14183 || aMachineState == MachineState_Teleported)
14184 {
14185 /* Make sure any transient guest properties get removed from the
14186 * property store on shutdown. */
14187
14188 HWData::GuestPropertyMap::const_iterator it;
14189 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
14190 if (!fNeedsSaving)
14191 for (it = mHWData->mGuestProperties.begin();
14192 it != mHWData->mGuestProperties.end(); ++it)
14193 if ( (it->second.mFlags & guestProp::TRANSIENT)
14194 || (it->second.mFlags & guestProp::TRANSRESET))
14195 {
14196 fNeedsSaving = true;
14197 break;
14198 }
14199 if (fNeedsSaving)
14200 {
14201 mData->mCurrentStateModified = TRUE;
14202 stsFlags |= SaveSTS_CurStateModified;
14203 }
14204 }
14205#endif
14206
14207 rc = saveStateSettings(stsFlags);
14208
14209 if ( ( oldMachineState != MachineState_PoweredOff
14210 && oldMachineState != MachineState_Aborted
14211 && oldMachineState != MachineState_Teleported
14212 )
14213 && ( aMachineState == MachineState_PoweredOff
14214 || aMachineState == MachineState_Aborted
14215 || aMachineState == MachineState_Teleported
14216 )
14217 )
14218 {
14219 /* we've been shut down for any reason */
14220 /* no special action so far */
14221 }
14222
14223 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
14224 LogFlowThisFuncLeave();
14225 return rc;
14226}
14227
14228/**
14229 * Sends the current machine state value to the VM process.
14230 *
14231 * @note Locks this object for reading, then calls a client process.
14232 */
14233HRESULT SessionMachine::updateMachineStateOnClient()
14234{
14235 AutoCaller autoCaller(this);
14236 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
14237
14238 ComPtr<IInternalSessionControl> directControl;
14239 {
14240 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
14241 AssertReturn(!!mData, E_FAIL);
14242 directControl = mData->mSession.mDirectControl;
14243
14244 /* directControl may be already set to NULL here in #OnSessionEnd()
14245 * called too early by the direct session process while there is still
14246 * some operation (like deleting the snapshot) in progress. The client
14247 * process in this case is waiting inside Session::close() for the
14248 * "end session" process object to complete, while #uninit() called by
14249 * #checkForDeath() on the Watcher thread is waiting for the pending
14250 * operation to complete. For now, we accept this inconsistent behavior
14251 * and simply do nothing here. */
14252
14253 if (mData->mSession.mState == SessionState_Unlocking)
14254 return S_OK;
14255
14256 AssertReturn(!directControl.isNull(), E_FAIL);
14257 }
14258
14259 return directControl->UpdateMachineState(mData->mMachineState);
14260}
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