VirtualBox

source: vbox/trunk/src/VBox/Main/MachineImpl.cpp@ 35357

Last change on this file since 35357 was 35357, checked in by vboxsync, 14 years ago

VMM, Main: PCI passthrough work

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 395.5 KB
Line 
1/* $Id: MachineImpl.cpp 35357 2010-12-27 22:38:34Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2010 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 "VBoxEvents.h"
53
54#ifdef VBOX_WITH_USB
55# include "USBProxyService.h"
56#endif
57
58#include "AutoCaller.h"
59#include "Performance.h"
60
61#include <iprt/asm.h>
62#include <iprt/path.h>
63#include <iprt/dir.h>
64#include <iprt/env.h>
65#include <iprt/lockvalidator.h>
66#include <iprt/process.h>
67#include <iprt/cpp/utils.h>
68#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
69#include <iprt/string.h>
70
71#include <VBox/com/array.h>
72
73#include <VBox/err.h>
74#include <VBox/param.h>
75#include <VBox/settings.h>
76#include <VBox/vmm/ssm.h>
77
78#ifdef VBOX_WITH_GUEST_PROPS
79# include <VBox/HostServices/GuestPropertySvc.h>
80# include <VBox/com/array.h>
81#endif
82
83#include "VBox/com/MultiResult.h"
84
85#include <algorithm>
86
87#include <typeinfo>
88
89#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
90# define HOSTSUFF_EXE ".exe"
91#else /* !RT_OS_WINDOWS */
92# define HOSTSUFF_EXE ""
93#endif /* !RT_OS_WINDOWS */
94
95// defines / prototypes
96/////////////////////////////////////////////////////////////////////////////
97
98/////////////////////////////////////////////////////////////////////////////
99// Machine::Data structure
100/////////////////////////////////////////////////////////////////////////////
101
102Machine::Data::Data()
103{
104 mRegistered = FALSE;
105 pMachineConfigFile = NULL;
106 flModifications = 0;
107 mAccessible = FALSE;
108 /* mUuid is initialized in Machine::init() */
109
110 mMachineState = MachineState_PoweredOff;
111 RTTimeNow(&mLastStateChange);
112
113 mMachineStateDeps = 0;
114 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
115 mMachineStateChangePending = 0;
116
117 mCurrentStateModified = TRUE;
118 mGuestPropertiesModified = FALSE;
119
120 mSession.mPid = NIL_RTPROCESS;
121 mSession.mState = SessionState_Unlocked;
122}
123
124Machine::Data::~Data()
125{
126 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
127 {
128 RTSemEventMultiDestroy(mMachineStateDepsSem);
129 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
130 }
131 if (pMachineConfigFile)
132 {
133 delete pMachineConfigFile;
134 pMachineConfigFile = NULL;
135 }
136}
137
138/////////////////////////////////////////////////////////////////////////////
139// Machine::HWData structure
140/////////////////////////////////////////////////////////////////////////////
141
142Machine::HWData::HWData()
143{
144 /* default values for a newly created machine */
145 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
146 mMemorySize = 128;
147 mCPUCount = 1;
148 mCPUHotPlugEnabled = false;
149 mMemoryBalloonSize = 0;
150 mPageFusionEnabled = false;
151 mVRAMSize = 8;
152 mAccelerate3DEnabled = false;
153 mAccelerate2DVideoEnabled = false;
154 mMonitorCount = 1;
155 mHWVirtExEnabled = true;
156 mHWVirtExNestedPagingEnabled = true;
157#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
158 mHWVirtExLargePagesEnabled = true;
159#else
160 /* Not supported on 32 bits hosts. */
161 mHWVirtExLargePagesEnabled = false;
162#endif
163 mHWVirtExVPIDEnabled = true;
164 mHWVirtExForceEnabled = false;
165#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
166 mHWVirtExExclusive = false;
167#else
168 mHWVirtExExclusive = true;
169#endif
170#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
171 mPAEEnabled = true;
172#else
173 mPAEEnabled = false;
174#endif
175 mSyntheticCpu = false;
176 mHpetEnabled = false;
177
178 /* default boot order: floppy - DVD - HDD */
179 mBootOrder[0] = DeviceType_Floppy;
180 mBootOrder[1] = DeviceType_DVD;
181 mBootOrder[2] = DeviceType_HardDisk;
182 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
183 mBootOrder[i] = DeviceType_Null;
184
185 mClipboardMode = ClipboardMode_Bidirectional;
186 mGuestPropertyNotificationPatterns = "";
187
188 mFirmwareType = FirmwareType_BIOS;
189 mKeyboardHidType = KeyboardHidType_PS2Keyboard;
190 mPointingHidType = PointingHidType_PS2Mouse;
191 mChipsetType = ChipsetType_PIIX3;
192
193 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); i++)
194 mCPUAttached[i] = false;
195
196 mIoCacheEnabled = true;
197 mIoCacheSize = 5; /* 5MB */
198
199 /* Maximum CPU execution cap by default. */
200 mCpuExecutionCap = 100;
201}
202
203Machine::HWData::~HWData()
204{
205}
206
207/////////////////////////////////////////////////////////////////////////////
208// Machine::HDData structure
209/////////////////////////////////////////////////////////////////////////////
210
211Machine::MediaData::MediaData()
212{
213}
214
215Machine::MediaData::~MediaData()
216{
217}
218
219/////////////////////////////////////////////////////////////////////////////
220// Machine class
221/////////////////////////////////////////////////////////////////////////////
222
223// constructor / destructor
224/////////////////////////////////////////////////////////////////////////////
225
226Machine::Machine()
227 : mGuestHAL(NULL),
228 mPeer(NULL),
229 mParent(NULL)
230{}
231
232Machine::~Machine()
233{}
234
235HRESULT Machine::FinalConstruct()
236{
237 LogFlowThisFunc(("\n"));
238 return S_OK;
239}
240
241void Machine::FinalRelease()
242{
243 LogFlowThisFunc(("\n"));
244 uninit();
245}
246
247/**
248 * Initializes a new machine instance; this init() variant creates a new, empty machine.
249 * This gets called from VirtualBox::CreateMachine().
250 *
251 * @param aParent Associated parent object
252 * @param strConfigFile Local file system path to the VM settings file (can
253 * be relative to the VirtualBox config directory).
254 * @param strName name for the machine
255 * @param aId UUID for the new machine.
256 * @param aOsType OS Type of this machine or NULL.
257 * @param fForceOverwrite Whether to overwrite an existing machine settings file.
258 *
259 * @return Success indicator. if not S_OK, the machine object is invalid
260 */
261HRESULT Machine::init(VirtualBox *aParent,
262 const Utf8Str &strConfigFile,
263 const Utf8Str &strName,
264 GuestOSType *aOsType,
265 const Guid &aId,
266 bool fForceOverwrite)
267{
268 LogFlowThisFuncEnter();
269 LogFlowThisFunc(("(Init_New) aConfigFile='%s'\n", strConfigFile.c_str()));
270
271 /* Enclose the state transition NotReady->InInit->Ready */
272 AutoInitSpan autoInitSpan(this);
273 AssertReturn(autoInitSpan.isOk(), E_FAIL);
274
275 HRESULT rc = initImpl(aParent, strConfigFile);
276 if (FAILED(rc)) return rc;
277
278 rc = tryCreateMachineConfigFile(fForceOverwrite);
279 if (FAILED(rc)) return rc;
280
281 if (SUCCEEDED(rc))
282 {
283 // create an empty machine config
284 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
285
286 rc = initDataAndChildObjects();
287 }
288
289 if (SUCCEEDED(rc))
290 {
291 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
292 mData->mAccessible = TRUE;
293
294 unconst(mData->mUuid) = aId;
295
296 mUserData->s.strName = strName;
297
298 // the "name sync" flag determines whether the machine directory gets renamed along
299 // with the machine file; say so if the settings file name is the same as the
300 // settings file parent directory (machine directory)
301 mUserData->s.fNameSync = isInOwnDir();
302
303 // initialize the default snapshots folder
304 rc = COMSETTER(SnapshotFolder)(NULL);
305 AssertComRC(rc);
306
307 if (aOsType)
308 {
309 /* Store OS type */
310 mUserData->s.strOsType = aOsType->id();
311
312 /* Apply BIOS defaults */
313 mBIOSSettings->applyDefaults(aOsType);
314
315 /* Apply network adapters defaults */
316 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); ++slot)
317 mNetworkAdapters[slot]->applyDefaults(aOsType);
318
319 /* Apply serial port defaults */
320 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); ++slot)
321 mSerialPorts[slot]->applyDefaults(aOsType);
322 }
323
324 /* commit all changes made during the initialization */
325 commit();
326 }
327
328 /* Confirm a successful initialization when it's the case */
329 if (SUCCEEDED(rc))
330 {
331 if (mData->mAccessible)
332 autoInitSpan.setSucceeded();
333 else
334 autoInitSpan.setLimited();
335 }
336
337 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool, rc=%08X\n",
338 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
339 mData->mRegistered,
340 mData->mAccessible,
341 rc));
342
343 LogFlowThisFuncLeave();
344
345 return rc;
346}
347
348/**
349 * Initializes a new instance with data from machine XML (formerly Init_Registered).
350 * Gets called in two modes:
351 *
352 * -- from VirtualBox::initMachines() during VirtualBox startup; in that case, the
353 * UUID is specified and we mark the machine as "registered";
354 *
355 * -- from the public VirtualBox::OpenMachine() API, in which case the UUID is NULL
356 * and the machine remains unregistered until RegisterMachine() is called.
357 *
358 * @param aParent Associated parent object
359 * @param aConfigFile Local file system path to the VM settings file (can
360 * be relative to the VirtualBox config directory).
361 * @param aId UUID of the machine or NULL (see above).
362 *
363 * @return Success indicator. if not S_OK, the machine object is invalid
364 */
365HRESULT Machine::init(VirtualBox *aParent,
366 const Utf8Str &strConfigFile,
367 const Guid *aId)
368{
369 LogFlowThisFuncEnter();
370 LogFlowThisFunc(("(Init_Registered) aConfigFile='%s\n", strConfigFile.c_str()));
371
372 /* Enclose the state transition NotReady->InInit->Ready */
373 AutoInitSpan autoInitSpan(this);
374 AssertReturn(autoInitSpan.isOk(), E_FAIL);
375
376 HRESULT rc = initImpl(aParent, strConfigFile);
377 if (FAILED(rc)) return rc;
378
379 if (aId)
380 {
381 // loading a registered VM:
382 unconst(mData->mUuid) = *aId;
383 mData->mRegistered = TRUE;
384 // now load the settings from XML:
385 rc = registeredInit();
386 // this calls initDataAndChildObjects() and loadSettings()
387 }
388 else
389 {
390 // opening an unregistered VM (VirtualBox::OpenMachine()):
391 rc = initDataAndChildObjects();
392
393 if (SUCCEEDED(rc))
394 {
395 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
396 mData->mAccessible = TRUE;
397
398 try
399 {
400 // load and parse machine XML; this will throw on XML or logic errors
401 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
402
403 // reject VM UUID duplicates, they can happen if someone
404 // tries to register an already known VM config again
405 if (aParent->findMachine(mData->pMachineConfigFile->uuid,
406 true /* fPermitInaccessible */,
407 false /* aDoSetError */,
408 NULL) != VBOX_E_OBJECT_NOT_FOUND)
409 {
410 throw setError(E_FAIL,
411 tr("Trying to open a VM config '%s' which has the same UUID as an existing virtual machine"),
412 mData->m_strConfigFile.c_str());
413 }
414
415 // use UUID from machine config
416 unconst(mData->mUuid) = mData->pMachineConfigFile->uuid;
417
418 rc = loadMachineDataFromSettings(*mData->pMachineConfigFile,
419 NULL /* puuidRegistry */);
420 if (FAILED(rc)) throw rc;
421
422 commit();
423 }
424 catch (HRESULT err)
425 {
426 /* we assume that error info is set by the thrower */
427 rc = err;
428 }
429 catch (...)
430 {
431 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
432 }
433 }
434 }
435
436 /* Confirm a successful initialization when it's the case */
437 if (SUCCEEDED(rc))
438 {
439 if (mData->mAccessible)
440 autoInitSpan.setSucceeded();
441 else
442 {
443 autoInitSpan.setLimited();
444
445 // uninit media from this machine's media registry, or else
446 // reloading the settings will fail
447 mParent->unregisterMachineMedia(getId());
448 }
449 }
450
451 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
452 "rc=%08X\n",
453 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
454 mData->mRegistered, mData->mAccessible, rc));
455
456 LogFlowThisFuncLeave();
457
458 return rc;
459}
460
461/**
462 * Initializes a new instance from a machine config that is already in memory
463 * (import OVF case). Since we are importing, the UUID in the machine
464 * config is ignored and we always generate a fresh one.
465 *
466 * @param strName Name for the new machine; this overrides what is specified in config and is used
467 * for the settings file as well.
468 * @param config Machine configuration loaded and parsed from XML.
469 *
470 * @return Success indicator. if not S_OK, the machine object is invalid
471 */
472HRESULT Machine::init(VirtualBox *aParent,
473 const Utf8Str &strName,
474 const settings::MachineConfigFile &config)
475{
476 LogFlowThisFuncEnter();
477
478 /* Enclose the state transition NotReady->InInit->Ready */
479 AutoInitSpan autoInitSpan(this);
480 AssertReturn(autoInitSpan.isOk(), E_FAIL);
481
482 Utf8Str strConfigFile;
483 aParent->getDefaultMachineFolder(strConfigFile);
484 strConfigFile.append(RTPATH_DELIMITER);
485 strConfigFile.append(strName);
486 strConfigFile.append(RTPATH_DELIMITER);
487 strConfigFile.append(strName);
488 strConfigFile.append(".vbox");
489
490 HRESULT rc = initImpl(aParent, strConfigFile);
491 if (FAILED(rc)) return rc;
492
493 rc = tryCreateMachineConfigFile(false /* fForceOverwrite */);
494 if (FAILED(rc)) return rc;
495
496 rc = initDataAndChildObjects();
497
498 if (SUCCEEDED(rc))
499 {
500 // set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
501 mData->mAccessible = TRUE;
502
503 // create empty machine config for instance data
504 mData->pMachineConfigFile = new settings::MachineConfigFile(NULL);
505
506 // generate fresh UUID, ignore machine config
507 unconst(mData->mUuid).create();
508
509 rc = loadMachineDataFromSettings(config,
510 &mData->mUuid); // puuidRegistry: initialize media with this registry ID
511
512 // override VM name as well, it may be different
513 mUserData->s.strName = strName;
514
515 /* commit all changes made during the initialization */
516 if (SUCCEEDED(rc))
517 commit();
518 }
519
520 /* Confirm a successful initialization when it's the case */
521 if (SUCCEEDED(rc))
522 {
523 if (mData->mAccessible)
524 autoInitSpan.setSucceeded();
525 else
526 {
527 autoInitSpan.setLimited();
528
529 // uninit media from this machine's media registry, or else
530 // reloading the settings will fail
531 mParent->unregisterMachineMedia(getId());
532 }
533 }
534
535 LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
536 "rc=%08X\n",
537 !!mUserData ? mUserData->s.strName.c_str() : "NULL",
538 mData->mRegistered, mData->mAccessible, rc));
539
540 LogFlowThisFuncLeave();
541
542 return rc;
543}
544
545/**
546 * Shared code between the various init() implementations.
547 * @param aParent
548 * @return
549 */
550HRESULT Machine::initImpl(VirtualBox *aParent,
551 const Utf8Str &strConfigFile)
552{
553 LogFlowThisFuncEnter();
554
555 AssertReturn(aParent, E_INVALIDARG);
556 AssertReturn(!strConfigFile.isEmpty(), E_INVALIDARG);
557
558 HRESULT rc = S_OK;
559
560 /* share the parent weakly */
561 unconst(mParent) = aParent;
562
563 /* allocate the essential machine data structure (the rest will be
564 * allocated later by initDataAndChildObjects() */
565 mData.allocate();
566
567 /* memorize the config file name (as provided) */
568 mData->m_strConfigFile = strConfigFile;
569
570 /* get the full file name */
571 int vrc1 = mParent->calculateFullPath(strConfigFile, mData->m_strConfigFileFull);
572 if (RT_FAILURE(vrc1))
573 return setError(VBOX_E_FILE_ERROR,
574 tr("Invalid machine settings file name '%s' (%Rrc)"),
575 strConfigFile.c_str(),
576 vrc1);
577
578 LogFlowThisFuncLeave();
579
580 return rc;
581}
582
583/**
584 * Tries to create a machine settings file in the path stored in the machine
585 * instance data. Used when a new machine is created to fail gracefully if
586 * the settings file could not be written (e.g. because machine dir is read-only).
587 * @return
588 */
589HRESULT Machine::tryCreateMachineConfigFile(bool fForceOverwrite)
590{
591 HRESULT rc = S_OK;
592
593 // when we create a new machine, we must be able to create the settings file
594 RTFILE f = NIL_RTFILE;
595 int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
596 if ( RT_SUCCESS(vrc)
597 || vrc == VERR_SHARING_VIOLATION
598 )
599 {
600 if (RT_SUCCESS(vrc))
601 RTFileClose(f);
602 if (!fForceOverwrite)
603 rc = setError(VBOX_E_FILE_ERROR,
604 tr("Machine settings file '%s' already exists"),
605 mData->m_strConfigFileFull.c_str());
606 else
607 {
608 /* try to delete the config file, as otherwise the creation
609 * of a new settings file will fail. */
610 int vrc2 = RTFileDelete(mData->m_strConfigFileFull.c_str());
611 if (RT_FAILURE(vrc2))
612 rc = setError(VBOX_E_FILE_ERROR,
613 tr("Could not delete the existing settings file '%s' (%Rrc)"),
614 mData->m_strConfigFileFull.c_str(), vrc2);
615 }
616 }
617 else if ( vrc != VERR_FILE_NOT_FOUND
618 && vrc != VERR_PATH_NOT_FOUND
619 )
620 rc = setError(VBOX_E_FILE_ERROR,
621 tr("Invalid machine settings file name '%s' (%Rrc)"),
622 mData->m_strConfigFileFull.c_str(),
623 vrc);
624 return rc;
625}
626
627/**
628 * Initializes the registered machine by loading the settings file.
629 * This method is separated from #init() in order to make it possible to
630 * retry the operation after VirtualBox startup instead of refusing to
631 * startup the whole VirtualBox server in case if the settings file of some
632 * registered VM is invalid or inaccessible.
633 *
634 * @note Must be always called from this object's write lock
635 * (unless called from #init() that doesn't need any locking).
636 * @note Locks the mUSBController method for writing.
637 * @note Subclasses must not call this method.
638 */
639HRESULT Machine::registeredInit()
640{
641 AssertReturn(!isSessionMachine(), E_FAIL);
642 AssertReturn(!isSnapshotMachine(), E_FAIL);
643 AssertReturn(!mData->mUuid.isEmpty(), E_FAIL);
644 AssertReturn(!mData->mAccessible, E_FAIL);
645
646 HRESULT rc = initDataAndChildObjects();
647
648 if (SUCCEEDED(rc))
649 {
650 /* Temporarily reset the registered flag in order to let setters
651 * potentially called from loadSettings() succeed (isMutable() used in
652 * all setters will return FALSE for a Machine instance if mRegistered
653 * is TRUE). */
654 mData->mRegistered = FALSE;
655
656 try
657 {
658 // load and parse machine XML; this will throw on XML or logic errors
659 mData->pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
660
661 if (mData->mUuid != mData->pMachineConfigFile->uuid)
662 throw setError(E_FAIL,
663 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
664 mData->pMachineConfigFile->uuid.raw(),
665 mData->m_strConfigFileFull.c_str(),
666 mData->mUuid.toString().c_str(),
667 mParent->settingsFilePath().c_str());
668
669 rc = loadMachineDataFromSettings(*mData->pMachineConfigFile,
670 NULL /* const Guid *puuidRegistry */);
671 if (FAILED(rc)) throw rc;
672 }
673 catch (HRESULT err)
674 {
675 /* we assume that error info is set by the thrower */
676 rc = err;
677 }
678 catch (...)
679 {
680 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
681 }
682
683 /* Restore the registered flag (even on failure) */
684 mData->mRegistered = TRUE;
685 }
686
687 if (SUCCEEDED(rc))
688 {
689 /* Set mAccessible to TRUE only if we successfully locked and loaded
690 * the settings file */
691 mData->mAccessible = TRUE;
692
693 /* commit all changes made during loading the settings file */
694 commit(); // @todo r=dj why do we need a commit during init?!? this is very expensive
695 }
696 else
697 {
698 /* If the machine is registered, then, instead of returning a
699 * failure, we mark it as inaccessible and set the result to
700 * success to give it a try later */
701
702 /* fetch the current error info */
703 mData->mAccessError = com::ErrorInfo();
704 LogWarning(("Machine {%RTuuid} is inaccessible! [%ls]\n",
705 mData->mUuid.raw(),
706 mData->mAccessError.getText().raw()));
707
708 /* rollback all changes */
709 rollback(false /* aNotify */);
710
711 // uninit media from this machine's media registry, or else
712 // reloading the settings will fail
713 mParent->unregisterMachineMedia(getId());
714
715 /* uninitialize the common part to make sure all data is reset to
716 * default (null) values */
717 uninitDataAndChildObjects();
718
719 rc = S_OK;
720 }
721
722 return rc;
723}
724
725/**
726 * Uninitializes the instance.
727 * Called either from FinalRelease() or by the parent when it gets destroyed.
728 *
729 * @note The caller of this method must make sure that this object
730 * a) doesn't have active callers on the current thread and b) is not locked
731 * by the current thread; otherwise uninit() will hang either a) due to
732 * AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
733 * a dead-lock caused by this thread waiting for all callers on the other
734 * threads are done but preventing them from doing so by holding a lock.
735 */
736void Machine::uninit()
737{
738 LogFlowThisFuncEnter();
739
740 Assert(!isWriteLockOnCurrentThread());
741
742 /* Enclose the state transition Ready->InUninit->NotReady */
743 AutoUninitSpan autoUninitSpan(this);
744 if (autoUninitSpan.uninitDone())
745 return;
746
747 Assert(!isSnapshotMachine());
748 Assert(!isSessionMachine());
749 Assert(!!mData);
750
751 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
752 LogFlowThisFunc(("mRegistered=%d\n", mData->mRegistered));
753
754 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
755
756 if (!mData->mSession.mMachine.isNull())
757 {
758 /* Theoretically, this can only happen if the VirtualBox server has been
759 * terminated while there were clients running that owned open direct
760 * sessions. Since in this case we are definitely called by
761 * VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
762 * won't happen on the client watcher thread (because it does
763 * VirtualBox::addCaller() for the duration of the
764 * SessionMachine::checkForDeath() call, so that VirtualBox::uninit()
765 * cannot happen until the VirtualBox caller is released). This is
766 * important, because SessionMachine::uninit() cannot correctly operate
767 * after we return from this method (it expects the Machine instance is
768 * still valid). We'll call it ourselves below.
769 */
770 LogWarningThisFunc(("Session machine is not NULL (%p), the direct session is still open!\n",
771 (SessionMachine*)mData->mSession.mMachine));
772
773 if (Global::IsOnlineOrTransient(mData->mMachineState))
774 {
775 LogWarningThisFunc(("Setting state to Aborted!\n"));
776 /* set machine state using SessionMachine reimplementation */
777 static_cast<Machine*>(mData->mSession.mMachine)->setMachineState(MachineState_Aborted);
778 }
779
780 /*
781 * Uninitialize SessionMachine using public uninit() to indicate
782 * an unexpected uninitialization.
783 */
784 mData->mSession.mMachine->uninit();
785 /* SessionMachine::uninit() must set mSession.mMachine to null */
786 Assert(mData->mSession.mMachine.isNull());
787 }
788
789 // uninit media from this machine's media registry, if they're still there
790 Guid uuidMachine(getId());
791 if (!uuidMachine.isEmpty()) // can be empty if we're called from a failure of Machine::init
792 mParent->unregisterMachineMedia(uuidMachine);
793
794 /* the lock is no more necessary (SessionMachine is uninitialized) */
795 alock.leave();
796
797 // has machine been modified?
798 if (mData->flModifications)
799 {
800 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
801 rollback(false /* aNotify */);
802 }
803
804 if (mData->mAccessible)
805 uninitDataAndChildObjects();
806
807 /* free the essential data structure last */
808 mData.free();
809
810 LogFlowThisFuncLeave();
811}
812
813// IMachine properties
814/////////////////////////////////////////////////////////////////////////////
815
816STDMETHODIMP Machine::COMGETTER(Parent)(IVirtualBox **aParent)
817{
818 CheckComArgOutPointerValid(aParent);
819
820 AutoLimitedCaller autoCaller(this);
821 if (FAILED(autoCaller.rc())) return autoCaller.rc();
822
823 /* mParent is constant during life time, no need to lock */
824 ComObjPtr<VirtualBox> pVirtualBox(mParent);
825 pVirtualBox.queryInterfaceTo(aParent);
826
827 return S_OK;
828}
829
830STDMETHODIMP Machine::COMGETTER(Accessible)(BOOL *aAccessible)
831{
832 CheckComArgOutPointerValid(aAccessible);
833
834 AutoLimitedCaller autoCaller(this);
835 if (FAILED(autoCaller.rc())) return autoCaller.rc();
836
837 LogFlowThisFunc(("ENTER\n"));
838
839 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
840
841 HRESULT rc = S_OK;
842
843 if (!mData->mAccessible)
844 {
845 /* try to initialize the VM once more if not accessible */
846
847 AutoReinitSpan autoReinitSpan(this);
848 AssertReturn(autoReinitSpan.isOk(), E_FAIL);
849
850#ifdef DEBUG
851 LogFlowThisFunc(("Dumping media backreferences\n"));
852 mParent->dumpAllBackRefs();
853#endif
854
855 if (mData->pMachineConfigFile)
856 {
857 // reset the XML file to force loadSettings() (called from registeredInit())
858 // to parse it again; the file might have changed
859 delete mData->pMachineConfigFile;
860 mData->pMachineConfigFile = NULL;
861 }
862
863 rc = registeredInit();
864
865 if (SUCCEEDED(rc) && mData->mAccessible)
866 {
867 autoReinitSpan.setSucceeded();
868
869 /* make sure interesting parties will notice the accessibility
870 * state change */
871 mParent->onMachineStateChange(mData->mUuid, mData->mMachineState);
872 mParent->onMachineDataChange(mData->mUuid);
873 }
874 }
875
876 if (SUCCEEDED(rc))
877 *aAccessible = mData->mAccessible;
878
879 LogFlowThisFuncLeave();
880
881 return rc;
882}
883
884STDMETHODIMP Machine::COMGETTER(AccessError)(IVirtualBoxErrorInfo **aAccessError)
885{
886 CheckComArgOutPointerValid(aAccessError);
887
888 AutoLimitedCaller autoCaller(this);
889 if (FAILED(autoCaller.rc())) return autoCaller.rc();
890
891 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
892
893 if (mData->mAccessible || !mData->mAccessError.isBasicAvailable())
894 {
895 /* return shortly */
896 aAccessError = NULL;
897 return S_OK;
898 }
899
900 HRESULT rc = S_OK;
901
902 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
903 rc = errorInfo.createObject();
904 if (SUCCEEDED(rc))
905 {
906 errorInfo->init(mData->mAccessError.getResultCode(),
907 mData->mAccessError.getInterfaceID().ref(),
908 Utf8Str(mData->mAccessError.getComponent()).c_str(),
909 Utf8Str(mData->mAccessError.getText()));
910 rc = errorInfo.queryInterfaceTo(aAccessError);
911 }
912
913 return rc;
914}
915
916STDMETHODIMP Machine::COMGETTER(Name)(BSTR *aName)
917{
918 CheckComArgOutPointerValid(aName);
919
920 AutoCaller autoCaller(this);
921 if (FAILED(autoCaller.rc())) return autoCaller.rc();
922
923 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
924
925 mUserData->s.strName.cloneTo(aName);
926
927 return S_OK;
928}
929
930STDMETHODIMP Machine::COMSETTER(Name)(IN_BSTR aName)
931{
932 CheckComArgStrNotEmptyOrNull(aName);
933
934 AutoCaller autoCaller(this);
935 if (FAILED(autoCaller.rc())) return autoCaller.rc();
936
937 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
938
939 HRESULT rc = checkStateDependency(MutableStateDep);
940 if (FAILED(rc)) return rc;
941
942 setModified(IsModified_MachineData);
943 mUserData.backup();
944 mUserData->s.strName = aName;
945
946 return S_OK;
947}
948
949STDMETHODIMP Machine::COMGETTER(Description)(BSTR *aDescription)
950{
951 CheckComArgOutPointerValid(aDescription);
952
953 AutoCaller autoCaller(this);
954 if (FAILED(autoCaller.rc())) return autoCaller.rc();
955
956 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
957
958 mUserData->s.strDescription.cloneTo(aDescription);
959
960 return S_OK;
961}
962
963STDMETHODIMP Machine::COMSETTER(Description)(IN_BSTR aDescription)
964{
965 AutoCaller autoCaller(this);
966 if (FAILED(autoCaller.rc())) return autoCaller.rc();
967
968 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
969
970 HRESULT rc = checkStateDependency(MutableStateDep);
971 if (FAILED(rc)) return rc;
972
973 setModified(IsModified_MachineData);
974 mUserData.backup();
975 mUserData->s.strDescription = aDescription;
976
977 return S_OK;
978}
979
980STDMETHODIMP Machine::COMGETTER(Id)(BSTR *aId)
981{
982 CheckComArgOutPointerValid(aId);
983
984 AutoLimitedCaller autoCaller(this);
985 if (FAILED(autoCaller.rc())) return autoCaller.rc();
986
987 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
988
989 mData->mUuid.toUtf16().cloneTo(aId);
990
991 return S_OK;
992}
993
994STDMETHODIMP Machine::COMGETTER(OSTypeId)(BSTR *aOSTypeId)
995{
996 CheckComArgOutPointerValid(aOSTypeId);
997
998 AutoCaller autoCaller(this);
999 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1000
1001 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1002
1003 mUserData->s.strOsType.cloneTo(aOSTypeId);
1004
1005 return S_OK;
1006}
1007
1008STDMETHODIMP Machine::COMSETTER(OSTypeId)(IN_BSTR aOSTypeId)
1009{
1010 CheckComArgStrNotEmptyOrNull(aOSTypeId);
1011
1012 AutoCaller autoCaller(this);
1013 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1014
1015 /* look up the object by Id to check it is valid */
1016 ComPtr<IGuestOSType> guestOSType;
1017 HRESULT rc = mParent->GetGuestOSType(aOSTypeId, guestOSType.asOutParam());
1018 if (FAILED(rc)) return rc;
1019
1020 /* when setting, always use the "etalon" value for consistency -- lookup
1021 * by ID is case-insensitive and the input value may have different case */
1022 Bstr osTypeId;
1023 rc = guestOSType->COMGETTER(Id)(osTypeId.asOutParam());
1024 if (FAILED(rc)) return rc;
1025
1026 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1027
1028 rc = checkStateDependency(MutableStateDep);
1029 if (FAILED(rc)) return rc;
1030
1031 setModified(IsModified_MachineData);
1032 mUserData.backup();
1033 mUserData->s.strOsType = osTypeId;
1034
1035 return S_OK;
1036}
1037
1038
1039STDMETHODIMP Machine::COMGETTER(FirmwareType)(FirmwareType_T *aFirmwareType)
1040{
1041 CheckComArgOutPointerValid(aFirmwareType);
1042
1043 AutoCaller autoCaller(this);
1044 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1045
1046 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1047
1048 *aFirmwareType = mHWData->mFirmwareType;
1049
1050 return S_OK;
1051}
1052
1053STDMETHODIMP Machine::COMSETTER(FirmwareType)(FirmwareType_T aFirmwareType)
1054{
1055 AutoCaller autoCaller(this);
1056 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1057 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1058
1059 int rc = checkStateDependency(MutableStateDep);
1060 if (FAILED(rc)) return rc;
1061
1062 setModified(IsModified_MachineData);
1063 mHWData.backup();
1064 mHWData->mFirmwareType = aFirmwareType;
1065
1066 return S_OK;
1067}
1068
1069STDMETHODIMP Machine::COMGETTER(KeyboardHidType)(KeyboardHidType_T *aKeyboardHidType)
1070{
1071 CheckComArgOutPointerValid(aKeyboardHidType);
1072
1073 AutoCaller autoCaller(this);
1074 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1075
1076 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1077
1078 *aKeyboardHidType = mHWData->mKeyboardHidType;
1079
1080 return S_OK;
1081}
1082
1083STDMETHODIMP Machine::COMSETTER(KeyboardHidType)(KeyboardHidType_T aKeyboardHidType)
1084{
1085 AutoCaller autoCaller(this);
1086 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1087 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1088
1089 int rc = checkStateDependency(MutableStateDep);
1090 if (FAILED(rc)) return rc;
1091
1092 setModified(IsModified_MachineData);
1093 mHWData.backup();
1094 mHWData->mKeyboardHidType = aKeyboardHidType;
1095
1096 return S_OK;
1097}
1098
1099STDMETHODIMP Machine::COMGETTER(PointingHidType)(PointingHidType_T *aPointingHidType)
1100{
1101 CheckComArgOutPointerValid(aPointingHidType);
1102
1103 AutoCaller autoCaller(this);
1104 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1105
1106 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1107
1108 *aPointingHidType = mHWData->mPointingHidType;
1109
1110 return S_OK;
1111}
1112
1113STDMETHODIMP Machine::COMSETTER(PointingHidType)(PointingHidType_T aPointingHidType)
1114{
1115 AutoCaller autoCaller(this);
1116 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1117 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1118
1119 int rc = checkStateDependency(MutableStateDep);
1120 if (FAILED(rc)) return rc;
1121
1122 setModified(IsModified_MachineData);
1123 mHWData.backup();
1124 mHWData->mPointingHidType = aPointingHidType;
1125
1126 return S_OK;
1127}
1128
1129STDMETHODIMP Machine::COMGETTER(ChipsetType)(ChipsetType_T *aChipsetType)
1130{
1131 CheckComArgOutPointerValid(aChipsetType);
1132
1133 AutoCaller autoCaller(this);
1134 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1135
1136 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1137
1138 *aChipsetType = mHWData->mChipsetType;
1139
1140 return S_OK;
1141}
1142
1143STDMETHODIMP Machine::COMSETTER(ChipsetType)(ChipsetType_T aChipsetType)
1144{
1145 AutoCaller autoCaller(this);
1146 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1147 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1148
1149 int rc = checkStateDependency(MutableStateDep);
1150 if (FAILED(rc)) return rc;
1151
1152 setModified(IsModified_MachineData);
1153 mHWData.backup();
1154 mHWData->mChipsetType = aChipsetType;
1155
1156 return S_OK;
1157}
1158
1159STDMETHODIMP Machine::COMGETTER(HardwareVersion)(BSTR *aHWVersion)
1160{
1161 if (!aHWVersion)
1162 return E_POINTER;
1163
1164 AutoCaller autoCaller(this);
1165 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1166
1167 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1168
1169 mHWData->mHWVersion.cloneTo(aHWVersion);
1170
1171 return S_OK;
1172}
1173
1174STDMETHODIMP Machine::COMSETTER(HardwareVersion)(IN_BSTR aHWVersion)
1175{
1176 /* check known version */
1177 Utf8Str hwVersion = aHWVersion;
1178 if ( hwVersion.compare("1") != 0
1179 && hwVersion.compare("2") != 0)
1180 return setError(E_INVALIDARG,
1181 tr("Invalid hardware version: %ls\n"), aHWVersion);
1182
1183 AutoCaller autoCaller(this);
1184 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1185
1186 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1187
1188 HRESULT rc = checkStateDependency(MutableStateDep);
1189 if (FAILED(rc)) return rc;
1190
1191 setModified(IsModified_MachineData);
1192 mHWData.backup();
1193 mHWData->mHWVersion = hwVersion;
1194
1195 return S_OK;
1196}
1197
1198STDMETHODIMP Machine::COMGETTER(HardwareUUID)(BSTR *aUUID)
1199{
1200 CheckComArgOutPointerValid(aUUID);
1201
1202 AutoCaller autoCaller(this);
1203 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1204
1205 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1206
1207 if (!mHWData->mHardwareUUID.isEmpty())
1208 mHWData->mHardwareUUID.toUtf16().cloneTo(aUUID);
1209 else
1210 mData->mUuid.toUtf16().cloneTo(aUUID);
1211
1212 return S_OK;
1213}
1214
1215STDMETHODIMP Machine::COMSETTER(HardwareUUID)(IN_BSTR aUUID)
1216{
1217 Guid hardwareUUID(aUUID);
1218 if (hardwareUUID.isEmpty())
1219 return E_INVALIDARG;
1220
1221 AutoCaller autoCaller(this);
1222 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1223
1224 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1225
1226 HRESULT rc = checkStateDependency(MutableStateDep);
1227 if (FAILED(rc)) return rc;
1228
1229 setModified(IsModified_MachineData);
1230 mHWData.backup();
1231 if (hardwareUUID == mData->mUuid)
1232 mHWData->mHardwareUUID.clear();
1233 else
1234 mHWData->mHardwareUUID = hardwareUUID;
1235
1236 return S_OK;
1237}
1238
1239STDMETHODIMP Machine::COMGETTER(MemorySize)(ULONG *memorySize)
1240{
1241 if (!memorySize)
1242 return E_POINTER;
1243
1244 AutoCaller autoCaller(this);
1245 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1246
1247 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1248
1249 *memorySize = mHWData->mMemorySize;
1250
1251 return S_OK;
1252}
1253
1254STDMETHODIMP Machine::COMSETTER(MemorySize)(ULONG memorySize)
1255{
1256 /* check RAM limits */
1257 if ( memorySize < MM_RAM_MIN_IN_MB
1258 || memorySize > MM_RAM_MAX_IN_MB
1259 )
1260 return setError(E_INVALIDARG,
1261 tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1262 memorySize, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
1263
1264 AutoCaller autoCaller(this);
1265 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1266
1267 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1268
1269 HRESULT rc = checkStateDependency(MutableStateDep);
1270 if (FAILED(rc)) return rc;
1271
1272 setModified(IsModified_MachineData);
1273 mHWData.backup();
1274 mHWData->mMemorySize = memorySize;
1275
1276 return S_OK;
1277}
1278
1279STDMETHODIMP Machine::COMGETTER(CPUCount)(ULONG *CPUCount)
1280{
1281 if (!CPUCount)
1282 return E_POINTER;
1283
1284 AutoCaller autoCaller(this);
1285 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1286
1287 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1288
1289 *CPUCount = mHWData->mCPUCount;
1290
1291 return S_OK;
1292}
1293
1294STDMETHODIMP Machine::COMSETTER(CPUCount)(ULONG CPUCount)
1295{
1296 /* check CPU limits */
1297 if ( CPUCount < SchemaDefs::MinCPUCount
1298 || CPUCount > SchemaDefs::MaxCPUCount
1299 )
1300 return setError(E_INVALIDARG,
1301 tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
1302 CPUCount, SchemaDefs::MinCPUCount, SchemaDefs::MaxCPUCount);
1303
1304 AutoCaller autoCaller(this);
1305 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1306
1307 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1308
1309 /* We cant go below the current number of CPUs if hotplug is enabled*/
1310 if (mHWData->mCPUHotPlugEnabled)
1311 {
1312 for (unsigned idx = CPUCount; idx < SchemaDefs::MaxCPUCount; idx++)
1313 {
1314 if (mHWData->mCPUAttached[idx])
1315 return setError(E_INVALIDARG,
1316 tr(": %lu (must be higher than or equal to %lu)"),
1317 CPUCount, idx+1);
1318 }
1319 }
1320
1321 HRESULT rc = checkStateDependency(MutableStateDep);
1322 if (FAILED(rc)) return rc;
1323
1324 setModified(IsModified_MachineData);
1325 mHWData.backup();
1326 mHWData->mCPUCount = CPUCount;
1327
1328 return S_OK;
1329}
1330
1331STDMETHODIMP Machine::COMGETTER(CPUExecutionCap)(ULONG *aExecutionCap)
1332{
1333 if (!aExecutionCap)
1334 return E_POINTER;
1335
1336 AutoCaller autoCaller(this);
1337 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1338
1339 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1340
1341 *aExecutionCap = mHWData->mCpuExecutionCap;
1342
1343 return S_OK;
1344}
1345
1346STDMETHODIMP Machine::COMSETTER(CPUExecutionCap)(ULONG aExecutionCap)
1347{
1348 HRESULT rc = S_OK;
1349
1350 /* check throttle limits */
1351 if ( aExecutionCap < 1
1352 || aExecutionCap > 100
1353 )
1354 return setError(E_INVALIDARG,
1355 tr("Invalid CPU execution cap value: %lu (must be in range [%lu, %lu])"),
1356 aExecutionCap, 1, 100);
1357
1358 AutoCaller autoCaller(this);
1359 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1360
1361 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1362
1363 alock.release();
1364 rc = onCPUExecutionCapChange(aExecutionCap);
1365 alock.acquire();
1366 if (FAILED(rc)) return rc;
1367
1368 setModified(IsModified_MachineData);
1369 mHWData.backup();
1370 mHWData->mCpuExecutionCap = aExecutionCap;
1371
1372 /* Save settings if online - todo why is this required?? */
1373 if (Global::IsOnline(mData->mMachineState))
1374 saveSettings(NULL);
1375
1376 return S_OK;
1377}
1378
1379
1380STDMETHODIMP Machine::COMGETTER(CPUHotPlugEnabled)(BOOL *enabled)
1381{
1382 if (!enabled)
1383 return E_POINTER;
1384
1385 AutoCaller autoCaller(this);
1386 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1387
1388 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1389
1390 *enabled = mHWData->mCPUHotPlugEnabled;
1391
1392 return S_OK;
1393}
1394
1395STDMETHODIMP Machine::COMSETTER(CPUHotPlugEnabled)(BOOL enabled)
1396{
1397 HRESULT rc = S_OK;
1398
1399 AutoCaller autoCaller(this);
1400 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1401
1402 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1403
1404 rc = checkStateDependency(MutableStateDep);
1405 if (FAILED(rc)) return rc;
1406
1407 if (mHWData->mCPUHotPlugEnabled != enabled)
1408 {
1409 if (enabled)
1410 {
1411 setModified(IsModified_MachineData);
1412 mHWData.backup();
1413
1414 /* Add the amount of CPUs currently attached */
1415 for (unsigned i = 0; i < mHWData->mCPUCount; i++)
1416 {
1417 mHWData->mCPUAttached[i] = true;
1418 }
1419 }
1420 else
1421 {
1422 /*
1423 * We can disable hotplug only if the amount of maximum CPUs is equal
1424 * to the amount of attached CPUs
1425 */
1426 unsigned cCpusAttached = 0;
1427 unsigned iHighestId = 0;
1428
1429 for (unsigned i = 0; i < SchemaDefs::MaxCPUCount; i++)
1430 {
1431 if (mHWData->mCPUAttached[i])
1432 {
1433 cCpusAttached++;
1434 iHighestId = i;
1435 }
1436 }
1437
1438 if ( (cCpusAttached != mHWData->mCPUCount)
1439 || (iHighestId >= mHWData->mCPUCount))
1440 return setError(E_INVALIDARG,
1441 tr("CPU hotplugging can't be disabled because the maximum number of CPUs is not equal to the amount of CPUs attached\n"));
1442
1443 setModified(IsModified_MachineData);
1444 mHWData.backup();
1445 }
1446 }
1447
1448 mHWData->mCPUHotPlugEnabled = enabled;
1449
1450 return rc;
1451}
1452
1453STDMETHODIMP Machine::COMGETTER(HpetEnabled)(BOOL *enabled)
1454{
1455 CheckComArgOutPointerValid(enabled);
1456
1457 AutoCaller autoCaller(this);
1458 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1459 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1460
1461 *enabled = mHWData->mHpetEnabled;
1462
1463 return S_OK;
1464}
1465
1466STDMETHODIMP Machine::COMSETTER(HpetEnabled)(BOOL enabled)
1467{
1468 HRESULT rc = S_OK;
1469
1470 AutoCaller autoCaller(this);
1471 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1472 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1473
1474 rc = checkStateDependency(MutableStateDep);
1475 if (FAILED(rc)) return rc;
1476
1477 setModified(IsModified_MachineData);
1478 mHWData.backup();
1479
1480 mHWData->mHpetEnabled = enabled;
1481
1482 return rc;
1483}
1484
1485STDMETHODIMP Machine::COMGETTER(VRAMSize)(ULONG *memorySize)
1486{
1487 if (!memorySize)
1488 return E_POINTER;
1489
1490 AutoCaller autoCaller(this);
1491 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1492
1493 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1494
1495 *memorySize = mHWData->mVRAMSize;
1496
1497 return S_OK;
1498}
1499
1500STDMETHODIMP Machine::COMSETTER(VRAMSize)(ULONG memorySize)
1501{
1502 /* check VRAM limits */
1503 if (memorySize < SchemaDefs::MinGuestVRAM ||
1504 memorySize > SchemaDefs::MaxGuestVRAM)
1505 return setError(E_INVALIDARG,
1506 tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1507 memorySize, SchemaDefs::MinGuestVRAM, SchemaDefs::MaxGuestVRAM);
1508
1509 AutoCaller autoCaller(this);
1510 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1511
1512 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1513
1514 HRESULT rc = checkStateDependency(MutableStateDep);
1515 if (FAILED(rc)) return rc;
1516
1517 setModified(IsModified_MachineData);
1518 mHWData.backup();
1519 mHWData->mVRAMSize = memorySize;
1520
1521 return S_OK;
1522}
1523
1524/** @todo this method should not be public */
1525STDMETHODIMP Machine::COMGETTER(MemoryBalloonSize)(ULONG *memoryBalloonSize)
1526{
1527 if (!memoryBalloonSize)
1528 return E_POINTER;
1529
1530 AutoCaller autoCaller(this);
1531 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1532
1533 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1534
1535 *memoryBalloonSize = mHWData->mMemoryBalloonSize;
1536
1537 return S_OK;
1538}
1539
1540/**
1541 * Set the memory balloon size.
1542 *
1543 * This method is also called from IGuest::COMSETTER(MemoryBalloonSize) so
1544 * we have to make sure that we never call IGuest from here.
1545 */
1546STDMETHODIMP Machine::COMSETTER(MemoryBalloonSize)(ULONG memoryBalloonSize)
1547{
1548 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
1549#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
1550 /* check limits */
1551 if (memoryBalloonSize >= VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize))
1552 return setError(E_INVALIDARG,
1553 tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
1554 memoryBalloonSize, 0, VMMDEV_MAX_MEMORY_BALLOON(mHWData->mMemorySize));
1555
1556 AutoCaller autoCaller(this);
1557 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1558
1559 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1560
1561 setModified(IsModified_MachineData);
1562 mHWData.backup();
1563 mHWData->mMemoryBalloonSize = memoryBalloonSize;
1564
1565 return S_OK;
1566#else
1567 NOREF(memoryBalloonSize);
1568 return setError(E_NOTIMPL, tr("Memory ballooning is only supported on 64-bit hosts"));
1569#endif
1570}
1571
1572STDMETHODIMP Machine::COMGETTER(PageFusionEnabled) (BOOL *enabled)
1573{
1574 if (!enabled)
1575 return E_POINTER;
1576
1577 AutoCaller autoCaller(this);
1578 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1579
1580 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1581
1582 *enabled = mHWData->mPageFusionEnabled;
1583 return S_OK;
1584}
1585
1586STDMETHODIMP Machine::COMSETTER(PageFusionEnabled) (BOOL enabled)
1587{
1588#ifdef VBOX_WITH_PAGE_SHARING
1589 AutoCaller autoCaller(this);
1590 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1591
1592 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1593
1594 /** @todo must support changes for running vms and keep this in sync with IGuest. */
1595 setModified(IsModified_MachineData);
1596 mHWData.backup();
1597 mHWData->mPageFusionEnabled = enabled;
1598 return S_OK;
1599#else
1600 NOREF(enabled);
1601 return setError(E_NOTIMPL, tr("Page fusion is only supported on 64-bit hosts"));
1602#endif
1603}
1604
1605STDMETHODIMP Machine::COMGETTER(Accelerate3DEnabled)(BOOL *enabled)
1606{
1607 if (!enabled)
1608 return E_POINTER;
1609
1610 AutoCaller autoCaller(this);
1611 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1612
1613 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1614
1615 *enabled = mHWData->mAccelerate3DEnabled;
1616
1617 return S_OK;
1618}
1619
1620STDMETHODIMP Machine::COMSETTER(Accelerate3DEnabled)(BOOL enable)
1621{
1622 AutoCaller autoCaller(this);
1623 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1624
1625 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1626
1627 HRESULT rc = checkStateDependency(MutableStateDep);
1628 if (FAILED(rc)) return rc;
1629
1630 /** @todo check validity! */
1631
1632 setModified(IsModified_MachineData);
1633 mHWData.backup();
1634 mHWData->mAccelerate3DEnabled = enable;
1635
1636 return S_OK;
1637}
1638
1639
1640STDMETHODIMP Machine::COMGETTER(Accelerate2DVideoEnabled)(BOOL *enabled)
1641{
1642 if (!enabled)
1643 return E_POINTER;
1644
1645 AutoCaller autoCaller(this);
1646 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1647
1648 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1649
1650 *enabled = mHWData->mAccelerate2DVideoEnabled;
1651
1652 return S_OK;
1653}
1654
1655STDMETHODIMP Machine::COMSETTER(Accelerate2DVideoEnabled)(BOOL enable)
1656{
1657 AutoCaller autoCaller(this);
1658 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1659
1660 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1661
1662 HRESULT rc = checkStateDependency(MutableStateDep);
1663 if (FAILED(rc)) return rc;
1664
1665 /** @todo check validity! */
1666
1667 setModified(IsModified_MachineData);
1668 mHWData.backup();
1669 mHWData->mAccelerate2DVideoEnabled = enable;
1670
1671 return S_OK;
1672}
1673
1674STDMETHODIMP Machine::COMGETTER(MonitorCount)(ULONG *monitorCount)
1675{
1676 if (!monitorCount)
1677 return E_POINTER;
1678
1679 AutoCaller autoCaller(this);
1680 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1681
1682 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1683
1684 *monitorCount = mHWData->mMonitorCount;
1685
1686 return S_OK;
1687}
1688
1689STDMETHODIMP Machine::COMSETTER(MonitorCount)(ULONG monitorCount)
1690{
1691 /* make sure monitor count is a sensible number */
1692 if (monitorCount < 1 || monitorCount > SchemaDefs::MaxGuestMonitors)
1693 return setError(E_INVALIDARG,
1694 tr("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
1695 monitorCount, 1, SchemaDefs::MaxGuestMonitors);
1696
1697 AutoCaller autoCaller(this);
1698 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1699
1700 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1701
1702 HRESULT rc = checkStateDependency(MutableStateDep);
1703 if (FAILED(rc)) return rc;
1704
1705 setModified(IsModified_MachineData);
1706 mHWData.backup();
1707 mHWData->mMonitorCount = monitorCount;
1708
1709 return S_OK;
1710}
1711
1712STDMETHODIMP Machine::COMGETTER(BIOSSettings)(IBIOSSettings **biosSettings)
1713{
1714 if (!biosSettings)
1715 return E_POINTER;
1716
1717 AutoCaller autoCaller(this);
1718 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1719
1720 /* mBIOSSettings is constant during life time, no need to lock */
1721 mBIOSSettings.queryInterfaceTo(biosSettings);
1722
1723 return S_OK;
1724}
1725
1726STDMETHODIMP Machine::GetCPUProperty(CPUPropertyType_T property, BOOL *aVal)
1727{
1728 if (!aVal)
1729 return E_POINTER;
1730
1731 AutoCaller autoCaller(this);
1732 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1733
1734 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1735
1736 switch(property)
1737 {
1738 case CPUPropertyType_PAE:
1739 *aVal = mHWData->mPAEEnabled;
1740 break;
1741
1742 case CPUPropertyType_Synthetic:
1743 *aVal = mHWData->mSyntheticCpu;
1744 break;
1745
1746 default:
1747 return E_INVALIDARG;
1748 }
1749 return S_OK;
1750}
1751
1752STDMETHODIMP Machine::SetCPUProperty(CPUPropertyType_T property, BOOL aVal)
1753{
1754 AutoCaller autoCaller(this);
1755 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1756
1757 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1758
1759 HRESULT rc = checkStateDependency(MutableStateDep);
1760 if (FAILED(rc)) return rc;
1761
1762 switch(property)
1763 {
1764 case CPUPropertyType_PAE:
1765 setModified(IsModified_MachineData);
1766 mHWData.backup();
1767 mHWData->mPAEEnabled = !!aVal;
1768 break;
1769
1770 case CPUPropertyType_Synthetic:
1771 setModified(IsModified_MachineData);
1772 mHWData.backup();
1773 mHWData->mSyntheticCpu = !!aVal;
1774 break;
1775
1776 default:
1777 return E_INVALIDARG;
1778 }
1779 return S_OK;
1780}
1781
1782STDMETHODIMP Machine::GetCPUIDLeaf(ULONG aId, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx)
1783{
1784 CheckComArgOutPointerValid(aValEax);
1785 CheckComArgOutPointerValid(aValEbx);
1786 CheckComArgOutPointerValid(aValEcx);
1787 CheckComArgOutPointerValid(aValEdx);
1788
1789 AutoCaller autoCaller(this);
1790 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1791
1792 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1793
1794 switch(aId)
1795 {
1796 case 0x0:
1797 case 0x1:
1798 case 0x2:
1799 case 0x3:
1800 case 0x4:
1801 case 0x5:
1802 case 0x6:
1803 case 0x7:
1804 case 0x8:
1805 case 0x9:
1806 case 0xA:
1807 if (mHWData->mCpuIdStdLeafs[aId].ulId != aId)
1808 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is not set"), aId);
1809
1810 *aValEax = mHWData->mCpuIdStdLeafs[aId].ulEax;
1811 *aValEbx = mHWData->mCpuIdStdLeafs[aId].ulEbx;
1812 *aValEcx = mHWData->mCpuIdStdLeafs[aId].ulEcx;
1813 *aValEdx = mHWData->mCpuIdStdLeafs[aId].ulEdx;
1814 break;
1815
1816 case 0x80000000:
1817 case 0x80000001:
1818 case 0x80000002:
1819 case 0x80000003:
1820 case 0x80000004:
1821 case 0x80000005:
1822 case 0x80000006:
1823 case 0x80000007:
1824 case 0x80000008:
1825 case 0x80000009:
1826 case 0x8000000A:
1827 if (mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId != aId)
1828 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is not set"), aId);
1829
1830 *aValEax = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax;
1831 *aValEbx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx;
1832 *aValEcx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx;
1833 *aValEdx = mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx;
1834 break;
1835
1836 default:
1837 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
1838 }
1839 return S_OK;
1840}
1841
1842STDMETHODIMP Machine::SetCPUIDLeaf(ULONG aId, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx)
1843{
1844 AutoCaller autoCaller(this);
1845 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1846
1847 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1848
1849 HRESULT rc = checkStateDependency(MutableStateDep);
1850 if (FAILED(rc)) return rc;
1851
1852 switch(aId)
1853 {
1854 case 0x0:
1855 case 0x1:
1856 case 0x2:
1857 case 0x3:
1858 case 0x4:
1859 case 0x5:
1860 case 0x6:
1861 case 0x7:
1862 case 0x8:
1863 case 0x9:
1864 case 0xA:
1865 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xA);
1866 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
1867 setModified(IsModified_MachineData);
1868 mHWData.backup();
1869 mHWData->mCpuIdStdLeafs[aId].ulId = aId;
1870 mHWData->mCpuIdStdLeafs[aId].ulEax = aValEax;
1871 mHWData->mCpuIdStdLeafs[aId].ulEbx = aValEbx;
1872 mHWData->mCpuIdStdLeafs[aId].ulEcx = aValEcx;
1873 mHWData->mCpuIdStdLeafs[aId].ulEdx = aValEdx;
1874 break;
1875
1876 case 0x80000000:
1877 case 0x80000001:
1878 case 0x80000002:
1879 case 0x80000003:
1880 case 0x80000004:
1881 case 0x80000005:
1882 case 0x80000006:
1883 case 0x80000007:
1884 case 0x80000008:
1885 case 0x80000009:
1886 case 0x8000000A:
1887 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xA);
1888 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
1889 setModified(IsModified_MachineData);
1890 mHWData.backup();
1891 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = aId;
1892 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEax = aValEax;
1893 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEbx = aValEbx;
1894 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEcx = aValEcx;
1895 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulEdx = aValEdx;
1896 break;
1897
1898 default:
1899 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
1900 }
1901 return S_OK;
1902}
1903
1904STDMETHODIMP Machine::RemoveCPUIDLeaf(ULONG aId)
1905{
1906 AutoCaller autoCaller(this);
1907 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1908
1909 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1910
1911 HRESULT rc = checkStateDependency(MutableStateDep);
1912 if (FAILED(rc)) return rc;
1913
1914 switch(aId)
1915 {
1916 case 0x0:
1917 case 0x1:
1918 case 0x2:
1919 case 0x3:
1920 case 0x4:
1921 case 0x5:
1922 case 0x6:
1923 case 0x7:
1924 case 0x8:
1925 case 0x9:
1926 case 0xA:
1927 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdStdLeafs) == 0xA);
1928 AssertRelease(aId < RT_ELEMENTS(mHWData->mCpuIdStdLeafs));
1929 setModified(IsModified_MachineData);
1930 mHWData.backup();
1931 /* Invalidate leaf. */
1932 mHWData->mCpuIdStdLeafs[aId].ulId = UINT32_MAX;
1933 break;
1934
1935 case 0x80000000:
1936 case 0x80000001:
1937 case 0x80000002:
1938 case 0x80000003:
1939 case 0x80000004:
1940 case 0x80000005:
1941 case 0x80000006:
1942 case 0x80000007:
1943 case 0x80000008:
1944 case 0x80000009:
1945 case 0x8000000A:
1946 AssertCompile(RT_ELEMENTS(mHWData->mCpuIdExtLeafs) == 0xA);
1947 AssertRelease(aId - 0x80000000 < RT_ELEMENTS(mHWData->mCpuIdExtLeafs));
1948 setModified(IsModified_MachineData);
1949 mHWData.backup();
1950 /* Invalidate leaf. */
1951 mHWData->mCpuIdExtLeafs[aId - 0x80000000].ulId = UINT32_MAX;
1952 break;
1953
1954 default:
1955 return setError(E_INVALIDARG, tr("CpuId override leaf %#x is out of range"), aId);
1956 }
1957 return S_OK;
1958}
1959
1960STDMETHODIMP Machine::RemoveAllCPUIDLeaves()
1961{
1962 AutoCaller autoCaller(this);
1963 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1964
1965 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1966
1967 HRESULT rc = checkStateDependency(MutableStateDep);
1968 if (FAILED(rc)) return rc;
1969
1970 setModified(IsModified_MachineData);
1971 mHWData.backup();
1972
1973 /* Invalidate all standard leafs. */
1974 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); i++)
1975 mHWData->mCpuIdStdLeafs[i].ulId = UINT32_MAX;
1976
1977 /* Invalidate all extended leafs. */
1978 for (unsigned i = 0; i < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); i++)
1979 mHWData->mCpuIdExtLeafs[i].ulId = UINT32_MAX;
1980
1981 return S_OK;
1982}
1983
1984STDMETHODIMP Machine::GetHWVirtExProperty(HWVirtExPropertyType_T property, BOOL *aVal)
1985{
1986 if (!aVal)
1987 return E_POINTER;
1988
1989 AutoCaller autoCaller(this);
1990 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1991
1992 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1993
1994 switch(property)
1995 {
1996 case HWVirtExPropertyType_Enabled:
1997 *aVal = mHWData->mHWVirtExEnabled;
1998 break;
1999
2000 case HWVirtExPropertyType_Exclusive:
2001 *aVal = mHWData->mHWVirtExExclusive;
2002 break;
2003
2004 case HWVirtExPropertyType_VPID:
2005 *aVal = mHWData->mHWVirtExVPIDEnabled;
2006 break;
2007
2008 case HWVirtExPropertyType_NestedPaging:
2009 *aVal = mHWData->mHWVirtExNestedPagingEnabled;
2010 break;
2011
2012 case HWVirtExPropertyType_LargePages:
2013 *aVal = mHWData->mHWVirtExLargePagesEnabled;
2014 break;
2015
2016 case HWVirtExPropertyType_Force:
2017 *aVal = mHWData->mHWVirtExForceEnabled;
2018 break;
2019
2020 default:
2021 return E_INVALIDARG;
2022 }
2023 return S_OK;
2024}
2025
2026STDMETHODIMP Machine::SetHWVirtExProperty(HWVirtExPropertyType_T property, BOOL aVal)
2027{
2028 AutoCaller autoCaller(this);
2029 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2030
2031 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2032
2033 HRESULT rc = checkStateDependency(MutableStateDep);
2034 if (FAILED(rc)) return rc;
2035
2036 switch(property)
2037 {
2038 case HWVirtExPropertyType_Enabled:
2039 setModified(IsModified_MachineData);
2040 mHWData.backup();
2041 mHWData->mHWVirtExEnabled = !!aVal;
2042 break;
2043
2044 case HWVirtExPropertyType_Exclusive:
2045 setModified(IsModified_MachineData);
2046 mHWData.backup();
2047 mHWData->mHWVirtExExclusive = !!aVal;
2048 break;
2049
2050 case HWVirtExPropertyType_VPID:
2051 setModified(IsModified_MachineData);
2052 mHWData.backup();
2053 mHWData->mHWVirtExVPIDEnabled = !!aVal;
2054 break;
2055
2056 case HWVirtExPropertyType_NestedPaging:
2057 setModified(IsModified_MachineData);
2058 mHWData.backup();
2059 mHWData->mHWVirtExNestedPagingEnabled = !!aVal;
2060 break;
2061
2062 case HWVirtExPropertyType_LargePages:
2063 setModified(IsModified_MachineData);
2064 mHWData.backup();
2065 mHWData->mHWVirtExLargePagesEnabled = !!aVal;
2066 break;
2067
2068 case HWVirtExPropertyType_Force:
2069 setModified(IsModified_MachineData);
2070 mHWData.backup();
2071 mHWData->mHWVirtExForceEnabled = !!aVal;
2072 break;
2073
2074 default:
2075 return E_INVALIDARG;
2076 }
2077
2078 return S_OK;
2079}
2080
2081STDMETHODIMP Machine::COMGETTER(SnapshotFolder)(BSTR *aSnapshotFolder)
2082{
2083 CheckComArgOutPointerValid(aSnapshotFolder);
2084
2085 AutoCaller autoCaller(this);
2086 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2087
2088 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2089
2090 Utf8Str strFullSnapshotFolder;
2091 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
2092 strFullSnapshotFolder.cloneTo(aSnapshotFolder);
2093
2094 return S_OK;
2095}
2096
2097STDMETHODIMP Machine::COMSETTER(SnapshotFolder)(IN_BSTR aSnapshotFolder)
2098{
2099 /* @todo (r=dmik):
2100 * 1. Allow to change the name of the snapshot folder containing snapshots
2101 * 2. Rename the folder on disk instead of just changing the property
2102 * value (to be smart and not to leave garbage). Note that it cannot be
2103 * done here because the change may be rolled back. Thus, the right
2104 * place is #saveSettings().
2105 */
2106
2107 AutoCaller autoCaller(this);
2108 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2109
2110 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2111
2112 HRESULT rc = checkStateDependency(MutableStateDep);
2113 if (FAILED(rc)) return rc;
2114
2115 if (!mData->mCurrentSnapshot.isNull())
2116 return setError(E_FAIL,
2117 tr("The snapshot folder of a machine with snapshots cannot be changed (please delete all snapshots first)"));
2118
2119 Utf8Str strSnapshotFolder0(aSnapshotFolder); // keep original
2120
2121 Utf8Str strSnapshotFolder(strSnapshotFolder0);
2122 if (strSnapshotFolder.isEmpty())
2123 strSnapshotFolder = "Snapshots";
2124 int vrc = calculateFullPath(strSnapshotFolder,
2125 strSnapshotFolder);
2126 if (RT_FAILURE(vrc))
2127 return setError(E_FAIL,
2128 tr("Invalid snapshot folder '%ls' (%Rrc)"),
2129 aSnapshotFolder, vrc);
2130
2131 setModified(IsModified_MachineData);
2132 mUserData.backup();
2133
2134 copyPathRelativeToMachine(strSnapshotFolder, mUserData->s.strSnapshotFolder);
2135
2136 return S_OK;
2137}
2138
2139STDMETHODIMP Machine::COMGETTER(MediumAttachments)(ComSafeArrayOut(IMediumAttachment*, aAttachments))
2140{
2141 if (ComSafeArrayOutIsNull(aAttachments))
2142 return E_POINTER;
2143
2144 AutoCaller autoCaller(this);
2145 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2146
2147 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2148
2149 SafeIfaceArray<IMediumAttachment> attachments(mMediaData->mAttachments);
2150 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
2151
2152 return S_OK;
2153}
2154
2155STDMETHODIMP Machine::COMGETTER(VRDEServer)(IVRDEServer **vrdeServer)
2156{
2157 if (!vrdeServer)
2158 return E_POINTER;
2159
2160 AutoCaller autoCaller(this);
2161 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2162
2163 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2164
2165 Assert(!!mVRDEServer);
2166 mVRDEServer.queryInterfaceTo(vrdeServer);
2167
2168 return S_OK;
2169}
2170
2171STDMETHODIMP Machine::COMGETTER(AudioAdapter)(IAudioAdapter **audioAdapter)
2172{
2173 if (!audioAdapter)
2174 return E_POINTER;
2175
2176 AutoCaller autoCaller(this);
2177 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2178
2179 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2180
2181 mAudioAdapter.queryInterfaceTo(audioAdapter);
2182 return S_OK;
2183}
2184
2185STDMETHODIMP Machine::COMGETTER(USBController)(IUSBController **aUSBController)
2186{
2187#ifdef VBOX_WITH_VUSB
2188 CheckComArgOutPointerValid(aUSBController);
2189
2190 AutoCaller autoCaller(this);
2191 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2192 MultiResult rc(S_OK);
2193
2194# ifdef VBOX_WITH_USB
2195 rc = mParent->host()->checkUSBProxyService();
2196 if (FAILED(rc)) return rc;
2197# endif
2198
2199 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2200
2201 return rc = mUSBController.queryInterfaceTo(aUSBController);
2202#else
2203 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2204 * extended error info to indicate that USB is simply not available
2205 * (w/o treating it as a failure), for example, as in OSE */
2206 NOREF(aUSBController);
2207 ReturnComNotImplemented();
2208#endif /* VBOX_WITH_VUSB */
2209}
2210
2211STDMETHODIMP Machine::COMGETTER(SettingsFilePath)(BSTR *aFilePath)
2212{
2213 CheckComArgOutPointerValid(aFilePath);
2214
2215 AutoLimitedCaller autoCaller(this);
2216 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2217
2218 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2219
2220 mData->m_strConfigFileFull.cloneTo(aFilePath);
2221 return S_OK;
2222}
2223
2224STDMETHODIMP Machine::COMGETTER(SettingsModified)(BOOL *aModified)
2225{
2226 CheckComArgOutPointerValid(aModified);
2227
2228 AutoCaller autoCaller(this);
2229 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2230
2231 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2232
2233 HRESULT rc = checkStateDependency(MutableStateDep);
2234 if (FAILED(rc)) return rc;
2235
2236 if (!mData->pMachineConfigFile->fileExists())
2237 // this is a new machine, and no config file exists yet:
2238 *aModified = TRUE;
2239 else
2240 *aModified = (mData->flModifications != 0);
2241
2242 return S_OK;
2243}
2244
2245STDMETHODIMP Machine::COMGETTER(SessionState)(SessionState_T *aSessionState)
2246{
2247 CheckComArgOutPointerValid(aSessionState);
2248
2249 AutoCaller autoCaller(this);
2250 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2251
2252 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2253
2254 *aSessionState = mData->mSession.mState;
2255
2256 return S_OK;
2257}
2258
2259STDMETHODIMP Machine::COMGETTER(SessionType)(BSTR *aSessionType)
2260{
2261 CheckComArgOutPointerValid(aSessionType);
2262
2263 AutoCaller autoCaller(this);
2264 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2265
2266 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2267
2268 mData->mSession.mType.cloneTo(aSessionType);
2269
2270 return S_OK;
2271}
2272
2273STDMETHODIMP Machine::COMGETTER(SessionPid)(ULONG *aSessionPid)
2274{
2275 CheckComArgOutPointerValid(aSessionPid);
2276
2277 AutoCaller autoCaller(this);
2278 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2279
2280 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2281
2282 *aSessionPid = mData->mSession.mPid;
2283
2284 return S_OK;
2285}
2286
2287STDMETHODIMP Machine::COMGETTER(State)(MachineState_T *machineState)
2288{
2289 if (!machineState)
2290 return E_POINTER;
2291
2292 AutoCaller autoCaller(this);
2293 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2294
2295 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2296
2297 *machineState = mData->mMachineState;
2298
2299 return S_OK;
2300}
2301
2302STDMETHODIMP Machine::COMGETTER(LastStateChange)(LONG64 *aLastStateChange)
2303{
2304 CheckComArgOutPointerValid(aLastStateChange);
2305
2306 AutoCaller autoCaller(this);
2307 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2308
2309 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2310
2311 *aLastStateChange = RTTimeSpecGetMilli(&mData->mLastStateChange);
2312
2313 return S_OK;
2314}
2315
2316STDMETHODIMP Machine::COMGETTER(StateFilePath)(BSTR *aStateFilePath)
2317{
2318 CheckComArgOutPointerValid(aStateFilePath);
2319
2320 AutoCaller autoCaller(this);
2321 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2322
2323 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2324
2325 mSSData->mStateFilePath.cloneTo(aStateFilePath);
2326
2327 return S_OK;
2328}
2329
2330STDMETHODIMP Machine::COMGETTER(LogFolder)(BSTR *aLogFolder)
2331{
2332 CheckComArgOutPointerValid(aLogFolder);
2333
2334 AutoCaller autoCaller(this);
2335 AssertComRCReturnRC(autoCaller.rc());
2336
2337 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2338
2339 Utf8Str logFolder;
2340 getLogFolder(logFolder);
2341 logFolder.cloneTo(aLogFolder);
2342
2343 return S_OK;
2344}
2345
2346STDMETHODIMP Machine::COMGETTER(CurrentSnapshot) (ISnapshot **aCurrentSnapshot)
2347{
2348 CheckComArgOutPointerValid(aCurrentSnapshot);
2349
2350 AutoCaller autoCaller(this);
2351 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2352
2353 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2354
2355 mData->mCurrentSnapshot.queryInterfaceTo(aCurrentSnapshot);
2356
2357 return S_OK;
2358}
2359
2360STDMETHODIMP Machine::COMGETTER(SnapshotCount)(ULONG *aSnapshotCount)
2361{
2362 CheckComArgOutPointerValid(aSnapshotCount);
2363
2364 AutoCaller autoCaller(this);
2365 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2366
2367 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2368
2369 *aSnapshotCount = mData->mFirstSnapshot.isNull()
2370 ? 0
2371 : mData->mFirstSnapshot->getAllChildrenCount() + 1;
2372
2373 return S_OK;
2374}
2375
2376STDMETHODIMP Machine::COMGETTER(CurrentStateModified)(BOOL *aCurrentStateModified)
2377{
2378 CheckComArgOutPointerValid(aCurrentStateModified);
2379
2380 AutoCaller autoCaller(this);
2381 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2382
2383 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2384
2385 /* Note: for machines with no snapshots, we always return FALSE
2386 * (mData->mCurrentStateModified will be TRUE in this case, for historical
2387 * reasons :) */
2388
2389 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
2390 ? FALSE
2391 : mData->mCurrentStateModified;
2392
2393 return S_OK;
2394}
2395
2396STDMETHODIMP Machine::COMGETTER(SharedFolders)(ComSafeArrayOut(ISharedFolder *, aSharedFolders))
2397{
2398 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
2399
2400 AutoCaller autoCaller(this);
2401 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2402
2403 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2404
2405 SafeIfaceArray<ISharedFolder> folders(mHWData->mSharedFolders);
2406 folders.detachTo(ComSafeArrayOutArg(aSharedFolders));
2407
2408 return S_OK;
2409}
2410
2411STDMETHODIMP Machine::COMGETTER(ClipboardMode)(ClipboardMode_T *aClipboardMode)
2412{
2413 CheckComArgOutPointerValid(aClipboardMode);
2414
2415 AutoCaller autoCaller(this);
2416 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2417
2418 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2419
2420 *aClipboardMode = mHWData->mClipboardMode;
2421
2422 return S_OK;
2423}
2424
2425STDMETHODIMP
2426Machine::COMSETTER(ClipboardMode)(ClipboardMode_T aClipboardMode)
2427{
2428 AutoCaller autoCaller(this);
2429 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2430
2431 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2432
2433 HRESULT rc = checkStateDependency(MutableStateDep);
2434 if (FAILED(rc)) return rc;
2435
2436 setModified(IsModified_MachineData);
2437 mHWData.backup();
2438 mHWData->mClipboardMode = aClipboardMode;
2439
2440 return S_OK;
2441}
2442
2443STDMETHODIMP
2444Machine::COMGETTER(GuestPropertyNotificationPatterns)(BSTR *aPatterns)
2445{
2446 CheckComArgOutPointerValid(aPatterns);
2447
2448 AutoCaller autoCaller(this);
2449 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2450
2451 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2452
2453 try
2454 {
2455 mHWData->mGuestPropertyNotificationPatterns.cloneTo(aPatterns);
2456 }
2457 catch (...)
2458 {
2459 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
2460 }
2461
2462 return S_OK;
2463}
2464
2465STDMETHODIMP
2466Machine::COMSETTER(GuestPropertyNotificationPatterns)(IN_BSTR aPatterns)
2467{
2468 AutoCaller autoCaller(this);
2469 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2470
2471 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2472
2473 HRESULT rc = checkStateDependency(MutableStateDep);
2474 if (FAILED(rc)) return rc;
2475
2476 setModified(IsModified_MachineData);
2477 mHWData.backup();
2478 mHWData->mGuestPropertyNotificationPatterns = aPatterns;
2479 return rc;
2480}
2481
2482STDMETHODIMP
2483Machine::COMGETTER(StorageControllers)(ComSafeArrayOut(IStorageController *, aStorageControllers))
2484{
2485 CheckComArgOutSafeArrayPointerValid(aStorageControllers);
2486
2487 AutoCaller autoCaller(this);
2488 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2489
2490 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2491
2492 SafeIfaceArray<IStorageController> ctrls(*mStorageControllers.data());
2493 ctrls.detachTo(ComSafeArrayOutArg(aStorageControllers));
2494
2495 return S_OK;
2496}
2497
2498STDMETHODIMP
2499Machine::COMGETTER(TeleporterEnabled)(BOOL *aEnabled)
2500{
2501 CheckComArgOutPointerValid(aEnabled);
2502
2503 AutoCaller autoCaller(this);
2504 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2505
2506 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2507
2508 *aEnabled = mUserData->s.fTeleporterEnabled;
2509
2510 return S_OK;
2511}
2512
2513STDMETHODIMP Machine::COMSETTER(TeleporterEnabled)(BOOL aEnabled)
2514{
2515 AutoCaller autoCaller(this);
2516 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2517
2518 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2519
2520 /* Only allow it to be set to true when PoweredOff or Aborted.
2521 (Clearing it is always permitted.) */
2522 if ( aEnabled
2523 && mData->mRegistered
2524 && ( !isSessionMachine()
2525 || ( mData->mMachineState != MachineState_PoweredOff
2526 && mData->mMachineState != MachineState_Teleported
2527 && mData->mMachineState != MachineState_Aborted
2528 )
2529 )
2530 )
2531 return setError(VBOX_E_INVALID_VM_STATE,
2532 tr("The machine is not powered off (state is %s)"),
2533 Global::stringifyMachineState(mData->mMachineState));
2534
2535 setModified(IsModified_MachineData);
2536 mUserData.backup();
2537 mUserData->s.fTeleporterEnabled = !!aEnabled;
2538
2539 return S_OK;
2540}
2541
2542STDMETHODIMP Machine::COMGETTER(TeleporterPort)(ULONG *aPort)
2543{
2544 CheckComArgOutPointerValid(aPort);
2545
2546 AutoCaller autoCaller(this);
2547 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2548
2549 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2550
2551 *aPort = (ULONG)mUserData->s.uTeleporterPort;
2552
2553 return S_OK;
2554}
2555
2556STDMETHODIMP Machine::COMSETTER(TeleporterPort)(ULONG aPort)
2557{
2558 if (aPort >= _64K)
2559 return setError(E_INVALIDARG, tr("Invalid port number %d"), aPort);
2560
2561 AutoCaller autoCaller(this);
2562 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2563
2564 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2565
2566 HRESULT rc = checkStateDependency(MutableStateDep);
2567 if (FAILED(rc)) return rc;
2568
2569 setModified(IsModified_MachineData);
2570 mUserData.backup();
2571 mUserData->s.uTeleporterPort = (uint32_t)aPort;
2572
2573 return S_OK;
2574}
2575
2576STDMETHODIMP Machine::COMGETTER(TeleporterAddress)(BSTR *aAddress)
2577{
2578 CheckComArgOutPointerValid(aAddress);
2579
2580 AutoCaller autoCaller(this);
2581 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2582
2583 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2584
2585 mUserData->s.strTeleporterAddress.cloneTo(aAddress);
2586
2587 return S_OK;
2588}
2589
2590STDMETHODIMP Machine::COMSETTER(TeleporterAddress)(IN_BSTR aAddress)
2591{
2592 AutoCaller autoCaller(this);
2593 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2594
2595 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2596
2597 HRESULT rc = checkStateDependency(MutableStateDep);
2598 if (FAILED(rc)) return rc;
2599
2600 setModified(IsModified_MachineData);
2601 mUserData.backup();
2602 mUserData->s.strTeleporterAddress = aAddress;
2603
2604 return S_OK;
2605}
2606
2607STDMETHODIMP Machine::COMGETTER(TeleporterPassword)(BSTR *aPassword)
2608{
2609 CheckComArgOutPointerValid(aPassword);
2610
2611 AutoCaller autoCaller(this);
2612 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2613
2614 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2615
2616 mUserData->s.strTeleporterPassword.cloneTo(aPassword);
2617
2618 return S_OK;
2619}
2620
2621STDMETHODIMP Machine::COMSETTER(TeleporterPassword)(IN_BSTR aPassword)
2622{
2623 AutoCaller autoCaller(this);
2624 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2625
2626 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2627
2628 HRESULT rc = checkStateDependency(MutableStateDep);
2629 if (FAILED(rc)) return rc;
2630
2631 setModified(IsModified_MachineData);
2632 mUserData.backup();
2633 mUserData->s.strTeleporterPassword = aPassword;
2634
2635 return S_OK;
2636}
2637
2638STDMETHODIMP Machine::COMGETTER(FaultToleranceState)(FaultToleranceState_T *aState)
2639{
2640 CheckComArgOutPointerValid(aState);
2641
2642 AutoCaller autoCaller(this);
2643 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2644
2645 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2646
2647 *aState = mUserData->s.enmFaultToleranceState;
2648 return S_OK;
2649}
2650
2651STDMETHODIMP Machine::COMSETTER(FaultToleranceState)(FaultToleranceState_T aState)
2652{
2653 AutoCaller autoCaller(this);
2654 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2655
2656 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2657
2658 /* @todo deal with running state change. */
2659 HRESULT rc = checkStateDependency(MutableStateDep);
2660 if (FAILED(rc)) return rc;
2661
2662 setModified(IsModified_MachineData);
2663 mUserData.backup();
2664 mUserData->s.enmFaultToleranceState = aState;
2665 return S_OK;
2666}
2667
2668STDMETHODIMP Machine::COMGETTER(FaultToleranceAddress)(BSTR *aAddress)
2669{
2670 CheckComArgOutPointerValid(aAddress);
2671
2672 AutoCaller autoCaller(this);
2673 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2674
2675 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2676
2677 mUserData->s.strFaultToleranceAddress.cloneTo(aAddress);
2678 return S_OK;
2679}
2680
2681STDMETHODIMP Machine::COMSETTER(FaultToleranceAddress)(IN_BSTR aAddress)
2682{
2683 AutoCaller autoCaller(this);
2684 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2685
2686 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2687
2688 /* @todo deal with running state change. */
2689 HRESULT rc = checkStateDependency(MutableStateDep);
2690 if (FAILED(rc)) return rc;
2691
2692 setModified(IsModified_MachineData);
2693 mUserData.backup();
2694 mUserData->s.strFaultToleranceAddress = aAddress;
2695 return S_OK;
2696}
2697
2698STDMETHODIMP Machine::COMGETTER(FaultTolerancePort)(ULONG *aPort)
2699{
2700 CheckComArgOutPointerValid(aPort);
2701
2702 AutoCaller autoCaller(this);
2703 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2704
2705 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2706
2707 *aPort = mUserData->s.uFaultTolerancePort;
2708 return S_OK;
2709}
2710
2711STDMETHODIMP Machine::COMSETTER(FaultTolerancePort)(ULONG aPort)
2712{
2713 AutoCaller autoCaller(this);
2714 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2715
2716 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2717
2718 /* @todo deal with running state change. */
2719 HRESULT rc = checkStateDependency(MutableStateDep);
2720 if (FAILED(rc)) return rc;
2721
2722 setModified(IsModified_MachineData);
2723 mUserData.backup();
2724 mUserData->s.uFaultTolerancePort = aPort;
2725 return S_OK;
2726}
2727
2728STDMETHODIMP Machine::COMGETTER(FaultTolerancePassword)(BSTR *aPassword)
2729{
2730 CheckComArgOutPointerValid(aPassword);
2731
2732 AutoCaller autoCaller(this);
2733 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2734
2735 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2736
2737 mUserData->s.strFaultTolerancePassword.cloneTo(aPassword);
2738
2739 return S_OK;
2740}
2741
2742STDMETHODIMP Machine::COMSETTER(FaultTolerancePassword)(IN_BSTR aPassword)
2743{
2744 AutoCaller autoCaller(this);
2745 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2746
2747 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2748
2749 /* @todo deal with running state change. */
2750 HRESULT rc = checkStateDependency(MutableStateDep);
2751 if (FAILED(rc)) return rc;
2752
2753 setModified(IsModified_MachineData);
2754 mUserData.backup();
2755 mUserData->s.strFaultTolerancePassword = aPassword;
2756
2757 return S_OK;
2758}
2759
2760STDMETHODIMP Machine::COMGETTER(FaultToleranceSyncInterval)(ULONG *aInterval)
2761{
2762 CheckComArgOutPointerValid(aInterval);
2763
2764 AutoCaller autoCaller(this);
2765 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2766
2767 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2768
2769 *aInterval = mUserData->s.uFaultToleranceInterval;
2770 return S_OK;
2771}
2772
2773STDMETHODIMP Machine::COMSETTER(FaultToleranceSyncInterval)(ULONG aInterval)
2774{
2775 AutoCaller autoCaller(this);
2776 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2777
2778 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2779
2780 /* @todo deal with running state change. */
2781 HRESULT rc = checkStateDependency(MutableStateDep);
2782 if (FAILED(rc)) return rc;
2783
2784 setModified(IsModified_MachineData);
2785 mUserData.backup();
2786 mUserData->s.uFaultToleranceInterval = aInterval;
2787 return S_OK;
2788}
2789
2790STDMETHODIMP Machine::COMGETTER(RTCUseUTC)(BOOL *aEnabled)
2791{
2792 CheckComArgOutPointerValid(aEnabled);
2793
2794 AutoCaller autoCaller(this);
2795 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2796
2797 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2798
2799 *aEnabled = mUserData->s.fRTCUseUTC;
2800
2801 return S_OK;
2802}
2803
2804STDMETHODIMP Machine::COMSETTER(RTCUseUTC)(BOOL aEnabled)
2805{
2806 AutoCaller autoCaller(this);
2807 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2808
2809 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2810
2811 /* Only allow it to be set to true when PoweredOff or Aborted.
2812 (Clearing it is always permitted.) */
2813 if ( aEnabled
2814 && mData->mRegistered
2815 && ( !isSessionMachine()
2816 || ( mData->mMachineState != MachineState_PoweredOff
2817 && mData->mMachineState != MachineState_Teleported
2818 && mData->mMachineState != MachineState_Aborted
2819 )
2820 )
2821 )
2822 return setError(VBOX_E_INVALID_VM_STATE,
2823 tr("The machine is not powered off (state is %s)"),
2824 Global::stringifyMachineState(mData->mMachineState));
2825
2826 setModified(IsModified_MachineData);
2827 mUserData.backup();
2828 mUserData->s.fRTCUseUTC = !!aEnabled;
2829
2830 return S_OK;
2831}
2832
2833STDMETHODIMP Machine::COMGETTER(IoCacheEnabled)(BOOL *aEnabled)
2834{
2835 CheckComArgOutPointerValid(aEnabled);
2836
2837 AutoCaller autoCaller(this);
2838 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2839
2840 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2841
2842 *aEnabled = mHWData->mIoCacheEnabled;
2843
2844 return S_OK;
2845}
2846
2847STDMETHODIMP Machine::COMSETTER(IoCacheEnabled)(BOOL aEnabled)
2848{
2849 AutoCaller autoCaller(this);
2850 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2851
2852 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2853
2854 HRESULT rc = checkStateDependency(MutableStateDep);
2855 if (FAILED(rc)) return rc;
2856
2857 setModified(IsModified_MachineData);
2858 mHWData.backup();
2859 mHWData->mIoCacheEnabled = aEnabled;
2860
2861 return S_OK;
2862}
2863
2864STDMETHODIMP Machine::COMGETTER(IoCacheSize)(ULONG *aIoCacheSize)
2865{
2866 CheckComArgOutPointerValid(aIoCacheSize);
2867
2868 AutoCaller autoCaller(this);
2869 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2870
2871 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2872
2873 *aIoCacheSize = mHWData->mIoCacheSize;
2874
2875 return S_OK;
2876}
2877
2878STDMETHODIMP Machine::COMSETTER(IoCacheSize)(ULONG aIoCacheSize)
2879{
2880 AutoCaller autoCaller(this);
2881 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2882
2883 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2884
2885 HRESULT rc = checkStateDependency(MutableStateDep);
2886 if (FAILED(rc)) return rc;
2887
2888 setModified(IsModified_MachineData);
2889 mHWData.backup();
2890 mHWData->mIoCacheSize = aIoCacheSize;
2891
2892 return S_OK;
2893}
2894
2895
2896/**
2897 * @note Locks objects!
2898 */
2899STDMETHODIMP Machine::LockMachine(ISession *aSession,
2900 LockType_T lockType)
2901{
2902 CheckComArgNotNull(aSession);
2903
2904 AutoCaller autoCaller(this);
2905 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2906
2907 /* check the session state */
2908 SessionState_T state;
2909 HRESULT rc = aSession->COMGETTER(State)(&state);
2910 if (FAILED(rc)) return rc;
2911
2912 if (state != SessionState_Unlocked)
2913 return setError(VBOX_E_INVALID_OBJECT_STATE,
2914 tr("The given session is busy"));
2915
2916 // get the client's IInternalSessionControl interface
2917 ComPtr<IInternalSessionControl> pSessionControl = aSession;
2918 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
2919 E_INVALIDARG);
2920
2921 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2922
2923 if (!mData->mRegistered)
2924 return setError(E_UNEXPECTED,
2925 tr("The machine '%s' is not registered"),
2926 mUserData->s.strName.c_str());
2927
2928 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
2929
2930 SessionState_T oldState = mData->mSession.mState;
2931 /* Hack: in case the session is closing and there is a progress object
2932 * which allows waiting for the session to be closed, take the opportunity
2933 * and do a limited wait (max. 1 second). This helps a lot when the system
2934 * is busy and thus session closing can take a little while. */
2935 if ( mData->mSession.mState == SessionState_Unlocking
2936 && mData->mSession.mProgress)
2937 {
2938 alock.release();
2939 mData->mSession.mProgress->WaitForCompletion(1000);
2940 alock.acquire();
2941 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
2942 }
2943
2944 // try again now
2945 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already (i.e. session machine exists)
2946 && (lockType == LockType_Shared) // caller wants a shared link to the existing session that holds the write lock:
2947 )
2948 {
2949 // OK, share the session... we are now dealing with three processes:
2950 // 1) VBoxSVC (where this code runs);
2951 // 2) process C: the caller's client process (who wants a shared session);
2952 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
2953
2954 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
2955 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
2956 ComAssertRet(!pSessionW.isNull(), E_FAIL);
2957 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
2958 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
2959
2960 /*
2961 * Leave the lock before calling the client process. It's safe here
2962 * since the only thing to do after we get the lock again is to add
2963 * the remote control to the list (which doesn't directly influence
2964 * anything).
2965 */
2966 alock.leave();
2967
2968 // get the console of the session holding the write lock (this is a remote call)
2969 ComPtr<IConsole> pConsoleW;
2970 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
2971 rc = pSessionW->GetRemoteConsole(pConsoleW.asOutParam());
2972 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
2973 if (FAILED(rc))
2974 // the failure may occur w/o any error info (from RPC), so provide one
2975 return setError(VBOX_E_VM_ERROR,
2976 tr("Failed to get a console object from the direct session (%Rrc)"), rc);
2977
2978 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
2979
2980 // share the session machine and W's console with the caller's session
2981 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
2982 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
2983 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
2984
2985 if (FAILED(rc))
2986 // the failure may occur w/o any error info (from RPC), so provide one
2987 return setError(VBOX_E_VM_ERROR,
2988 tr("Failed to assign the machine to the session (%Rrc)"), rc);
2989 alock.enter();
2990
2991 // need to revalidate the state after entering the lock again
2992 if (mData->mSession.mState != SessionState_Locked)
2993 {
2994 pSessionControl->Uninitialize();
2995 return setError(VBOX_E_INVALID_SESSION_STATE,
2996 tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
2997 mUserData->s.strName.c_str());
2998 }
2999
3000 // add the caller's session to the list
3001 mData->mSession.mRemoteControls.push_back(pSessionControl);
3002 }
3003 else if ( mData->mSession.mState == SessionState_Locked
3004 || mData->mSession.mState == SessionState_Unlocking
3005 )
3006 {
3007 // sharing not permitted, or machine still unlocking:
3008 return setError(VBOX_E_INVALID_OBJECT_STATE,
3009 tr("The machine '%s' is already locked for a session (or being unlocked)"),
3010 mUserData->s.strName.c_str());
3011 }
3012 else
3013 {
3014 // machine is not locked: then write-lock the machine (create the session machine)
3015
3016 // must not be busy
3017 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
3018
3019 // get the caller's session PID
3020 RTPROCESS pid = NIL_RTPROCESS;
3021 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
3022 pSessionControl->GetPID((ULONG*)&pid);
3023 Assert(pid != NIL_RTPROCESS);
3024
3025 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
3026
3027 if (fLaunchingVMProcess)
3028 {
3029 // this machine is awaiting for a spawning session to be opened:
3030 // then the calling process must be the one that got started by
3031 // launchVMProcess()
3032
3033 LogFlowThisFunc(("mSession.mPid=%d(0x%x)\n", mData->mSession.mPid, mData->mSession.mPid));
3034 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3035
3036 if (mData->mSession.mPid != pid)
3037 return setError(E_ACCESSDENIED,
3038 tr("An unexpected process (PID=0x%08X) has tried to lock the "
3039 "machine '%s', while only the process started by launchVMProcess (PID=0x%08X) is allowed"),
3040 pid, mUserData->s.strName.c_str(), mData->mSession.mPid);
3041 }
3042
3043 // create the mutable SessionMachine from the current machine
3044 ComObjPtr<SessionMachine> sessionMachine;
3045 sessionMachine.createObject();
3046 rc = sessionMachine->init(this);
3047 AssertComRC(rc);
3048
3049 /* NOTE: doing return from this function after this point but
3050 * before the end is forbidden since it may call SessionMachine::uninit()
3051 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3052 * lock while still holding the Machine lock in alock so that a deadlock
3053 * is possible due to the wrong lock order. */
3054
3055 if (SUCCEEDED(rc))
3056 {
3057 /*
3058 * Set the session state to Spawning to protect against subsequent
3059 * attempts to open a session and to unregister the machine after
3060 * we leave the lock.
3061 */
3062 SessionState_T origState = mData->mSession.mState;
3063 mData->mSession.mState = SessionState_Spawning;
3064
3065 /*
3066 * Leave the lock before calling the client process -- it will call
3067 * Machine/SessionMachine methods. Leaving the lock here is quite safe
3068 * because the state is Spawning, so that openRemotesession() and
3069 * openExistingSession() calls will fail. This method, called before we
3070 * enter the lock again, will fail because of the wrong PID.
3071 *
3072 * Note that mData->mSession.mRemoteControls accessed outside
3073 * the lock may not be modified when state is Spawning, so it's safe.
3074 */
3075 alock.leave();
3076
3077 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3078 rc = pSessionControl->AssignMachine(sessionMachine);
3079 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3080
3081 /* The failure may occur w/o any error info (from RPC), so provide one */
3082 if (FAILED(rc))
3083 setError(VBOX_E_VM_ERROR,
3084 tr("Failed to assign the machine to the session (%Rrc)"), rc);
3085
3086 if ( SUCCEEDED(rc)
3087 && fLaunchingVMProcess
3088 )
3089 {
3090 /* complete the remote session initialization */
3091
3092 /* get the console from the direct session */
3093 ComPtr<IConsole> console;
3094 rc = pSessionControl->GetRemoteConsole(console.asOutParam());
3095 ComAssertComRC(rc);
3096
3097 if (SUCCEEDED(rc) && !console)
3098 {
3099 ComAssert(!!console);
3100 rc = E_FAIL;
3101 }
3102
3103 /* assign machine & console to the remote session */
3104 if (SUCCEEDED(rc))
3105 {
3106 /*
3107 * after openRemoteSession(), the first and the only
3108 * entry in remoteControls is that remote session
3109 */
3110 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3111 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
3112 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3113
3114 /* The failure may occur w/o any error info (from RPC), so provide one */
3115 if (FAILED(rc))
3116 setError(VBOX_E_VM_ERROR,
3117 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
3118 }
3119
3120 if (FAILED(rc))
3121 pSessionControl->Uninitialize();
3122 }
3123
3124 /* enter the lock again */
3125 alock.enter();
3126
3127 /* Restore the session state */
3128 mData->mSession.mState = origState;
3129 }
3130
3131 // finalize spawning anyway (this is why we don't return on errors above)
3132 if (fLaunchingVMProcess)
3133 {
3134 /* Note that the progress object is finalized later */
3135 /** @todo Consider checking mData->mSession.mProgress for cancellation
3136 * around here. */
3137
3138 /* We don't reset mSession.mPid here because it is necessary for
3139 * SessionMachine::uninit() to reap the child process later. */
3140
3141 if (FAILED(rc))
3142 {
3143 /* Close the remote session, remove the remote control from the list
3144 * and reset session state to Closed (@note keep the code in sync
3145 * with the relevant part in openSession()). */
3146
3147 Assert(mData->mSession.mRemoteControls.size() == 1);
3148 if (mData->mSession.mRemoteControls.size() == 1)
3149 {
3150 ErrorInfoKeeper eik;
3151 mData->mSession.mRemoteControls.front()->Uninitialize();
3152 }
3153
3154 mData->mSession.mRemoteControls.clear();
3155 mData->mSession.mState = SessionState_Unlocked;
3156 }
3157 }
3158 else
3159 {
3160 /* memorize PID of the directly opened session */
3161 if (SUCCEEDED(rc))
3162 mData->mSession.mPid = pid;
3163 }
3164
3165 if (SUCCEEDED(rc))
3166 {
3167 /* memorize the direct session control and cache IUnknown for it */
3168 mData->mSession.mDirectControl = pSessionControl;
3169 mData->mSession.mState = SessionState_Locked;
3170 /* associate the SessionMachine with this Machine */
3171 mData->mSession.mMachine = sessionMachine;
3172
3173 /* request an IUnknown pointer early from the remote party for later
3174 * identity checks (it will be internally cached within mDirectControl
3175 * at least on XPCOM) */
3176 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3177 NOREF(unk);
3178 }
3179
3180 /* Leave the lock since SessionMachine::uninit() locks VirtualBox which
3181 * would break the lock order */
3182 alock.leave();
3183
3184 /* uninitialize the created session machine on failure */
3185 if (FAILED(rc))
3186 sessionMachine->uninit();
3187
3188 }
3189
3190 if (SUCCEEDED(rc))
3191 {
3192 /*
3193 * tell the client watcher thread to update the set of
3194 * machines that have open sessions
3195 */
3196 mParent->updateClientWatcher();
3197
3198 if (oldState != SessionState_Locked)
3199 /* fire an event */
3200 mParent->onSessionStateChange(getId(), SessionState_Locked);
3201 }
3202
3203 return rc;
3204}
3205
3206/**
3207 * @note Locks objects!
3208 */
3209STDMETHODIMP Machine::LaunchVMProcess(ISession *aSession,
3210 IN_BSTR aType,
3211 IN_BSTR aEnvironment,
3212 IProgress **aProgress)
3213{
3214 CheckComArgNotNull(aSession);
3215 CheckComArgStrNotEmptyOrNull(aType);
3216 CheckComArgOutPointerValid(aProgress);
3217
3218 AutoCaller autoCaller(this);
3219 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3220
3221 /* check the session state */
3222 SessionState_T state;
3223 HRESULT rc = aSession->COMGETTER(State)(&state);
3224 if (FAILED(rc)) return rc;
3225
3226 if (state != SessionState_Unlocked)
3227 return setError(VBOX_E_INVALID_OBJECT_STATE,
3228 tr("The given session is busy"));
3229
3230 /* get the IInternalSessionControl interface */
3231 ComPtr<IInternalSessionControl> control = aSession;
3232 ComAssertMsgRet(!!control, ("No IInternalSessionControl interface"),
3233 E_INVALIDARG);
3234
3235 /* get the teleporter enable state for the progress object init. */
3236 BOOL fTeleporterEnabled;
3237 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3238 if (FAILED(rc))
3239 return rc;
3240
3241 /* create a progress object */
3242 ComObjPtr<ProgressProxy> progress;
3243 progress.createObject();
3244 rc = progress->init(mParent,
3245 static_cast<IMachine*>(this),
3246 Bstr(tr("Spawning session")).raw(),
3247 TRUE /* aCancelable */,
3248 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3249 Bstr(tr("Spawning session")).raw(),
3250 2 /* uFirstOperationWeight */,
3251 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3252 if (SUCCEEDED(rc))
3253 {
3254 rc = openRemoteSession(control, aType, aEnvironment, progress);
3255 if (SUCCEEDED(rc))
3256 {
3257 progress.queryInterfaceTo(aProgress);
3258
3259 /* signal the client watcher thread */
3260 mParent->updateClientWatcher();
3261
3262 /* fire an event */
3263 mParent->onSessionStateChange(getId(), SessionState_Spawning);
3264 }
3265 }
3266
3267 return rc;
3268}
3269
3270STDMETHODIMP Machine::SetBootOrder(ULONG aPosition, DeviceType_T aDevice)
3271{
3272 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3273 return setError(E_INVALIDARG,
3274 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3275 aPosition, SchemaDefs::MaxBootPosition);
3276
3277 if (aDevice == DeviceType_USB)
3278 return setError(E_NOTIMPL,
3279 tr("Booting from USB device is currently not supported"));
3280
3281 AutoCaller autoCaller(this);
3282 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3283
3284 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3285
3286 HRESULT rc = checkStateDependency(MutableStateDep);
3287 if (FAILED(rc)) return rc;
3288
3289 setModified(IsModified_MachineData);
3290 mHWData.backup();
3291 mHWData->mBootOrder[aPosition - 1] = aDevice;
3292
3293 return S_OK;
3294}
3295
3296STDMETHODIMP Machine::GetBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3297{
3298 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3299 return setError(E_INVALIDARG,
3300 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3301 aPosition, SchemaDefs::MaxBootPosition);
3302
3303 AutoCaller autoCaller(this);
3304 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3305
3306 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3307
3308 *aDevice = mHWData->mBootOrder[aPosition - 1];
3309
3310 return S_OK;
3311}
3312
3313STDMETHODIMP Machine::AttachDevice(IN_BSTR aControllerName,
3314 LONG aControllerPort,
3315 LONG aDevice,
3316 DeviceType_T aType,
3317 IMedium *aMedium)
3318{
3319 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aType=%d aId=\"%ls\"\n",
3320 aControllerName, aControllerPort, aDevice, aType, aMedium));
3321
3322 CheckComArgStrNotEmptyOrNull(aControllerName);
3323
3324 AutoCaller autoCaller(this);
3325 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3326
3327 // request the host lock first, since might be calling Host methods for getting host drives;
3328 // next, protect the media tree all the while we're in here, as well as our member variables
3329 AutoMultiWriteLock2 alock(mParent->host()->lockHandle(),
3330 this->lockHandle() COMMA_LOCKVAL_SRC_POS);
3331 AutoWriteLock treeLock(&mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3332
3333 HRESULT rc = checkStateDependency(MutableStateDep);
3334 if (FAILED(rc)) return rc;
3335
3336 GuidList llRegistriesThatNeedSaving;
3337
3338 /// @todo NEWMEDIA implicit machine registration
3339 if (!mData->mRegistered)
3340 return setError(VBOX_E_INVALID_OBJECT_STATE,
3341 tr("Cannot attach storage devices to an unregistered machine"));
3342
3343 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3344
3345 if (Global::IsOnlineOrTransient(mData->mMachineState))
3346 return setError(VBOX_E_INVALID_VM_STATE,
3347 tr("Invalid machine state: %s"),
3348 Global::stringifyMachineState(mData->mMachineState));
3349
3350 /* Check for an existing controller. */
3351 ComObjPtr<StorageController> ctl;
3352 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
3353 if (FAILED(rc)) return rc;
3354
3355 // check that the port and device are not out of range
3356 rc = ctl->checkPortAndDeviceValid(aControllerPort, aDevice);
3357 if (FAILED(rc)) return rc;
3358
3359 /* check if the device slot is already busy */
3360 MediumAttachment *pAttachTemp;
3361 if ((pAttachTemp = findAttachment(mMediaData->mAttachments,
3362 aControllerName,
3363 aControllerPort,
3364 aDevice)))
3365 {
3366 Medium *pMedium = pAttachTemp->getMedium();
3367 if (pMedium)
3368 {
3369 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3370 return setError(VBOX_E_OBJECT_IN_USE,
3371 tr("Medium '%s' is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3372 pMedium->getLocationFull().c_str(),
3373 aControllerPort,
3374 aDevice,
3375 aControllerName);
3376 }
3377 else
3378 return setError(VBOX_E_OBJECT_IN_USE,
3379 tr("Device is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3380 aControllerPort, aDevice, aControllerName);
3381 }
3382
3383 ComObjPtr<Medium> medium = static_cast<Medium*>(aMedium);
3384 if (aMedium && medium.isNull())
3385 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3386
3387 AutoCaller mediumCaller(medium);
3388 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3389
3390 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3391
3392 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
3393 && !medium.isNull()
3394 )
3395 return setError(VBOX_E_OBJECT_IN_USE,
3396 tr("Medium '%s' is already attached to this virtual machine"),
3397 medium->getLocationFull().c_str());
3398
3399 if (!medium.isNull())
3400 {
3401 MediumType_T mtype = medium->getType();
3402 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3403 // For DVDs it's not written to the config file, so needs no global config
3404 // version bump. For floppies it's a new attribute "type", which is ignored
3405 // by older VirtualBox version, so needs no global config version bump either.
3406 // For hard disks this type is not accepted.
3407 if (mtype == MediumType_MultiAttach)
3408 {
3409 // This type is new with VirtualBox 4.0 and therefore requires settings
3410 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3411 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3412 // two reasons: The medium type is a property of the media registry tree, which
3413 // can reside in the global config file (for pre-4.0 media); we would therefore
3414 // possibly need to bump the global config version. We don't want to do that though
3415 // because that might make downgrading to pre-4.0 impossible.
3416 // As a result, we can only use these two new types if the medium is NOT in the
3417 // global registry:
3418 const Guid &uuidGlobalRegistry = mParent->getGlobalRegistryId();
3419 if ( medium->isInRegistry(uuidGlobalRegistry)
3420 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3421 )
3422 return setError(VBOX_E_INVALID_OBJECT_STATE,
3423 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3424 "to machines that were created with VirtualBox 4.0 or later"),
3425 medium->getLocationFull().c_str());
3426 }
3427 }
3428
3429 bool fIndirect = false;
3430 if (!medium.isNull())
3431 fIndirect = medium->isReadOnly();
3432 bool associate = true;
3433
3434 do
3435 {
3436 if ( aType == DeviceType_HardDisk
3437 && mMediaData.isBackedUp())
3438 {
3439 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3440
3441 /* check if the medium was attached to the VM before we started
3442 * changing attachments in which case the attachment just needs to
3443 * be restored */
3444 if ((pAttachTemp = findAttachment(oldAtts, medium)))
3445 {
3446 AssertReturn(!fIndirect, E_FAIL);
3447
3448 /* see if it's the same bus/channel/device */
3449 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
3450 {
3451 /* the simplest case: restore the whole attachment
3452 * and return, nothing else to do */
3453 mMediaData->mAttachments.push_back(pAttachTemp);
3454 return S_OK;
3455 }
3456
3457 /* bus/channel/device differ; we need a new attachment object,
3458 * but don't try to associate it again */
3459 associate = false;
3460 break;
3461 }
3462 }
3463
3464 /* go further only if the attachment is to be indirect */
3465 if (!fIndirect)
3466 break;
3467
3468 /* perform the so called smart attachment logic for indirect
3469 * attachments. Note that smart attachment is only applicable to base
3470 * hard disks. */
3471
3472 if (medium->getParent().isNull())
3473 {
3474 /* first, investigate the backup copy of the current hard disk
3475 * attachments to make it possible to re-attach existing diffs to
3476 * another device slot w/o losing their contents */
3477 if (mMediaData.isBackedUp())
3478 {
3479 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3480
3481 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
3482 uint32_t foundLevel = 0;
3483
3484 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
3485 it != oldAtts.end();
3486 ++it)
3487 {
3488 uint32_t level = 0;
3489 MediumAttachment *pAttach = *it;
3490 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3491 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3492 if (pMedium.isNull())
3493 continue;
3494
3495 if (pMedium->getBase(&level) == medium)
3496 {
3497 /* skip the hard disk if its currently attached (we
3498 * cannot attach the same hard disk twice) */
3499 if (findAttachment(mMediaData->mAttachments,
3500 pMedium))
3501 continue;
3502
3503 /* matched device, channel and bus (i.e. attached to the
3504 * same place) will win and immediately stop the search;
3505 * otherwise the attachment that has the youngest
3506 * descendant of medium will be used
3507 */
3508 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
3509 {
3510 /* the simplest case: restore the whole attachment
3511 * and return, nothing else to do */
3512 mMediaData->mAttachments.push_back(*it);
3513 return S_OK;
3514 }
3515 else if ( foundIt == oldAtts.end()
3516 || level > foundLevel /* prefer younger */
3517 )
3518 {
3519 foundIt = it;
3520 foundLevel = level;
3521 }
3522 }
3523 }
3524
3525 if (foundIt != oldAtts.end())
3526 {
3527 /* use the previously attached hard disk */
3528 medium = (*foundIt)->getMedium();
3529 mediumCaller.attach(medium);
3530 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3531 mediumLock.attach(medium);
3532 /* not implicit, doesn't require association with this VM */
3533 fIndirect = false;
3534 associate = false;
3535 /* go right to the MediumAttachment creation */
3536 break;
3537 }
3538 }
3539
3540 /* must give up the medium lock and medium tree lock as below we
3541 * go over snapshots, which needs a lock with higher lock order. */
3542 mediumLock.release();
3543 treeLock.release();
3544
3545 /* then, search through snapshots for the best diff in the given
3546 * hard disk's chain to base the new diff on */
3547
3548 ComObjPtr<Medium> base;
3549 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
3550 while (snap)
3551 {
3552 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
3553
3554 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
3555
3556 MediumAttachment *pAttachFound = NULL;
3557 uint32_t foundLevel = 0;
3558
3559 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
3560 it != snapAtts.end();
3561 ++it)
3562 {
3563 MediumAttachment *pAttach = *it;
3564 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3565 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3566 if (pMedium.isNull())
3567 continue;
3568
3569 uint32_t level = 0;
3570 if (pMedium->getBase(&level) == medium)
3571 {
3572 /* matched device, channel and bus (i.e. attached to the
3573 * same place) will win and immediately stop the search;
3574 * otherwise the attachment that has the youngest
3575 * descendant of medium will be used
3576 */
3577 if ( pAttach->getDevice() == aDevice
3578 && pAttach->getPort() == aControllerPort
3579 && pAttach->getControllerName() == aControllerName
3580 )
3581 {
3582 pAttachFound = pAttach;
3583 break;
3584 }
3585 else if ( !pAttachFound
3586 || level > foundLevel /* prefer younger */
3587 )
3588 {
3589 pAttachFound = pAttach;
3590 foundLevel = level;
3591 }
3592 }
3593 }
3594
3595 if (pAttachFound)
3596 {
3597 base = pAttachFound->getMedium();
3598 break;
3599 }
3600
3601 snap = snap->getParent();
3602 }
3603
3604 /* re-lock medium tree and the medium, as we need it below */
3605 treeLock.acquire();
3606 mediumLock.acquire();
3607
3608 /* found a suitable diff, use it as a base */
3609 if (!base.isNull())
3610 {
3611 medium = base;
3612 mediumCaller.attach(medium);
3613 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3614 mediumLock.attach(medium);
3615 }
3616 }
3617
3618 Utf8Str strFullSnapshotFolder;
3619 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
3620
3621 ComObjPtr<Medium> diff;
3622 diff.createObject();
3623 rc = diff->init(mParent,
3624 medium->getPreferredDiffFormat(),
3625 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
3626 medium->getFirstRegistryMachineId(), // store this diff in the same registry as the parent
3627 &llRegistriesThatNeedSaving);
3628 if (FAILED(rc)) return rc;
3629
3630 /* Apply the normal locking logic to the entire chain. */
3631 MediumLockList *pMediumLockList(new MediumLockList());
3632 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
3633 true /* fMediumLockWrite */,
3634 medium,
3635 *pMediumLockList);
3636 if (SUCCEEDED(rc))
3637 {
3638 rc = pMediumLockList->Lock();
3639 if (FAILED(rc))
3640 setError(rc,
3641 tr("Could not lock medium when creating diff '%s'"),
3642 diff->getLocationFull().c_str());
3643 else
3644 {
3645 /* will leave the lock before the potentially lengthy operation, so
3646 * protect with the special state */
3647 MachineState_T oldState = mData->mMachineState;
3648 setMachineState(MachineState_SettingUp);
3649
3650 mediumLock.leave();
3651 treeLock.leave();
3652 alock.leave();
3653
3654 rc = medium->createDiffStorage(diff,
3655 MediumVariant_Standard,
3656 pMediumLockList,
3657 NULL /* aProgress */,
3658 true /* aWait */,
3659 &llRegistriesThatNeedSaving);
3660
3661 alock.enter();
3662 treeLock.enter();
3663 mediumLock.enter();
3664
3665 setMachineState(oldState);
3666 }
3667 }
3668
3669 /* Unlock the media and free the associated memory. */
3670 delete pMediumLockList;
3671
3672 if (FAILED(rc)) return rc;
3673
3674 /* use the created diff for the actual attachment */
3675 medium = diff;
3676 mediumCaller.attach(medium);
3677 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3678 mediumLock.attach(medium);
3679 }
3680 while (0);
3681
3682 ComObjPtr<MediumAttachment> attachment;
3683 attachment.createObject();
3684 rc = attachment->init(this,
3685 medium,
3686 aControllerName,
3687 aControllerPort,
3688 aDevice,
3689 aType,
3690 fIndirect,
3691 NULL);
3692 if (FAILED(rc)) return rc;
3693
3694 if (associate && !medium.isNull())
3695 {
3696 // as the last step, associate the medium to the VM
3697 rc = medium->addBackReference(mData->mUuid);
3698 // here we can fail because of Deleting, or being in process of creating a Diff
3699 if (FAILED(rc)) return rc;
3700
3701 // and decide which medium registry to use now that the medium is attached:
3702 Guid uuid;
3703 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
3704 // machine XML is VirtualBox 4.0 or higher:
3705 uuid = getId(); // machine UUID
3706 else
3707 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
3708
3709 if (medium->addRegistry(uuid))
3710 // registry actually changed:
3711 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
3712 }
3713
3714 /* success: finally remember the attachment */
3715 setModified(IsModified_Storage);
3716 mMediaData.backup();
3717 mMediaData->mAttachments.push_back(attachment);
3718
3719 mediumLock.release();
3720 treeLock.leave();
3721 alock.release();
3722
3723 mParent->saveRegistries(llRegistriesThatNeedSaving);
3724
3725 return rc;
3726}
3727
3728STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
3729 LONG aDevice)
3730{
3731 CheckComArgStrNotEmptyOrNull(aControllerName);
3732
3733 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3734 aControllerName, aControllerPort, aDevice));
3735
3736 AutoCaller autoCaller(this);
3737 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3738
3739 GuidList llRegistriesThatNeedSaving;
3740
3741 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3742
3743 HRESULT rc = checkStateDependency(MutableStateDep);
3744 if (FAILED(rc)) return rc;
3745
3746 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3747
3748 if (Global::IsOnlineOrTransient(mData->mMachineState))
3749 return setError(VBOX_E_INVALID_VM_STATE,
3750 tr("Invalid machine state: %s"),
3751 Global::stringifyMachineState(mData->mMachineState));
3752
3753 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3754 aControllerName,
3755 aControllerPort,
3756 aDevice);
3757 if (!pAttach)
3758 return setError(VBOX_E_OBJECT_NOT_FOUND,
3759 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3760 aDevice, aControllerPort, aControllerName);
3761
3762 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */, &llRegistriesThatNeedSaving);
3763
3764 alock.release();
3765
3766 if (SUCCEEDED(rc))
3767 rc = mParent->saveRegistries(llRegistriesThatNeedSaving);
3768
3769 return rc;
3770}
3771
3772STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
3773 LONG aDevice, BOOL aPassthrough)
3774{
3775 CheckComArgStrNotEmptyOrNull(aControllerName);
3776
3777 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aPassthrough=%d\n",
3778 aControllerName, aControllerPort, aDevice, aPassthrough));
3779
3780 AutoCaller autoCaller(this);
3781 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3782
3783 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3784
3785 HRESULT rc = checkStateDependency(MutableStateDep);
3786 if (FAILED(rc)) return rc;
3787
3788 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3789
3790 if (Global::IsOnlineOrTransient(mData->mMachineState))
3791 return setError(VBOX_E_INVALID_VM_STATE,
3792 tr("Invalid machine state: %s"),
3793 Global::stringifyMachineState(mData->mMachineState));
3794
3795 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3796 aControllerName,
3797 aControllerPort,
3798 aDevice);
3799 if (!pAttach)
3800 return setError(VBOX_E_OBJECT_NOT_FOUND,
3801 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3802 aDevice, aControllerPort, aControllerName);
3803
3804
3805 setModified(IsModified_Storage);
3806 mMediaData.backup();
3807
3808 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3809
3810 if (pAttach->getType() != DeviceType_DVD)
3811 return setError(E_INVALIDARG,
3812 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3813 aDevice, aControllerPort, aControllerName);
3814 pAttach->updatePassthrough(!!aPassthrough);
3815
3816 return S_OK;
3817}
3818
3819STDMETHODIMP Machine::SetBandwidthGroupForDevice(IN_BSTR aControllerName, LONG aControllerPort,
3820 LONG aDevice, IBandwidthGroup *aBandwidthGroup)
3821{
3822 CheckComArgStrNotEmptyOrNull(aControllerName);
3823
3824 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3825 aControllerName, aControllerPort, aDevice));
3826
3827 AutoCaller autoCaller(this);
3828 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3829
3830 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3831
3832 HRESULT rc = checkStateDependency(MutableStateDep);
3833 if (FAILED(rc)) return rc;
3834
3835 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3836
3837 if (Global::IsOnlineOrTransient(mData->mMachineState))
3838 return setError(VBOX_E_INVALID_VM_STATE,
3839 tr("Invalid machine state: %s"),
3840 Global::stringifyMachineState(mData->mMachineState));
3841
3842 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3843 aControllerName,
3844 aControllerPort,
3845 aDevice);
3846 if (!pAttach)
3847 return setError(VBOX_E_OBJECT_NOT_FOUND,
3848 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3849 aDevice, aControllerPort, aControllerName);
3850
3851
3852 setModified(IsModified_Storage);
3853 mMediaData.backup();
3854
3855 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(aBandwidthGroup);
3856 if (aBandwidthGroup && group.isNull())
3857 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
3858
3859 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3860
3861 pAttach->updateBandwidthGroup(group);
3862
3863 return S_OK;
3864}
3865
3866
3867STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
3868 LONG aControllerPort,
3869 LONG aDevice,
3870 IMedium *aMedium,
3871 BOOL aForce)
3872{
3873 int rc = S_OK;
3874 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aForce=%d\n",
3875 aControllerName, aControllerPort, aDevice, aForce));
3876
3877 CheckComArgStrNotEmptyOrNull(aControllerName);
3878
3879 AutoCaller autoCaller(this);
3880 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3881
3882 // request the host lock first, since might be calling Host methods for getting host drives;
3883 // next, protect the media tree all the while we're in here, as well as our member variables
3884 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
3885 this->lockHandle(),
3886 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3887
3888 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3889 aControllerName,
3890 aControllerPort,
3891 aDevice);
3892 if (pAttach.isNull())
3893 return setError(VBOX_E_OBJECT_NOT_FOUND,
3894 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
3895 aDevice, aControllerPort, aControllerName);
3896
3897 /* Remember previously mounted medium. The medium before taking the
3898 * backup is not necessarily the same thing. */
3899 ComObjPtr<Medium> oldmedium;
3900 oldmedium = pAttach->getMedium();
3901
3902 ComObjPtr<Medium> pMedium = static_cast<Medium*>(aMedium);
3903 if (aMedium && pMedium.isNull())
3904 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3905
3906 AutoCaller mediumCaller(pMedium);
3907 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3908
3909 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3910 if (pMedium)
3911 {
3912 DeviceType_T mediumType = pAttach->getType();
3913 switch (mediumType)
3914 {
3915 case DeviceType_DVD:
3916 case DeviceType_Floppy:
3917 break;
3918
3919 default:
3920 return setError(VBOX_E_INVALID_OBJECT_STATE,
3921 tr("The device at port %d, device %d of controller '%ls' of this virtual machine is not removeable"),
3922 aControllerPort,
3923 aDevice,
3924 aControllerName);
3925 }
3926 }
3927
3928 setModified(IsModified_Storage);
3929 mMediaData.backup();
3930
3931 GuidList llRegistriesThatNeedSaving;
3932
3933 {
3934 // The backup operation makes the pAttach reference point to the
3935 // old settings. Re-get the correct reference.
3936 pAttach = findAttachment(mMediaData->mAttachments,
3937 aControllerName,
3938 aControllerPort,
3939 aDevice);
3940 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3941 if (!oldmedium.isNull())
3942 oldmedium->removeBackReference(mData->mUuid);
3943 if (!pMedium.isNull())
3944 {
3945 pMedium->addBackReference(mData->mUuid);
3946
3947 // and decide which medium registry to use now that the medium is attached:
3948 Guid uuid;
3949 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
3950 // machine XML is VirtualBox 4.0 or higher:
3951 uuid = getId(); // machine UUID
3952 else
3953 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
3954
3955 if (pMedium->addRegistry(uuid))
3956 // registry actually changed:
3957 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
3958 }
3959
3960 pAttach->updateMedium(pMedium);
3961 }
3962
3963 setModified(IsModified_Storage);
3964
3965 mediumLock.release();
3966 multiLock.release();
3967 rc = onMediumChange(pAttach, aForce);
3968 multiLock.acquire();
3969 mediumLock.acquire();
3970
3971 /* On error roll back this change only. */
3972 if (FAILED(rc))
3973 {
3974 if (!pMedium.isNull())
3975 pMedium->removeBackReference(mData->mUuid);
3976 pAttach = findAttachment(mMediaData->mAttachments,
3977 aControllerName,
3978 aControllerPort,
3979 aDevice);
3980 /* If the attachment is gone in the meantime, bail out. */
3981 if (pAttach.isNull())
3982 return rc;
3983 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3984 if (!oldmedium.isNull())
3985 oldmedium->addBackReference(mData->mUuid);
3986 pAttach->updateMedium(oldmedium);
3987 }
3988
3989 mediumLock.release();
3990 multiLock.release();
3991
3992 mParent->saveRegistries(llRegistriesThatNeedSaving);
3993
3994 return rc;
3995}
3996
3997STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
3998 LONG aControllerPort,
3999 LONG aDevice,
4000 IMedium **aMedium)
4001{
4002 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
4003 aControllerName, aControllerPort, aDevice));
4004
4005 CheckComArgStrNotEmptyOrNull(aControllerName);
4006 CheckComArgOutPointerValid(aMedium);
4007
4008 AutoCaller autoCaller(this);
4009 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4010
4011 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4012
4013 *aMedium = NULL;
4014
4015 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4016 aControllerName,
4017 aControllerPort,
4018 aDevice);
4019 if (pAttach.isNull())
4020 return setError(VBOX_E_OBJECT_NOT_FOUND,
4021 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4022 aDevice, aControllerPort, aControllerName);
4023
4024 pAttach->getMedium().queryInterfaceTo(aMedium);
4025
4026 return S_OK;
4027}
4028
4029STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
4030{
4031 CheckComArgOutPointerValid(port);
4032 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
4033
4034 AutoCaller autoCaller(this);
4035 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4036
4037 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4038
4039 mSerialPorts[slot].queryInterfaceTo(port);
4040
4041 return S_OK;
4042}
4043
4044STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
4045{
4046 CheckComArgOutPointerValid(port);
4047 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
4048
4049 AutoCaller autoCaller(this);
4050 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4051
4052 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4053
4054 mParallelPorts[slot].queryInterfaceTo(port);
4055
4056 return S_OK;
4057}
4058
4059STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
4060{
4061 CheckComArgOutPointerValid(adapter);
4062 CheckComArgExpr(slot, slot < RT_ELEMENTS(mNetworkAdapters));
4063
4064 AutoCaller autoCaller(this);
4065 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4066
4067 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4068
4069 mNetworkAdapters[slot].queryInterfaceTo(adapter);
4070
4071 return S_OK;
4072}
4073
4074STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
4075{
4076 if (ComSafeArrayOutIsNull(aKeys))
4077 return E_POINTER;
4078
4079 AutoCaller autoCaller(this);
4080 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4081
4082 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4083
4084 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
4085 int i = 0;
4086 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4087 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4088 ++it, ++i)
4089 {
4090 const Utf8Str &strKey = it->first;
4091 strKey.cloneTo(&saKeys[i]);
4092 }
4093 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
4094
4095 return S_OK;
4096 }
4097
4098 /**
4099 * @note Locks this object for reading.
4100 */
4101STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
4102 BSTR *aValue)
4103{
4104 CheckComArgStrNotEmptyOrNull(aKey);
4105 CheckComArgOutPointerValid(aValue);
4106
4107 AutoCaller autoCaller(this);
4108 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4109
4110 /* start with nothing found */
4111 Bstr bstrResult("");
4112
4113 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4114
4115 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
4116 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4117 // found:
4118 bstrResult = it->second; // source is a Utf8Str
4119
4120 /* return the result to caller (may be empty) */
4121 bstrResult.cloneTo(aValue);
4122
4123 return S_OK;
4124}
4125
4126 /**
4127 * @note Locks mParent for writing + this object for writing.
4128 */
4129STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
4130{
4131 CheckComArgStrNotEmptyOrNull(aKey);
4132
4133 AutoCaller autoCaller(this);
4134 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4135
4136 Utf8Str strKey(aKey);
4137 Utf8Str strValue(aValue);
4138 Utf8Str strOldValue; // empty
4139
4140 // locking note: we only hold the read lock briefly to look up the old value,
4141 // then release it and call the onExtraCanChange callbacks. There is a small
4142 // chance of a race insofar as the callback might be called twice if two callers
4143 // change the same key at the same time, but that's a much better solution
4144 // than the deadlock we had here before. The actual changing of the extradata
4145 // is then performed under the write lock and race-free.
4146
4147 // look up the old value first; if nothing has changed then we need not do anything
4148 {
4149 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
4150 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
4151 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4152 strOldValue = it->second;
4153 }
4154
4155 bool fChanged;
4156 if ((fChanged = (strOldValue != strValue)))
4157 {
4158 // ask for permission from all listeners outside the locks;
4159 // onExtraDataCanChange() only briefly requests the VirtualBox
4160 // lock to copy the list of callbacks to invoke
4161 Bstr error;
4162 Bstr bstrValue(aValue);
4163
4164 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue.raw(), error))
4165 {
4166 const char *sep = error.isEmpty() ? "" : ": ";
4167 CBSTR err = error.raw();
4168 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
4169 sep, err));
4170 return setError(E_ACCESSDENIED,
4171 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
4172 aKey,
4173 bstrValue.raw(),
4174 sep,
4175 err);
4176 }
4177
4178 // data is changing and change not vetoed: then write it out under the lock
4179 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4180
4181 if (isSnapshotMachine())
4182 {
4183 HRESULT rc = checkStateDependency(MutableStateDep);
4184 if (FAILED(rc)) return rc;
4185 }
4186
4187 if (strValue.isEmpty())
4188 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
4189 else
4190 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
4191 // creates a new key if needed
4192
4193 bool fNeedsGlobalSaveSettings = false;
4194 saveSettings(&fNeedsGlobalSaveSettings);
4195
4196 if (fNeedsGlobalSaveSettings)
4197 {
4198 // save the global settings; for that we should hold only the VirtualBox lock
4199 alock.release();
4200 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
4201 mParent->saveSettings();
4202 }
4203 }
4204
4205 // fire notification outside the lock
4206 if (fChanged)
4207 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
4208
4209 return S_OK;
4210}
4211
4212STDMETHODIMP Machine::SaveSettings()
4213{
4214 AutoCaller autoCaller(this);
4215 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4216
4217 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
4218
4219 /* when there was auto-conversion, we want to save the file even if
4220 * the VM is saved */
4221 HRESULT rc = checkStateDependency(MutableStateDep);
4222 if (FAILED(rc)) return rc;
4223
4224 /* the settings file path may never be null */
4225 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
4226
4227 /* save all VM data excluding snapshots */
4228 bool fNeedsGlobalSaveSettings = false;
4229 rc = saveSettings(&fNeedsGlobalSaveSettings);
4230 mlock.release();
4231
4232 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
4233 {
4234 // save the global settings; for that we should hold only the VirtualBox lock
4235 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
4236 rc = mParent->saveSettings();
4237 }
4238
4239 return rc;
4240}
4241
4242STDMETHODIMP Machine::DiscardSettings()
4243{
4244 AutoCaller autoCaller(this);
4245 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4246
4247 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4248
4249 HRESULT rc = checkStateDependency(MutableStateDep);
4250 if (FAILED(rc)) return rc;
4251
4252 /*
4253 * during this rollback, the session will be notified if data has
4254 * been actually changed
4255 */
4256 rollback(true /* aNotify */);
4257
4258 return S_OK;
4259}
4260
4261/** @note Locks objects! */
4262STDMETHODIMP Machine::Unregister(CleanupMode_T cleanupMode,
4263 ComSafeArrayOut(IMedium*, aMedia))
4264{
4265 // use AutoLimitedCaller because this call is valid on inaccessible machines as well
4266 AutoLimitedCaller autoCaller(this);
4267 AssertComRCReturnRC(autoCaller.rc());
4268
4269 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4270
4271 Guid id(getId());
4272
4273 if (mData->mSession.mState != SessionState_Unlocked)
4274 return setError(VBOX_E_INVALID_OBJECT_STATE,
4275 tr("Cannot unregister the machine '%s' while it is locked"),
4276 mUserData->s.strName.c_str());
4277
4278 // wait for state dependents to drop to zero
4279 ensureNoStateDependencies();
4280
4281 if (!mData->mAccessible)
4282 {
4283 // inaccessible maschines can only be unregistered; uninitialize ourselves
4284 // here because currently there may be no unregistered that are inaccessible
4285 // (this state combination is not supported). Note releasing the caller and
4286 // leaving the lock before calling uninit()
4287 alock.leave();
4288 autoCaller.release();
4289
4290 uninit();
4291
4292 mParent->unregisterMachine(this, id);
4293 // calls VirtualBox::saveSettings()
4294
4295 return S_OK;
4296 }
4297
4298 HRESULT rc = S_OK;
4299
4300 // discard saved state
4301 if (mData->mMachineState == MachineState_Saved)
4302 {
4303 // add the saved state file to the list of files the caller should delete
4304 Assert(!mSSData->mStateFilePath.isEmpty());
4305 mData->llFilesToDelete.push_back(mSSData->mStateFilePath);
4306
4307 mSSData->mStateFilePath.setNull();
4308
4309 // unconditionally set the machine state to powered off, we now
4310 // know no session has locked the machine
4311 mData->mMachineState = MachineState_PoweredOff;
4312 }
4313
4314 size_t cSnapshots = 0;
4315 if (mData->mFirstSnapshot)
4316 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4317 if (cSnapshots && cleanupMode == CleanupMode_UnregisterOnly)
4318 // fail now before we start detaching media
4319 return setError(VBOX_E_INVALID_OBJECT_STATE,
4320 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
4321 mUserData->s.strName.c_str(), cSnapshots);
4322
4323 // this list collects the medium objects from all medium attachments
4324 // which got detached from the machine and its snapshots, in the following
4325 // order:
4326 // 1) media from machine attachments (these have the "leaf" attachments with snapshots
4327 // and must be closed first, or closing the parents will fail because they will
4328 // children);
4329 // 2) media from the youngest snapshots followed by those from the parent snapshots until
4330 // the root ("first") snapshot of the machine
4331 // This order allows for closing the media on this list from the beginning to the end
4332 // without getting "media in use" errors.
4333 MediaList llMedia;
4334
4335 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4336 && mMediaData->mAttachments.size()
4337 )
4338 {
4339 // we have media attachments: detach them all and add the Medium objects to our list
4340 if (cleanupMode != CleanupMode_UnregisterOnly)
4341 detachAllMedia(alock, NULL /* pSnapshot */, cleanupMode, llMedia);
4342 else
4343 return setError(VBOX_E_INVALID_OBJECT_STATE,
4344 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
4345 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
4346 }
4347
4348 if (cSnapshots)
4349 {
4350 // autoCleanup must be true here, or we would have failed above
4351
4352 // add the media from the medium attachments of the snapshots to llMedia
4353 // as well, after the "main" machine media; Snapshot::uninitRecursively()
4354 // calls Machine::detachAllMedia() for the snapshot machine, recursing
4355 // into the children first
4356
4357 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
4358 MachineState_T oldState = mData->mMachineState;
4359 mData->mMachineState = MachineState_DeletingSnapshot;
4360
4361 // make a copy of the first snapshot so the refcount does not drop to 0
4362 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
4363 // because of the AutoCaller voodoo)
4364 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
4365
4366 // GO!
4367 pFirstSnapshot->uninitRecursively(alock, cleanupMode, llMedia, mData->llFilesToDelete);
4368
4369 mData->mMachineState = oldState;
4370 }
4371
4372 if (FAILED(rc))
4373 {
4374 rollbackMedia();
4375 return rc;
4376 }
4377
4378 // commit all the media changes made above
4379 commitMedia();
4380
4381 mData->mRegistered = false;
4382
4383 // machine lock no longer needed
4384 alock.release();
4385
4386 // return media to caller
4387 SafeIfaceArray<IMedium> sfaMedia(llMedia);
4388 sfaMedia.detachTo(ComSafeArrayOutArg(aMedia));
4389
4390 mParent->unregisterMachine(this, id);
4391 // calls VirtualBox::saveSettings()
4392
4393 return S_OK;
4394}
4395
4396struct Machine::DeleteTask
4397{
4398 ComObjPtr<Machine> pMachine;
4399 std::list<Utf8Str> llFilesToDelete;
4400 ComObjPtr<Progress> pProgress;
4401 GuidList llRegistriesThatNeedSaving;
4402};
4403
4404STDMETHODIMP Machine::Delete(ComSafeArrayIn(IMedium*, aMedia), IProgress **aProgress)
4405{
4406 LogFlowFuncEnter();
4407
4408 AutoCaller autoCaller(this);
4409 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4410
4411 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4412
4413 HRESULT rc = checkStateDependency(MutableStateDep);
4414 if (FAILED(rc)) return rc;
4415
4416 if (mData->mRegistered)
4417 return setError(VBOX_E_INVALID_VM_STATE,
4418 tr("Cannot delete settings of a registered machine"));
4419
4420 DeleteTask *pTask = new DeleteTask;
4421 pTask->pMachine = this;
4422 com::SafeIfaceArray<IMedium> sfaMedia(ComSafeArrayInArg(aMedia));
4423
4424 // collect files to delete
4425 pTask->llFilesToDelete = mData->llFilesToDelete; // saved states pushed here by Unregister()
4426
4427 for (size_t i = 0; i < sfaMedia.size(); ++i)
4428 {
4429 IMedium *pIMedium(sfaMedia[i]);
4430 Medium *pMedium = static_cast<Medium*>(pIMedium);
4431 AutoCaller mediumAutoCaller(pMedium);
4432 if (FAILED(mediumAutoCaller.rc())) return mediumAutoCaller.rc();
4433
4434 Utf8Str bstrLocation = pMedium->getLocationFull();
4435
4436 bool fDoesMediumNeedFileDeletion = pMedium->isMediumFormatFile();
4437
4438 // close the medium now; if that succeeds, then that means the medium is no longer
4439 // in use and we can add it to the list of files to delete
4440 rc = pMedium->close(&pTask->llRegistriesThatNeedSaving,
4441 mediumAutoCaller);
4442 if (SUCCEEDED(rc) && fDoesMediumNeedFileDeletion)
4443 pTask->llFilesToDelete.push_back(bstrLocation);
4444 }
4445 if (mData->pMachineConfigFile->fileExists())
4446 pTask->llFilesToDelete.push_back(mData->m_strConfigFileFull);
4447
4448 pTask->pProgress.createObject();
4449 pTask->pProgress->init(getVirtualBox(),
4450 static_cast<IMachine*>(this) /* aInitiator */,
4451 Bstr(tr("Deleting files")).raw(),
4452 true /* fCancellable */,
4453 pTask->llFilesToDelete.size() + 1, // cOperations
4454 BstrFmt(tr("Deleting '%s'"), pTask->llFilesToDelete.front().c_str()).raw());
4455
4456 int vrc = RTThreadCreate(NULL,
4457 Machine::deleteThread,
4458 (void*)pTask,
4459 0,
4460 RTTHREADTYPE_MAIN_WORKER,
4461 0,
4462 "MachineDelete");
4463
4464 pTask->pProgress.queryInterfaceTo(aProgress);
4465
4466 if (RT_FAILURE(vrc))
4467 {
4468 delete pTask;
4469 return setError(E_FAIL, "Could not create MachineDelete thread (%Rrc)", vrc);
4470 }
4471
4472 LogFlowFuncLeave();
4473
4474 return S_OK;
4475}
4476
4477/**
4478 * Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
4479 * calls Machine::deleteTaskWorker() on the actual machine object.
4480 * @param Thread
4481 * @param pvUser
4482 * @return
4483 */
4484/*static*/
4485DECLCALLBACK(int) Machine::deleteThread(RTTHREAD Thread, void *pvUser)
4486{
4487 LogFlowFuncEnter();
4488
4489 DeleteTask *pTask = (DeleteTask*)pvUser;
4490 Assert(pTask);
4491 Assert(pTask->pMachine);
4492 Assert(pTask->pProgress);
4493
4494 HRESULT rc = pTask->pMachine->deleteTaskWorker(*pTask);
4495 pTask->pProgress->notifyComplete(rc);
4496
4497 delete pTask;
4498
4499 LogFlowFuncLeave();
4500
4501 NOREF(Thread);
4502
4503 return VINF_SUCCESS;
4504}
4505
4506/**
4507 * Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
4508 * @param task
4509 * @return
4510 */
4511HRESULT Machine::deleteTaskWorker(DeleteTask &task)
4512{
4513 AutoCaller autoCaller(this);
4514 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4515
4516 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4517
4518 ULONG uLogHistoryCount = 3;
4519 ComPtr<ISystemProperties> systemProperties;
4520 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4521 if (!systemProperties.isNull())
4522 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4523
4524 // delete the files pushed on the task list by Machine::Delete()
4525 // (this includes saved states of the machine and snapshots and
4526 // medium storage files from the IMedium list passed in, and the
4527 // machine XML file)
4528 std::list<Utf8Str>::const_iterator it = task.llFilesToDelete.begin();
4529 while (it != task.llFilesToDelete.end())
4530 {
4531 const Utf8Str &strFile = *it;
4532 LogFunc(("Deleting file %s\n", strFile.c_str()));
4533 RTFileDelete(strFile.c_str());
4534
4535 ++it;
4536 if (it == task.llFilesToDelete.end())
4537 {
4538 task.pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
4539 break;
4540 }
4541
4542 task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
4543 }
4544
4545 /* delete the settings only when the file actually exists */
4546 if (mData->pMachineConfigFile->fileExists())
4547 {
4548 /* Delete any backup or uncommitted XML files. Ignore failures.
4549 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4550 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4551 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4552 RTFileDelete(otherXml.c_str());
4553 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4554 RTFileDelete(otherXml.c_str());
4555
4556 /* delete the Logs folder, nothing important should be left
4557 * there (we don't check for errors because the user might have
4558 * some private files there that we don't want to delete) */
4559 Utf8Str logFolder;
4560 getLogFolder(logFolder);
4561 Assert(logFolder.length());
4562 if (RTDirExists(logFolder.c_str()))
4563 {
4564 /* Delete all VBox.log[.N] files from the Logs folder
4565 * (this must be in sync with the rotation logic in
4566 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4567 * files that may have been created by the GUI. */
4568 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4569 logFolder.c_str(), RTPATH_DELIMITER);
4570 RTFileDelete(log.c_str());
4571 log = Utf8StrFmt("%s%cVBox.png",
4572 logFolder.c_str(), RTPATH_DELIMITER);
4573 RTFileDelete(log.c_str());
4574 for (int i = uLogHistoryCount; i > 0; i--)
4575 {
4576 log = Utf8StrFmt("%s%cVBox.log.%d",
4577 logFolder.c_str(), RTPATH_DELIMITER, i);
4578 RTFileDelete(log.c_str());
4579 log = Utf8StrFmt("%s%cVBox.png.%d",
4580 logFolder.c_str(), RTPATH_DELIMITER, i);
4581 RTFileDelete(log.c_str());
4582 }
4583
4584 RTDirRemove(logFolder.c_str());
4585 }
4586
4587 /* delete the Snapshots folder, nothing important should be left
4588 * there (we don't check for errors because the user might have
4589 * some private files there that we don't want to delete) */
4590 Utf8Str strFullSnapshotFolder;
4591 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4592 Assert(!strFullSnapshotFolder.isEmpty());
4593 if (RTDirExists(strFullSnapshotFolder.c_str()))
4594 RTDirRemove(strFullSnapshotFolder.c_str());
4595
4596 // delete the directory that contains the settings file, but only
4597 // if it matches the VM name
4598 Utf8Str settingsDir;
4599 if (isInOwnDir(&settingsDir))
4600 RTDirRemove(settingsDir.c_str());
4601 }
4602
4603 alock.release();
4604
4605 mParent->saveRegistries(task.llRegistriesThatNeedSaving);
4606
4607 return S_OK;
4608}
4609
4610STDMETHODIMP Machine::FindSnapshot(IN_BSTR aNameOrId, ISnapshot **aSnapshot)
4611{
4612 CheckComArgOutPointerValid(aSnapshot);
4613
4614 AutoCaller autoCaller(this);
4615 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4616
4617 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4618
4619 ComObjPtr<Snapshot> pSnapshot;
4620 HRESULT rc;
4621
4622 if (!aNameOrId || !*aNameOrId)
4623 // null case (caller wants root snapshot): findSnapshotById() handles this
4624 rc = findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
4625 else
4626 {
4627 Guid uuid(aNameOrId);
4628 if (!uuid.isEmpty())
4629 rc = findSnapshotById(uuid, pSnapshot, true /* aSetError */);
4630 else
4631 rc = findSnapshotByName(Utf8Str(aNameOrId), pSnapshot, true /* aSetError */);
4632 }
4633 pSnapshot.queryInterfaceTo(aSnapshot);
4634
4635 return rc;
4636}
4637
4638STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4639{
4640 CheckComArgStrNotEmptyOrNull(aName);
4641 CheckComArgStrNotEmptyOrNull(aHostPath);
4642
4643 AutoCaller autoCaller(this);
4644 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4645
4646 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4647
4648 HRESULT rc = checkStateDependency(MutableStateDep);
4649 if (FAILED(rc)) return rc;
4650
4651 ComObjPtr<SharedFolder> sharedFolder;
4652 rc = findSharedFolder(aName, sharedFolder, false /* aSetError */);
4653 if (SUCCEEDED(rc))
4654 return setError(VBOX_E_OBJECT_IN_USE,
4655 tr("Shared folder named '%ls' already exists"),
4656 aName);
4657
4658 sharedFolder.createObject();
4659 rc = sharedFolder->init(getMachine(), aName, aHostPath, aWritable, aAutoMount);
4660 if (FAILED(rc)) return rc;
4661
4662 setModified(IsModified_SharedFolders);
4663 mHWData.backup();
4664 mHWData->mSharedFolders.push_back(sharedFolder);
4665
4666 /* inform the direct session if any */
4667 alock.leave();
4668 onSharedFolderChange();
4669
4670 return S_OK;
4671}
4672
4673STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4674{
4675 CheckComArgStrNotEmptyOrNull(aName);
4676
4677 AutoCaller autoCaller(this);
4678 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4679
4680 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4681
4682 HRESULT rc = checkStateDependency(MutableStateDep);
4683 if (FAILED(rc)) return rc;
4684
4685 ComObjPtr<SharedFolder> sharedFolder;
4686 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4687 if (FAILED(rc)) return rc;
4688
4689 setModified(IsModified_SharedFolders);
4690 mHWData.backup();
4691 mHWData->mSharedFolders.remove(sharedFolder);
4692
4693 /* inform the direct session if any */
4694 alock.leave();
4695 onSharedFolderChange();
4696
4697 return S_OK;
4698}
4699
4700STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4701{
4702 CheckComArgOutPointerValid(aCanShow);
4703
4704 /* start with No */
4705 *aCanShow = FALSE;
4706
4707 AutoCaller autoCaller(this);
4708 AssertComRCReturnRC(autoCaller.rc());
4709
4710 ComPtr<IInternalSessionControl> directControl;
4711 {
4712 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4713
4714 if (mData->mSession.mState != SessionState_Locked)
4715 return setError(VBOX_E_INVALID_VM_STATE,
4716 tr("Machine is not locked for session (session state: %s)"),
4717 Global::stringifySessionState(mData->mSession.mState));
4718
4719 directControl = mData->mSession.mDirectControl;
4720 }
4721
4722 /* ignore calls made after #OnSessionEnd() is called */
4723 if (!directControl)
4724 return S_OK;
4725
4726 LONG64 dummy;
4727 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
4728}
4729
4730STDMETHODIMP Machine::ShowConsoleWindow(LONG64 *aWinId)
4731{
4732 CheckComArgOutPointerValid(aWinId);
4733
4734 AutoCaller autoCaller(this);
4735 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4736
4737 ComPtr<IInternalSessionControl> directControl;
4738 {
4739 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4740
4741 if (mData->mSession.mState != SessionState_Locked)
4742 return setError(E_FAIL,
4743 tr("Machine is not locked for session (session state: %s)"),
4744 Global::stringifySessionState(mData->mSession.mState));
4745
4746 directControl = mData->mSession.mDirectControl;
4747 }
4748
4749 /* ignore calls made after #OnSessionEnd() is called */
4750 if (!directControl)
4751 return S_OK;
4752
4753 BOOL dummy;
4754 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
4755}
4756
4757#ifdef VBOX_WITH_GUEST_PROPS
4758/**
4759 * Look up a guest property in VBoxSVC's internal structures.
4760 */
4761HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4762 BSTR *aValue,
4763 LONG64 *aTimestamp,
4764 BSTR *aFlags) const
4765{
4766 using namespace guestProp;
4767
4768 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4769 Utf8Str strName(aName);
4770 HWData::GuestPropertyList::const_iterator it;
4771
4772 for (it = mHWData->mGuestProperties.begin();
4773 it != mHWData->mGuestProperties.end(); ++it)
4774 {
4775 if (it->strName == strName)
4776 {
4777 char szFlags[MAX_FLAGS_LEN + 1];
4778 it->strValue.cloneTo(aValue);
4779 *aTimestamp = it->mTimestamp;
4780 writeFlags(it->mFlags, szFlags);
4781 Bstr(szFlags).cloneTo(aFlags);
4782 break;
4783 }
4784 }
4785 return S_OK;
4786}
4787
4788/**
4789 * Query the VM that a guest property belongs to for the property.
4790 * @returns E_ACCESSDENIED if the VM process is not available or not
4791 * currently handling queries and the lookup should then be done in
4792 * VBoxSVC.
4793 */
4794HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4795 BSTR *aValue,
4796 LONG64 *aTimestamp,
4797 BSTR *aFlags) const
4798{
4799 HRESULT rc;
4800 ComPtr<IInternalSessionControl> directControl;
4801 directControl = mData->mSession.mDirectControl;
4802
4803 /* fail if we were called after #OnSessionEnd() is called. This is a
4804 * silly race condition. */
4805
4806 if (!directControl)
4807 rc = E_ACCESSDENIED;
4808 else
4809 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4810 false /* isSetter */,
4811 aValue, aTimestamp, aFlags);
4812 return rc;
4813}
4814#endif // VBOX_WITH_GUEST_PROPS
4815
4816STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4817 BSTR *aValue,
4818 LONG64 *aTimestamp,
4819 BSTR *aFlags)
4820{
4821#ifndef VBOX_WITH_GUEST_PROPS
4822 ReturnComNotImplemented();
4823#else // VBOX_WITH_GUEST_PROPS
4824 CheckComArgStrNotEmptyOrNull(aName);
4825 CheckComArgOutPointerValid(aValue);
4826 CheckComArgOutPointerValid(aTimestamp);
4827 CheckComArgOutPointerValid(aFlags);
4828
4829 AutoCaller autoCaller(this);
4830 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4831
4832 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4833 if (rc == E_ACCESSDENIED)
4834 /* The VM is not running or the service is not (yet) accessible */
4835 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4836 return rc;
4837#endif // VBOX_WITH_GUEST_PROPS
4838}
4839
4840STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4841{
4842 LONG64 dummyTimestamp;
4843 Bstr dummyFlags;
4844 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
4845}
4846
4847STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, LONG64 *aTimestamp)
4848{
4849 Bstr dummyValue;
4850 Bstr dummyFlags;
4851 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
4852}
4853
4854#ifdef VBOX_WITH_GUEST_PROPS
4855/**
4856 * Set a guest property in VBoxSVC's internal structures.
4857 */
4858HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4859 IN_BSTR aFlags)
4860{
4861 using namespace guestProp;
4862
4863 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4864 HRESULT rc = S_OK;
4865 HWData::GuestProperty property;
4866 property.mFlags = NILFLAG;
4867 bool found = false;
4868
4869 rc = checkStateDependency(MutableStateDep);
4870 if (FAILED(rc)) return rc;
4871
4872 try
4873 {
4874 Utf8Str utf8Name(aName);
4875 Utf8Str utf8Flags(aFlags);
4876 uint32_t fFlags = NILFLAG;
4877 if ( (aFlags != NULL)
4878 && RT_FAILURE(validateFlags(utf8Flags.c_str(), &fFlags))
4879 )
4880 return setError(E_INVALIDARG,
4881 tr("Invalid flag values: '%ls'"),
4882 aFlags);
4883
4884 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
4885 * know, this is simple and do an OK job atm.) */
4886 HWData::GuestPropertyList::iterator it;
4887 for (it = mHWData->mGuestProperties.begin();
4888 it != mHWData->mGuestProperties.end(); ++it)
4889 if (it->strName == utf8Name)
4890 {
4891 property = *it;
4892 if (it->mFlags & (RDONLYHOST))
4893 rc = setError(E_ACCESSDENIED,
4894 tr("The property '%ls' cannot be changed by the host"),
4895 aName);
4896 else
4897 {
4898 setModified(IsModified_MachineData);
4899 mHWData.backup(); // @todo r=dj backup in a loop?!?
4900
4901 /* The backup() operation invalidates our iterator, so
4902 * get a new one. */
4903 for (it = mHWData->mGuestProperties.begin();
4904 it->strName != utf8Name;
4905 ++it)
4906 ;
4907 mHWData->mGuestProperties.erase(it);
4908 }
4909 found = true;
4910 break;
4911 }
4912 if (found && SUCCEEDED(rc))
4913 {
4914 if (*aValue)
4915 {
4916 RTTIMESPEC time;
4917 property.strValue = aValue;
4918 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4919 if (aFlags != NULL)
4920 property.mFlags = fFlags;
4921 mHWData->mGuestProperties.push_back(property);
4922 }
4923 }
4924 else if (SUCCEEDED(rc) && *aValue)
4925 {
4926 RTTIMESPEC time;
4927 setModified(IsModified_MachineData);
4928 mHWData.backup();
4929 property.strName = aName;
4930 property.strValue = aValue;
4931 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4932 property.mFlags = fFlags;
4933 mHWData->mGuestProperties.push_back(property);
4934 }
4935 if ( SUCCEEDED(rc)
4936 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
4937 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
4938 RTSTR_MAX,
4939 utf8Name.c_str(),
4940 RTSTR_MAX,
4941 NULL)
4942 )
4943 )
4944 {
4945 /** @todo r=bird: Why aren't we leaving the lock here? The
4946 * same code in PushGuestProperty does... */
4947 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
4948 }
4949 }
4950 catch (std::bad_alloc &)
4951 {
4952 rc = E_OUTOFMEMORY;
4953 }
4954
4955 return rc;
4956}
4957
4958/**
4959 * Set a property on the VM that that property belongs to.
4960 * @returns E_ACCESSDENIED if the VM process is not available or not
4961 * currently handling queries and the setting should then be done in
4962 * VBoxSVC.
4963 */
4964HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
4965 IN_BSTR aFlags)
4966{
4967 HRESULT rc;
4968
4969 try {
4970 ComPtr<IInternalSessionControl> directControl =
4971 mData->mSession.mDirectControl;
4972
4973 BSTR dummy = NULL; /* will not be changed (setter) */
4974 LONG64 dummy64;
4975 if (!directControl)
4976 rc = E_ACCESSDENIED;
4977 else
4978 rc = directControl->AccessGuestProperty
4979 (aName,
4980 /** @todo Fix when adding DeleteGuestProperty(),
4981 see defect. */
4982 *aValue ? aValue : NULL, aFlags, true /* isSetter */,
4983 &dummy, &dummy64, &dummy);
4984 }
4985 catch (std::bad_alloc &)
4986 {
4987 rc = E_OUTOFMEMORY;
4988 }
4989
4990 return rc;
4991}
4992#endif // VBOX_WITH_GUEST_PROPS
4993
4994STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
4995 IN_BSTR aFlags)
4996{
4997#ifndef VBOX_WITH_GUEST_PROPS
4998 ReturnComNotImplemented();
4999#else // VBOX_WITH_GUEST_PROPS
5000 CheckComArgStrNotEmptyOrNull(aName);
5001 if ((aFlags != NULL) && !VALID_PTR(aFlags))
5002 return E_INVALIDARG;
5003 AutoCaller autoCaller(this);
5004 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5005
5006 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
5007 if (rc == E_ACCESSDENIED)
5008 /* The VM is not running or the service is not (yet) accessible */
5009 rc = setGuestPropertyToService(aName, aValue, aFlags);
5010 return rc;
5011#endif // VBOX_WITH_GUEST_PROPS
5012}
5013
5014STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
5015{
5016 return SetGuestProperty(aName, aValue, NULL);
5017}
5018
5019#ifdef VBOX_WITH_GUEST_PROPS
5020/**
5021 * Enumerate the guest properties in VBoxSVC's internal structures.
5022 */
5023HRESULT Machine::enumerateGuestPropertiesInService
5024 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5025 ComSafeArrayOut(BSTR, aValues),
5026 ComSafeArrayOut(LONG64, aTimestamps),
5027 ComSafeArrayOut(BSTR, aFlags))
5028{
5029 using namespace guestProp;
5030
5031 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5032 Utf8Str strPatterns(aPatterns);
5033
5034 /*
5035 * Look for matching patterns and build up a list.
5036 */
5037 HWData::GuestPropertyList propList;
5038 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
5039 it != mHWData->mGuestProperties.end();
5040 ++it)
5041 if ( strPatterns.isEmpty()
5042 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5043 RTSTR_MAX,
5044 it->strName.c_str(),
5045 RTSTR_MAX,
5046 NULL)
5047 )
5048 propList.push_back(*it);
5049
5050 /*
5051 * And build up the arrays for returning the property information.
5052 */
5053 size_t cEntries = propList.size();
5054 SafeArray<BSTR> names(cEntries);
5055 SafeArray<BSTR> values(cEntries);
5056 SafeArray<LONG64> timestamps(cEntries);
5057 SafeArray<BSTR> flags(cEntries);
5058 size_t iProp = 0;
5059 for (HWData::GuestPropertyList::iterator it = propList.begin();
5060 it != propList.end();
5061 ++it)
5062 {
5063 char szFlags[MAX_FLAGS_LEN + 1];
5064 it->strName.cloneTo(&names[iProp]);
5065 it->strValue.cloneTo(&values[iProp]);
5066 timestamps[iProp] = it->mTimestamp;
5067 writeFlags(it->mFlags, szFlags);
5068 Bstr(szFlags).cloneTo(&flags[iProp]);
5069 ++iProp;
5070 }
5071 names.detachTo(ComSafeArrayOutArg(aNames));
5072 values.detachTo(ComSafeArrayOutArg(aValues));
5073 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
5074 flags.detachTo(ComSafeArrayOutArg(aFlags));
5075 return S_OK;
5076}
5077
5078/**
5079 * Enumerate the properties managed by a VM.
5080 * @returns E_ACCESSDENIED if the VM process is not available or not
5081 * currently handling queries and the setting should then be done in
5082 * VBoxSVC.
5083 */
5084HRESULT Machine::enumerateGuestPropertiesOnVM
5085 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5086 ComSafeArrayOut(BSTR, aValues),
5087 ComSafeArrayOut(LONG64, aTimestamps),
5088 ComSafeArrayOut(BSTR, aFlags))
5089{
5090 HRESULT rc;
5091 ComPtr<IInternalSessionControl> directControl;
5092 directControl = mData->mSession.mDirectControl;
5093
5094 if (!directControl)
5095 rc = E_ACCESSDENIED;
5096 else
5097 rc = directControl->EnumerateGuestProperties
5098 (aPatterns, ComSafeArrayOutArg(aNames),
5099 ComSafeArrayOutArg(aValues),
5100 ComSafeArrayOutArg(aTimestamps),
5101 ComSafeArrayOutArg(aFlags));
5102 return rc;
5103}
5104#endif // VBOX_WITH_GUEST_PROPS
5105
5106STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
5107 ComSafeArrayOut(BSTR, aNames),
5108 ComSafeArrayOut(BSTR, aValues),
5109 ComSafeArrayOut(LONG64, aTimestamps),
5110 ComSafeArrayOut(BSTR, aFlags))
5111{
5112#ifndef VBOX_WITH_GUEST_PROPS
5113 ReturnComNotImplemented();
5114#else // VBOX_WITH_GUEST_PROPS
5115 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
5116 return E_POINTER;
5117
5118 CheckComArgOutSafeArrayPointerValid(aNames);
5119 CheckComArgOutSafeArrayPointerValid(aValues);
5120 CheckComArgOutSafeArrayPointerValid(aTimestamps);
5121 CheckComArgOutSafeArrayPointerValid(aFlags);
5122
5123 AutoCaller autoCaller(this);
5124 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5125
5126 HRESULT rc = enumerateGuestPropertiesOnVM
5127 (aPatterns, ComSafeArrayOutArg(aNames),
5128 ComSafeArrayOutArg(aValues),
5129 ComSafeArrayOutArg(aTimestamps),
5130 ComSafeArrayOutArg(aFlags));
5131 if (rc == E_ACCESSDENIED)
5132 /* The VM is not running or the service is not (yet) accessible */
5133 rc = enumerateGuestPropertiesInService
5134 (aPatterns, ComSafeArrayOutArg(aNames),
5135 ComSafeArrayOutArg(aValues),
5136 ComSafeArrayOutArg(aTimestamps),
5137 ComSafeArrayOutArg(aFlags));
5138 return rc;
5139#endif // VBOX_WITH_GUEST_PROPS
5140}
5141
5142STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
5143 ComSafeArrayOut(IMediumAttachment*, aAttachments))
5144{
5145 MediaData::AttachmentList atts;
5146
5147 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
5148 if (FAILED(rc)) return rc;
5149
5150 SafeIfaceArray<IMediumAttachment> attachments(atts);
5151 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
5152
5153 return S_OK;
5154}
5155
5156STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
5157 LONG aControllerPort,
5158 LONG aDevice,
5159 IMediumAttachment **aAttachment)
5160{
5161 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
5162 aControllerName, aControllerPort, aDevice));
5163
5164 CheckComArgStrNotEmptyOrNull(aControllerName);
5165 CheckComArgOutPointerValid(aAttachment);
5166
5167 AutoCaller autoCaller(this);
5168 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5169
5170 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5171
5172 *aAttachment = NULL;
5173
5174 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
5175 aControllerName,
5176 aControllerPort,
5177 aDevice);
5178 if (pAttach.isNull())
5179 return setError(VBOX_E_OBJECT_NOT_FOUND,
5180 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
5181 aDevice, aControllerPort, aControllerName);
5182
5183 pAttach.queryInterfaceTo(aAttachment);
5184
5185 return S_OK;
5186}
5187
5188STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
5189 StorageBus_T aConnectionType,
5190 IStorageController **controller)
5191{
5192 CheckComArgStrNotEmptyOrNull(aName);
5193
5194 if ( (aConnectionType <= StorageBus_Null)
5195 || (aConnectionType > StorageBus_SAS))
5196 return setError(E_INVALIDARG,
5197 tr("Invalid connection type: %d"),
5198 aConnectionType);
5199
5200 AutoCaller autoCaller(this);
5201 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5202
5203 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5204
5205 HRESULT rc = checkStateDependency(MutableStateDep);
5206 if (FAILED(rc)) return rc;
5207
5208 /* try to find one with the name first. */
5209 ComObjPtr<StorageController> ctrl;
5210
5211 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
5212 if (SUCCEEDED(rc))
5213 return setError(VBOX_E_OBJECT_IN_USE,
5214 tr("Storage controller named '%ls' already exists"),
5215 aName);
5216
5217 ctrl.createObject();
5218
5219 /* get a new instance number for the storage controller */
5220 ULONG ulInstance = 0;
5221 bool fBootable = true;
5222 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5223 it != mStorageControllers->end();
5224 ++it)
5225 {
5226 if ((*it)->getStorageBus() == aConnectionType)
5227 {
5228 ULONG ulCurInst = (*it)->getInstance();
5229
5230 if (ulCurInst >= ulInstance)
5231 ulInstance = ulCurInst + 1;
5232
5233 /* Only one controller of each type can be marked as bootable. */
5234 if ((*it)->getBootable())
5235 fBootable = false;
5236 }
5237 }
5238
5239 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
5240 if (FAILED(rc)) return rc;
5241
5242 setModified(IsModified_Storage);
5243 mStorageControllers.backup();
5244 mStorageControllers->push_back(ctrl);
5245
5246 ctrl.queryInterfaceTo(controller);
5247
5248 /* inform the direct session if any */
5249 alock.leave();
5250 onStorageControllerChange();
5251
5252 return S_OK;
5253}
5254
5255STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
5256 IStorageController **aStorageController)
5257{
5258 CheckComArgStrNotEmptyOrNull(aName);
5259
5260 AutoCaller autoCaller(this);
5261 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5262
5263 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5264
5265 ComObjPtr<StorageController> ctrl;
5266
5267 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5268 if (SUCCEEDED(rc))
5269 ctrl.queryInterfaceTo(aStorageController);
5270
5271 return rc;
5272}
5273
5274STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
5275 IStorageController **aStorageController)
5276{
5277 AutoCaller autoCaller(this);
5278 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5279
5280 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5281
5282 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5283 it != mStorageControllers->end();
5284 ++it)
5285 {
5286 if ((*it)->getInstance() == aInstance)
5287 {
5288 (*it).queryInterfaceTo(aStorageController);
5289 return S_OK;
5290 }
5291 }
5292
5293 return setError(VBOX_E_OBJECT_NOT_FOUND,
5294 tr("Could not find a storage controller with instance number '%lu'"),
5295 aInstance);
5296}
5297
5298STDMETHODIMP Machine::SetStorageControllerBootable(IN_BSTR aName, BOOL fBootable)
5299{
5300 AutoCaller autoCaller(this);
5301 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5302
5303 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5304
5305 HRESULT rc = checkStateDependency(MutableStateDep);
5306 if (FAILED(rc)) return rc;
5307
5308 ComObjPtr<StorageController> ctrl;
5309
5310 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5311 if (SUCCEEDED(rc))
5312 {
5313 /* Ensure that only one controller of each type is marked as bootable. */
5314 if (fBootable == TRUE)
5315 {
5316 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5317 it != mStorageControllers->end();
5318 ++it)
5319 {
5320 ComObjPtr<StorageController> aCtrl = (*it);
5321
5322 if ( (aCtrl->getName() != Utf8Str(aName))
5323 && aCtrl->getBootable() == TRUE
5324 && aCtrl->getStorageBus() == ctrl->getStorageBus()
5325 && aCtrl->getControllerType() == ctrl->getControllerType())
5326 {
5327 aCtrl->setBootable(FALSE);
5328 break;
5329 }
5330 }
5331 }
5332
5333 if (SUCCEEDED(rc))
5334 {
5335 ctrl->setBootable(fBootable);
5336 setModified(IsModified_Storage);
5337 }
5338 }
5339
5340 if (SUCCEEDED(rc))
5341 {
5342 /* inform the direct session if any */
5343 alock.leave();
5344 onStorageControllerChange();
5345 }
5346
5347 return rc;
5348}
5349
5350STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5351{
5352 CheckComArgStrNotEmptyOrNull(aName);
5353
5354 AutoCaller autoCaller(this);
5355 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5356
5357 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5358
5359 HRESULT rc = checkStateDependency(MutableStateDep);
5360 if (FAILED(rc)) return rc;
5361
5362 ComObjPtr<StorageController> ctrl;
5363 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5364 if (FAILED(rc)) return rc;
5365
5366 /* We can remove the controller only if there is no device attached. */
5367 /* check if the device slot is already busy */
5368 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5369 it != mMediaData->mAttachments.end();
5370 ++it)
5371 {
5372 if ((*it)->getControllerName() == aName)
5373 return setError(VBOX_E_OBJECT_IN_USE,
5374 tr("Storage controller named '%ls' has still devices attached"),
5375 aName);
5376 }
5377
5378 /* We can remove it now. */
5379 setModified(IsModified_Storage);
5380 mStorageControllers.backup();
5381
5382 ctrl->unshare();
5383
5384 mStorageControllers->remove(ctrl);
5385
5386 /* inform the direct session if any */
5387 alock.leave();
5388 onStorageControllerChange();
5389
5390 return S_OK;
5391}
5392
5393STDMETHODIMP Machine::QuerySavedGuestSize(ULONG uScreenId, ULONG *puWidth, ULONG *puHeight)
5394{
5395 LogFlowThisFunc(("\n"));
5396
5397 CheckComArgNotNull(puWidth);
5398 CheckComArgNotNull(puHeight);
5399
5400 uint32_t u32Width = 0;
5401 uint32_t u32Height = 0;
5402
5403 int vrc = readSavedGuestSize(mSSData->mStateFilePath, uScreenId, &u32Width, &u32Height);
5404 if (RT_FAILURE(vrc))
5405 return setError(VBOX_E_IPRT_ERROR,
5406 tr("Saved guest size is not available (%Rrc)"),
5407 vrc);
5408
5409 *puWidth = u32Width;
5410 *puHeight = u32Height;
5411
5412 return S_OK;
5413}
5414
5415STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5416{
5417 LogFlowThisFunc(("\n"));
5418
5419 CheckComArgNotNull(aSize);
5420 CheckComArgNotNull(aWidth);
5421 CheckComArgNotNull(aHeight);
5422
5423 if (aScreenId != 0)
5424 return E_NOTIMPL;
5425
5426 AutoCaller autoCaller(this);
5427 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5428
5429 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5430
5431 uint8_t *pu8Data = NULL;
5432 uint32_t cbData = 0;
5433 uint32_t u32Width = 0;
5434 uint32_t u32Height = 0;
5435
5436 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5437
5438 if (RT_FAILURE(vrc))
5439 return setError(VBOX_E_IPRT_ERROR,
5440 tr("Saved screenshot data is not available (%Rrc)"),
5441 vrc);
5442
5443 *aSize = cbData;
5444 *aWidth = u32Width;
5445 *aHeight = u32Height;
5446
5447 freeSavedDisplayScreenshot(pu8Data);
5448
5449 return S_OK;
5450}
5451
5452STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5453{
5454 LogFlowThisFunc(("\n"));
5455
5456 CheckComArgNotNull(aWidth);
5457 CheckComArgNotNull(aHeight);
5458 CheckComArgOutSafeArrayPointerValid(aData);
5459
5460 if (aScreenId != 0)
5461 return E_NOTIMPL;
5462
5463 AutoCaller autoCaller(this);
5464 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5465
5466 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5467
5468 uint8_t *pu8Data = NULL;
5469 uint32_t cbData = 0;
5470 uint32_t u32Width = 0;
5471 uint32_t u32Height = 0;
5472
5473 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5474
5475 if (RT_FAILURE(vrc))
5476 return setError(VBOX_E_IPRT_ERROR,
5477 tr("Saved screenshot data is not available (%Rrc)"),
5478 vrc);
5479
5480 *aWidth = u32Width;
5481 *aHeight = u32Height;
5482
5483 com::SafeArray<BYTE> bitmap(cbData);
5484 /* Convert pixels to format expected by the API caller. */
5485 if (aBGR)
5486 {
5487 /* [0] B, [1] G, [2] R, [3] A. */
5488 for (unsigned i = 0; i < cbData; i += 4)
5489 {
5490 bitmap[i] = pu8Data[i];
5491 bitmap[i + 1] = pu8Data[i + 1];
5492 bitmap[i + 2] = pu8Data[i + 2];
5493 bitmap[i + 3] = 0xff;
5494 }
5495 }
5496 else
5497 {
5498 /* [0] R, [1] G, [2] B, [3] A. */
5499 for (unsigned i = 0; i < cbData; i += 4)
5500 {
5501 bitmap[i] = pu8Data[i + 2];
5502 bitmap[i + 1] = pu8Data[i + 1];
5503 bitmap[i + 2] = pu8Data[i];
5504 bitmap[i + 3] = 0xff;
5505 }
5506 }
5507 bitmap.detachTo(ComSafeArrayOutArg(aData));
5508
5509 freeSavedDisplayScreenshot(pu8Data);
5510
5511 return S_OK;
5512}
5513
5514
5515STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5516{
5517 LogFlowThisFunc(("\n"));
5518
5519 CheckComArgNotNull(aWidth);
5520 CheckComArgNotNull(aHeight);
5521 CheckComArgOutSafeArrayPointerValid(aData);
5522
5523 if (aScreenId != 0)
5524 return E_NOTIMPL;
5525
5526 AutoCaller autoCaller(this);
5527 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5528
5529 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5530
5531 uint8_t *pu8Data = NULL;
5532 uint32_t cbData = 0;
5533 uint32_t u32Width = 0;
5534 uint32_t u32Height = 0;
5535
5536 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5537
5538 if (RT_FAILURE(vrc))
5539 return setError(VBOX_E_IPRT_ERROR,
5540 tr("Saved screenshot data is not available (%Rrc)"),
5541 vrc);
5542
5543 *aWidth = u32Width;
5544 *aHeight = u32Height;
5545
5546 uint8_t *pu8PNG = NULL;
5547 uint32_t cbPNG = 0;
5548 uint32_t cxPNG = 0;
5549 uint32_t cyPNG = 0;
5550
5551 DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
5552
5553 com::SafeArray<BYTE> screenData(cbPNG);
5554 screenData.initFrom(pu8PNG, cbPNG);
5555 RTMemFree(pu8PNG);
5556
5557 screenData.detachTo(ComSafeArrayOutArg(aData));
5558
5559 freeSavedDisplayScreenshot(pu8Data);
5560
5561 return S_OK;
5562}
5563
5564STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5565{
5566 LogFlowThisFunc(("\n"));
5567
5568 CheckComArgNotNull(aSize);
5569 CheckComArgNotNull(aWidth);
5570 CheckComArgNotNull(aHeight);
5571
5572 if (aScreenId != 0)
5573 return E_NOTIMPL;
5574
5575 AutoCaller autoCaller(this);
5576 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5577
5578 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5579
5580 uint8_t *pu8Data = NULL;
5581 uint32_t cbData = 0;
5582 uint32_t u32Width = 0;
5583 uint32_t u32Height = 0;
5584
5585 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5586
5587 if (RT_FAILURE(vrc))
5588 return setError(VBOX_E_IPRT_ERROR,
5589 tr("Saved screenshot data is not available (%Rrc)"),
5590 vrc);
5591
5592 *aSize = cbData;
5593 *aWidth = u32Width;
5594 *aHeight = u32Height;
5595
5596 freeSavedDisplayScreenshot(pu8Data);
5597
5598 return S_OK;
5599}
5600
5601STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5602{
5603 LogFlowThisFunc(("\n"));
5604
5605 CheckComArgNotNull(aWidth);
5606 CheckComArgNotNull(aHeight);
5607 CheckComArgOutSafeArrayPointerValid(aData);
5608
5609 if (aScreenId != 0)
5610 return E_NOTIMPL;
5611
5612 AutoCaller autoCaller(this);
5613 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5614
5615 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5616
5617 uint8_t *pu8Data = NULL;
5618 uint32_t cbData = 0;
5619 uint32_t u32Width = 0;
5620 uint32_t u32Height = 0;
5621
5622 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5623
5624 if (RT_FAILURE(vrc))
5625 return setError(VBOX_E_IPRT_ERROR,
5626 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
5627 vrc);
5628
5629 *aWidth = u32Width;
5630 *aHeight = u32Height;
5631
5632 com::SafeArray<BYTE> png(cbData);
5633 png.initFrom(pu8Data, cbData);
5634 png.detachTo(ComSafeArrayOutArg(aData));
5635
5636 freeSavedDisplayScreenshot(pu8Data);
5637
5638 return S_OK;
5639}
5640
5641STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5642{
5643 HRESULT rc = S_OK;
5644 LogFlowThisFunc(("\n"));
5645
5646 AutoCaller autoCaller(this);
5647 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5648
5649 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5650
5651 if (!mHWData->mCPUHotPlugEnabled)
5652 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5653
5654 if (aCpu >= mHWData->mCPUCount)
5655 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5656
5657 if (mHWData->mCPUAttached[aCpu])
5658 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5659
5660 alock.release();
5661 rc = onCPUChange(aCpu, false);
5662 alock.acquire();
5663 if (FAILED(rc)) return rc;
5664
5665 setModified(IsModified_MachineData);
5666 mHWData.backup();
5667 mHWData->mCPUAttached[aCpu] = true;
5668
5669 /* Save settings if online */
5670 if (Global::IsOnline(mData->mMachineState))
5671 saveSettings(NULL);
5672
5673 return S_OK;
5674}
5675
5676STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5677{
5678 HRESULT rc = S_OK;
5679 LogFlowThisFunc(("\n"));
5680
5681 AutoCaller autoCaller(this);
5682 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5683
5684 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5685
5686 if (!mHWData->mCPUHotPlugEnabled)
5687 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5688
5689 if (aCpu >= SchemaDefs::MaxCPUCount)
5690 return setError(E_INVALIDARG,
5691 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5692 SchemaDefs::MaxCPUCount);
5693
5694 if (!mHWData->mCPUAttached[aCpu])
5695 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5696
5697 /* CPU 0 can't be detached */
5698 if (aCpu == 0)
5699 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5700
5701 alock.release();
5702 rc = onCPUChange(aCpu, true);
5703 alock.acquire();
5704 if (FAILED(rc)) return rc;
5705
5706 setModified(IsModified_MachineData);
5707 mHWData.backup();
5708 mHWData->mCPUAttached[aCpu] = false;
5709
5710 /* Save settings if online */
5711 if (Global::IsOnline(mData->mMachineState))
5712 saveSettings(NULL);
5713
5714 return S_OK;
5715}
5716
5717STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5718{
5719 LogFlowThisFunc(("\n"));
5720
5721 CheckComArgNotNull(aCpuAttached);
5722
5723 *aCpuAttached = false;
5724
5725 AutoCaller autoCaller(this);
5726 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5727
5728 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5729
5730 /* If hotplug is enabled the CPU is always enabled. */
5731 if (!mHWData->mCPUHotPlugEnabled)
5732 {
5733 if (aCpu < mHWData->mCPUCount)
5734 *aCpuAttached = true;
5735 }
5736 else
5737 {
5738 if (aCpu < SchemaDefs::MaxCPUCount)
5739 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5740 }
5741
5742 return S_OK;
5743}
5744
5745STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5746{
5747 CheckComArgOutPointerValid(aName);
5748
5749 AutoCaller autoCaller(this);
5750 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5751
5752 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5753
5754 Utf8Str log = queryLogFilename(aIdx);
5755 if (!RTFileExists(log.c_str()))
5756 log.setNull();
5757 log.cloneTo(aName);
5758
5759 return S_OK;
5760}
5761
5762STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
5763{
5764 LogFlowThisFunc(("\n"));
5765 CheckComArgOutSafeArrayPointerValid(aData);
5766 if (aSize < 0)
5767 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
5768
5769 AutoCaller autoCaller(this);
5770 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5771
5772 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5773
5774 HRESULT rc = S_OK;
5775 Utf8Str log = queryLogFilename(aIdx);
5776
5777 /* do not unnecessarily hold the lock while doing something which does
5778 * not need the lock and potentially takes a long time. */
5779 alock.release();
5780
5781 /* Limit the chunk size to 32K for now, as that gives better performance
5782 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5783 * One byte expands to approx. 25 bytes of breathtaking XML. */
5784 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5785 com::SafeArray<BYTE> logData(cbData);
5786
5787 RTFILE LogFile;
5788 int vrc = RTFileOpen(&LogFile, log.c_str(),
5789 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5790 if (RT_SUCCESS(vrc))
5791 {
5792 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5793 if (RT_SUCCESS(vrc))
5794 logData.resize(cbData);
5795 else
5796 rc = setError(VBOX_E_IPRT_ERROR,
5797 tr("Could not read log file '%s' (%Rrc)"),
5798 log.c_str(), vrc);
5799 RTFileClose(LogFile);
5800 }
5801 else
5802 rc = setError(VBOX_E_IPRT_ERROR,
5803 tr("Could not open log file '%s' (%Rrc)"),
5804 log.c_str(), vrc);
5805
5806 if (FAILED(rc))
5807 logData.resize(0);
5808 logData.detachTo(ComSafeArrayOutArg(aData));
5809
5810 return rc;
5811}
5812
5813/**
5814 * Currently this method doesn't attach device to the running VM,
5815 * just makes sure it's plugged on next VM start.
5816 */
5817STDMETHODIMP Machine::AttachHostPciDevice(LONG hostAddress, LONG desiredGuestAddress, BOOL /*tryToUnbind*/)
5818{
5819 AutoCaller autoCaller(this);
5820 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5821
5822 // lock scope
5823 {
5824 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5825
5826 //HRESULT rc = checkStateDependency(MutableStateDep);
5827 //if (FAILED(rc)) return rc;
5828
5829 ComObjPtr<PciDeviceAttachment> pda;
5830 char name[32];
5831
5832 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (hostAddress>>8) & 0xff, (hostAddress & 0xf8) >> 3, hostAddress & 7);
5833 Bstr bname(name);
5834 pda.createObject();
5835 pda->init(this, bname, hostAddress, desiredGuestAddress, TRUE);
5836 setModified(IsModified_MachineData);
5837 mHWData.backup();
5838 mHWData->mPciDeviceAssignments.push_back(pda);
5839 }
5840
5841 // do we need it?
5842 //saveSettings(NULL);
5843 mHWData.commit();
5844
5845 return S_OK;
5846}
5847
5848/**
5849 * Currently this method doesn't detach device from the running VM,
5850 * just makes sure it's not plugged on next VM start.
5851 */
5852STDMETHODIMP Machine::DetachHostPciDevice(LONG hostAddress)
5853{
5854 AutoCaller autoCaller(this);
5855 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5856
5857 ComObjPtr<PciDeviceAttachment> pAttach;
5858 bool fRemoved = false;
5859 HRESULT rc;
5860
5861 // lock scope
5862 {
5863 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5864
5865 rc = checkStateDependency(MutableStateDep);
5866 if (FAILED(rc)) return rc;
5867
5868 for (HWData::PciDeviceAssignmentList::iterator it = mHWData->mPciDeviceAssignments.begin();
5869 it != mHWData->mPciDeviceAssignments.end();
5870 ++it)
5871 {
5872 LONG iHostAddress = -1;
5873 pAttach = *it;
5874 pAttach->COMGETTER(HostAddress)(&iHostAddress);
5875 if (iHostAddress != -1 && iHostAddress == hostAddress)
5876 {
5877 setModified(IsModified_MachineData);
5878 mHWData.backup();
5879 mHWData->mPciDeviceAssignments.remove(pAttach);
5880 fRemoved = true;
5881 break;
5882 }
5883 }
5884 // Indeed under lock?
5885 mHWData.commit();
5886
5887 // do we need it?
5888 // saveSettings(NULL);
5889 }
5890
5891
5892 /* Fire event outside of the lock */
5893 if (fRemoved)
5894 {
5895 Assert(!pAttach.isNull());
5896 ComPtr<IEventSource> es;
5897 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
5898 Assert(SUCCEEDED(rc));
5899 Bstr mid;
5900 rc = this->COMGETTER(Id)(mid.asOutParam());
5901 Assert(SUCCEEDED(rc));
5902 fireHostPciDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
5903 }
5904
5905 return S_OK;
5906}
5907
5908STDMETHODIMP Machine::COMGETTER(PciDeviceAssignments)(ComSafeArrayOut(IPciDeviceAttachment *, aAssignments))
5909{
5910 CheckComArgOutSafeArrayPointerValid(aAssignments);
5911
5912 AutoCaller autoCaller(this);
5913 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5914
5915 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5916
5917 SafeIfaceArray<IPciDeviceAttachment> assignments(mHWData->mPciDeviceAssignments);
5918 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
5919
5920 return S_OK;
5921}
5922
5923STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
5924{
5925 CheckComArgOutPointerValid(aBandwidthControl);
5926
5927 AutoCaller autoCaller(this);
5928 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5929
5930 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
5931
5932 return S_OK;
5933}
5934
5935// public methods for internal purposes
5936/////////////////////////////////////////////////////////////////////////////
5937
5938/**
5939 * Adds the given IsModified_* flag to the dirty flags of the machine.
5940 * This must be called either during loadSettings or under the machine write lock.
5941 * @param fl
5942 */
5943void Machine::setModified(uint32_t fl)
5944{
5945 mData->flModifications |= fl;
5946}
5947
5948/**
5949 * Saves the registry entry of this machine to the given configuration node.
5950 *
5951 * @param aEntryNode Node to save the registry entry to.
5952 *
5953 * @note locks this object for reading.
5954 */
5955HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5956{
5957 AutoLimitedCaller autoCaller(this);
5958 AssertComRCReturnRC(autoCaller.rc());
5959
5960 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5961
5962 data.uuid = mData->mUuid;
5963 data.strSettingsFile = mData->m_strConfigFile;
5964
5965 return S_OK;
5966}
5967
5968/**
5969 * Calculates the absolute path of the given path taking the directory of the
5970 * machine settings file as the current directory.
5971 *
5972 * @param aPath Path to calculate the absolute path for.
5973 * @param aResult Where to put the result (used only on success, can be the
5974 * same Utf8Str instance as passed in @a aPath).
5975 * @return IPRT result.
5976 *
5977 * @note Locks this object for reading.
5978 */
5979int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5980{
5981 AutoCaller autoCaller(this);
5982 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5983
5984 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5985
5986 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5987
5988 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5989
5990 strSettingsDir.stripFilename();
5991 char folder[RTPATH_MAX];
5992 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5993 if (RT_SUCCESS(vrc))
5994 aResult = folder;
5995
5996 return vrc;
5997}
5998
5999/**
6000 * Copies strSource to strTarget, making it relative to the machine folder
6001 * if it is a subdirectory thereof, or simply copying it otherwise.
6002 *
6003 * @param strSource Path to evaluate and copy.
6004 * @param strTarget Buffer to receive target path.
6005 *
6006 * @note Locks this object for reading.
6007 */
6008void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6009 Utf8Str &strTarget)
6010{
6011 AutoCaller autoCaller(this);
6012 AssertComRCReturn(autoCaller.rc(), (void)0);
6013
6014 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6015
6016 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6017 // use strTarget as a temporary buffer to hold the machine settings dir
6018 strTarget = mData->m_strConfigFileFull;
6019 strTarget.stripFilename();
6020 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6021 // is relative: then append what's left
6022 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6023 else
6024 // is not relative: then overwrite
6025 strTarget = strSource;
6026}
6027
6028/**
6029 * Returns the full path to the machine's log folder in the
6030 * \a aLogFolder argument.
6031 */
6032void Machine::getLogFolder(Utf8Str &aLogFolder)
6033{
6034 AutoCaller autoCaller(this);
6035 AssertComRCReturnVoid(autoCaller.rc());
6036
6037 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6038
6039 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6040 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6041 aLogFolder.append(RTPATH_DELIMITER);
6042 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6043}
6044
6045/**
6046 * Returns the full path to the machine's log file for an given index.
6047 */
6048Utf8Str Machine::queryLogFilename(ULONG idx)
6049{
6050 Utf8Str logFolder;
6051 getLogFolder(logFolder);
6052 Assert(logFolder.length());
6053 Utf8Str log;
6054 if (idx == 0)
6055 log = Utf8StrFmt("%s%cVBox.log",
6056 logFolder.c_str(), RTPATH_DELIMITER);
6057 else
6058 log = Utf8StrFmt("%s%cVBox.log.%d",
6059 logFolder.c_str(), RTPATH_DELIMITER, idx);
6060 return log;
6061}
6062
6063/**
6064 * @note Locks this object for writing, calls the client process
6065 * (inside the lock).
6066 */
6067HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
6068 IN_BSTR aType,
6069 IN_BSTR aEnvironment,
6070 ProgressProxy *aProgress)
6071{
6072 LogFlowThisFuncEnter();
6073
6074 AssertReturn(aControl, E_FAIL);
6075 AssertReturn(aProgress, E_FAIL);
6076
6077 AutoCaller autoCaller(this);
6078 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6079
6080 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6081
6082 if (!mData->mRegistered)
6083 return setError(E_UNEXPECTED,
6084 tr("The machine '%s' is not registered"),
6085 mUserData->s.strName.c_str());
6086
6087 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6088
6089 if ( mData->mSession.mState == SessionState_Locked
6090 || mData->mSession.mState == SessionState_Spawning
6091 || mData->mSession.mState == SessionState_Unlocking)
6092 return setError(VBOX_E_INVALID_OBJECT_STATE,
6093 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6094 mUserData->s.strName.c_str());
6095
6096 /* may not be busy */
6097 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6098
6099 /* get the path to the executable */
6100 char szPath[RTPATH_MAX];
6101 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6102 size_t sz = strlen(szPath);
6103 szPath[sz++] = RTPATH_DELIMITER;
6104 szPath[sz] = 0;
6105 char *cmd = szPath + sz;
6106 sz = RTPATH_MAX - sz;
6107
6108 int vrc = VINF_SUCCESS;
6109 RTPROCESS pid = NIL_RTPROCESS;
6110
6111 RTENV env = RTENV_DEFAULT;
6112
6113 if (aEnvironment != NULL && *aEnvironment)
6114 {
6115 char *newEnvStr = NULL;
6116
6117 do
6118 {
6119 /* clone the current environment */
6120 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6121 AssertRCBreakStmt(vrc2, vrc = vrc2);
6122
6123 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
6124 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6125
6126 /* put new variables to the environment
6127 * (ignore empty variable names here since RTEnv API
6128 * intentionally doesn't do that) */
6129 char *var = newEnvStr;
6130 for (char *p = newEnvStr; *p; ++p)
6131 {
6132 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6133 {
6134 *p = '\0';
6135 if (*var)
6136 {
6137 char *val = strchr(var, '=');
6138 if (val)
6139 {
6140 *val++ = '\0';
6141 vrc2 = RTEnvSetEx(env, var, val);
6142 }
6143 else
6144 vrc2 = RTEnvUnsetEx(env, var);
6145 if (RT_FAILURE(vrc2))
6146 break;
6147 }
6148 var = p + 1;
6149 }
6150 }
6151 if (RT_SUCCESS(vrc2) && *var)
6152 vrc2 = RTEnvPutEx(env, var);
6153
6154 AssertRCBreakStmt(vrc2, vrc = vrc2);
6155 }
6156 while (0);
6157
6158 if (newEnvStr != NULL)
6159 RTStrFree(newEnvStr);
6160 }
6161
6162 Utf8Str strType(aType);
6163
6164 /* Qt is default */
6165#ifdef VBOX_WITH_QTGUI
6166 if (strType == "gui" || strType == "GUI/Qt")
6167 {
6168# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6169 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6170# else
6171 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6172# endif
6173 Assert(sz >= sizeof(VirtualBox_exe));
6174 strcpy(cmd, VirtualBox_exe);
6175
6176 Utf8Str idStr = mData->mUuid.toString();
6177 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6178 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6179 }
6180#else /* !VBOX_WITH_QTGUI */
6181 if (0)
6182 ;
6183#endif /* VBOX_WITH_QTGUI */
6184
6185 else
6186
6187#ifdef VBOX_WITH_VBOXSDL
6188 if (strType == "sdl" || strType == "GUI/SDL")
6189 {
6190 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6191 Assert(sz >= sizeof(VBoxSDL_exe));
6192 strcpy(cmd, VBoxSDL_exe);
6193
6194 Utf8Str idStr = mData->mUuid.toString();
6195 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6196 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6197 }
6198#else /* !VBOX_WITH_VBOXSDL */
6199 if (0)
6200 ;
6201#endif /* !VBOX_WITH_VBOXSDL */
6202
6203 else
6204
6205#ifdef VBOX_WITH_HEADLESS
6206 if ( strType == "headless"
6207 || strType == "capture"
6208 || strType == "vrdp" /* Deprecated. Same as headless. */
6209 )
6210 {
6211 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6212 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6213 * and a VM works even if the server has not been installed.
6214 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6215 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6216 * differently in 4.0 and 3.x.
6217 */
6218 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6219 Assert(sz >= sizeof(VBoxHeadless_exe));
6220 strcpy(cmd, VBoxHeadless_exe);
6221
6222 Utf8Str idStr = mData->mUuid.toString();
6223 /* Leave space for "--capture" arg. */
6224 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0, 0 };
6225 if (strType == "capture")
6226 {
6227 unsigned pos = RT_ELEMENTS(args) - 2;
6228 args[pos] = "--capture";
6229 }
6230 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6231 }
6232#else /* !VBOX_WITH_HEADLESS */
6233 if (0)
6234 ;
6235#endif /* !VBOX_WITH_HEADLESS */
6236 else
6237 {
6238 RTEnvDestroy(env);
6239 return setError(E_INVALIDARG,
6240 tr("Invalid session type: '%s'"),
6241 strType.c_str());
6242 }
6243
6244 RTEnvDestroy(env);
6245
6246 if (RT_FAILURE(vrc))
6247 return setError(VBOX_E_IPRT_ERROR,
6248 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6249 mUserData->s.strName.c_str(), vrc);
6250
6251 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6252
6253 /*
6254 * Note that we don't leave the lock here before calling the client,
6255 * because it doesn't need to call us back if called with a NULL argument.
6256 * Leaving the lock here is dangerous because we didn't prepare the
6257 * launch data yet, but the client we've just started may happen to be
6258 * too fast and call openSession() that will fail (because of PID, etc.),
6259 * so that the Machine will never get out of the Spawning session state.
6260 */
6261
6262 /* inform the session that it will be a remote one */
6263 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6264 HRESULT rc = aControl->AssignMachine(NULL);
6265 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6266
6267 if (FAILED(rc))
6268 {
6269 /* restore the session state */
6270 mData->mSession.mState = SessionState_Unlocked;
6271 /* The failure may occur w/o any error info (from RPC), so provide one */
6272 return setError(VBOX_E_VM_ERROR,
6273 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6274 }
6275
6276 /* attach launch data to the machine */
6277 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6278 mData->mSession.mRemoteControls.push_back (aControl);
6279 mData->mSession.mProgress = aProgress;
6280 mData->mSession.mPid = pid;
6281 mData->mSession.mState = SessionState_Spawning;
6282 mData->mSession.mType = strType;
6283
6284 LogFlowThisFuncLeave();
6285 return S_OK;
6286}
6287
6288/**
6289 * Returns @c true if the given machine has an open direct session and returns
6290 * the session machine instance and additional session data (on some platforms)
6291 * if so.
6292 *
6293 * Note that when the method returns @c false, the arguments remain unchanged.
6294 *
6295 * @param aMachine Session machine object.
6296 * @param aControl Direct session control object (optional).
6297 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6298 *
6299 * @note locks this object for reading.
6300 */
6301#if defined(RT_OS_WINDOWS)
6302bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6303 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6304 HANDLE *aIPCSem /*= NULL*/,
6305 bool aAllowClosing /*= false*/)
6306#elif defined(RT_OS_OS2)
6307bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6308 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6309 HMTX *aIPCSem /*= NULL*/,
6310 bool aAllowClosing /*= false*/)
6311#else
6312bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6313 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6314 bool aAllowClosing /*= false*/)
6315#endif
6316{
6317 AutoLimitedCaller autoCaller(this);
6318 AssertComRCReturn(autoCaller.rc(), false);
6319
6320 /* just return false for inaccessible machines */
6321 if (autoCaller.state() != Ready)
6322 return false;
6323
6324 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6325
6326 if ( mData->mSession.mState == SessionState_Locked
6327 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6328 )
6329 {
6330 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6331
6332 aMachine = mData->mSession.mMachine;
6333
6334 if (aControl != NULL)
6335 *aControl = mData->mSession.mDirectControl;
6336
6337#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6338 /* Additional session data */
6339 if (aIPCSem != NULL)
6340 *aIPCSem = aMachine->mIPCSem;
6341#endif
6342 return true;
6343 }
6344
6345 return false;
6346}
6347
6348/**
6349 * Returns @c true if the given machine has an spawning direct session and
6350 * returns and additional session data (on some platforms) if so.
6351 *
6352 * Note that when the method returns @c false, the arguments remain unchanged.
6353 *
6354 * @param aPID PID of the spawned direct session process.
6355 *
6356 * @note locks this object for reading.
6357 */
6358#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6359bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6360#else
6361bool Machine::isSessionSpawning()
6362#endif
6363{
6364 AutoLimitedCaller autoCaller(this);
6365 AssertComRCReturn(autoCaller.rc(), false);
6366
6367 /* just return false for inaccessible machines */
6368 if (autoCaller.state() != Ready)
6369 return false;
6370
6371 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6372
6373 if (mData->mSession.mState == SessionState_Spawning)
6374 {
6375#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6376 /* Additional session data */
6377 if (aPID != NULL)
6378 {
6379 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6380 *aPID = mData->mSession.mPid;
6381 }
6382#endif
6383 return true;
6384 }
6385
6386 return false;
6387}
6388
6389/**
6390 * Called from the client watcher thread to check for unexpected client process
6391 * death during Session_Spawning state (e.g. before it successfully opened a
6392 * direct session).
6393 *
6394 * On Win32 and on OS/2, this method is called only when we've got the
6395 * direct client's process termination notification, so it always returns @c
6396 * true.
6397 *
6398 * On other platforms, this method returns @c true if the client process is
6399 * terminated and @c false if it's still alive.
6400 *
6401 * @note Locks this object for writing.
6402 */
6403bool Machine::checkForSpawnFailure()
6404{
6405 AutoCaller autoCaller(this);
6406 if (!autoCaller.isOk())
6407 {
6408 /* nothing to do */
6409 LogFlowThisFunc(("Already uninitialized!\n"));
6410 return true;
6411 }
6412
6413 /* VirtualBox::addProcessToReap() needs a write lock */
6414 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6415
6416 if (mData->mSession.mState != SessionState_Spawning)
6417 {
6418 /* nothing to do */
6419 LogFlowThisFunc(("Not spawning any more!\n"));
6420 return true;
6421 }
6422
6423 HRESULT rc = S_OK;
6424
6425#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6426
6427 /* the process was already unexpectedly terminated, we just need to set an
6428 * error and finalize session spawning */
6429 rc = setError(E_FAIL,
6430 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6431 getName().c_str());
6432#else
6433
6434 /* PID not yet initialized, skip check. */
6435 if (mData->mSession.mPid == NIL_RTPROCESS)
6436 return false;
6437
6438 RTPROCSTATUS status;
6439 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6440 &status);
6441
6442 if (vrc != VERR_PROCESS_RUNNING)
6443 {
6444 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6445 rc = setError(E_FAIL,
6446 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6447 getName().c_str(), status.iStatus);
6448 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6449 rc = setError(E_FAIL,
6450 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6451 getName().c_str(), status.iStatus);
6452 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6453 rc = setError(E_FAIL,
6454 tr("The virtual machine '%s' has terminated abnormally"),
6455 getName().c_str(), status.iStatus);
6456 else
6457 rc = setError(E_FAIL,
6458 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6459 getName().c_str(), rc);
6460 }
6461
6462#endif
6463
6464 if (FAILED(rc))
6465 {
6466 /* Close the remote session, remove the remote control from the list
6467 * and reset session state to Closed (@note keep the code in sync with
6468 * the relevant part in checkForSpawnFailure()). */
6469
6470 Assert(mData->mSession.mRemoteControls.size() == 1);
6471 if (mData->mSession.mRemoteControls.size() == 1)
6472 {
6473 ErrorInfoKeeper eik;
6474 mData->mSession.mRemoteControls.front()->Uninitialize();
6475 }
6476
6477 mData->mSession.mRemoteControls.clear();
6478 mData->mSession.mState = SessionState_Unlocked;
6479
6480 /* finalize the progress after setting the state */
6481 if (!mData->mSession.mProgress.isNull())
6482 {
6483 mData->mSession.mProgress->notifyComplete(rc);
6484 mData->mSession.mProgress.setNull();
6485 }
6486
6487 mParent->addProcessToReap(mData->mSession.mPid);
6488 mData->mSession.mPid = NIL_RTPROCESS;
6489
6490 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6491 return true;
6492 }
6493
6494 return false;
6495}
6496
6497/**
6498 * Checks whether the machine can be registered. If so, commits and saves
6499 * all settings.
6500 *
6501 * @note Must be called from mParent's write lock. Locks this object and
6502 * children for writing.
6503 */
6504HRESULT Machine::prepareRegister()
6505{
6506 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6507
6508 AutoLimitedCaller autoCaller(this);
6509 AssertComRCReturnRC(autoCaller.rc());
6510
6511 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6512
6513 /* wait for state dependents to drop to zero */
6514 ensureNoStateDependencies();
6515
6516 if (!mData->mAccessible)
6517 return setError(VBOX_E_INVALID_OBJECT_STATE,
6518 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6519 mUserData->s.strName.c_str(),
6520 mData->mUuid.toString().c_str());
6521
6522 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6523
6524 if (mData->mRegistered)
6525 return setError(VBOX_E_INVALID_OBJECT_STATE,
6526 tr("The machine '%s' with UUID {%s} is already registered"),
6527 mUserData->s.strName.c_str(),
6528 mData->mUuid.toString().c_str());
6529
6530 HRESULT rc = S_OK;
6531 // Ensure the settings are saved. If we are going to be registered and
6532 // no config file exists yet, create it by calling saveSettings() too.
6533 if ( (mData->flModifications)
6534 || (!mData->pMachineConfigFile->fileExists())
6535 )
6536 {
6537 rc = saveSettings(NULL);
6538 // no need to check whether VirtualBox.xml needs saving too since
6539 // we can't have a machine XML file rename pending
6540 if (FAILED(rc)) return rc;
6541 }
6542
6543 /* more config checking goes here */
6544
6545 if (SUCCEEDED(rc))
6546 {
6547 /* we may have had implicit modifications we want to fix on success */
6548 commit();
6549
6550 mData->mRegistered = true;
6551 }
6552 else
6553 {
6554 /* we may have had implicit modifications we want to cancel on failure*/
6555 rollback(false /* aNotify */);
6556 }
6557
6558 return rc;
6559}
6560
6561/**
6562 * Increases the number of objects dependent on the machine state or on the
6563 * registered state. Guarantees that these two states will not change at least
6564 * until #releaseStateDependency() is called.
6565 *
6566 * Depending on the @a aDepType value, additional state checks may be made.
6567 * These checks will set extended error info on failure. See
6568 * #checkStateDependency() for more info.
6569 *
6570 * If this method returns a failure, the dependency is not added and the caller
6571 * is not allowed to rely on any particular machine state or registration state
6572 * value and may return the failed result code to the upper level.
6573 *
6574 * @param aDepType Dependency type to add.
6575 * @param aState Current machine state (NULL if not interested).
6576 * @param aRegistered Current registered state (NULL if not interested).
6577 *
6578 * @note Locks this object for writing.
6579 */
6580HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6581 MachineState_T *aState /* = NULL */,
6582 BOOL *aRegistered /* = NULL */)
6583{
6584 AutoCaller autoCaller(this);
6585 AssertComRCReturnRC(autoCaller.rc());
6586
6587 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6588
6589 HRESULT rc = checkStateDependency(aDepType);
6590 if (FAILED(rc)) return rc;
6591
6592 {
6593 if (mData->mMachineStateChangePending != 0)
6594 {
6595 /* ensureNoStateDependencies() is waiting for state dependencies to
6596 * drop to zero so don't add more. It may make sense to wait a bit
6597 * and retry before reporting an error (since the pending state
6598 * transition should be really quick) but let's just assert for
6599 * now to see if it ever happens on practice. */
6600
6601 AssertFailed();
6602
6603 return setError(E_ACCESSDENIED,
6604 tr("Machine state change is in progress. Please retry the operation later."));
6605 }
6606
6607 ++mData->mMachineStateDeps;
6608 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6609 }
6610
6611 if (aState)
6612 *aState = mData->mMachineState;
6613 if (aRegistered)
6614 *aRegistered = mData->mRegistered;
6615
6616 return S_OK;
6617}
6618
6619/**
6620 * Decreases the number of objects dependent on the machine state.
6621 * Must always complete the #addStateDependency() call after the state
6622 * dependency is no more necessary.
6623 */
6624void Machine::releaseStateDependency()
6625{
6626 AutoCaller autoCaller(this);
6627 AssertComRCReturnVoid(autoCaller.rc());
6628
6629 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6630
6631 /* releaseStateDependency() w/o addStateDependency()? */
6632 AssertReturnVoid(mData->mMachineStateDeps != 0);
6633 -- mData->mMachineStateDeps;
6634
6635 if (mData->mMachineStateDeps == 0)
6636 {
6637 /* inform ensureNoStateDependencies() that there are no more deps */
6638 if (mData->mMachineStateChangePending != 0)
6639 {
6640 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6641 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6642 }
6643 }
6644}
6645
6646// protected methods
6647/////////////////////////////////////////////////////////////////////////////
6648
6649/**
6650 * Performs machine state checks based on the @a aDepType value. If a check
6651 * fails, this method will set extended error info, otherwise it will return
6652 * S_OK. It is supposed, that on failure, the caller will immediately return
6653 * the return value of this method to the upper level.
6654 *
6655 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6656 *
6657 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6658 * current state of this machine object allows to change settings of the
6659 * machine (i.e. the machine is not registered, or registered but not running
6660 * and not saved). It is useful to call this method from Machine setters
6661 * before performing any change.
6662 *
6663 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6664 * as for MutableStateDep except that if the machine is saved, S_OK is also
6665 * returned. This is useful in setters which allow changing machine
6666 * properties when it is in the saved state.
6667 *
6668 * @param aDepType Dependency type to check.
6669 *
6670 * @note Non Machine based classes should use #addStateDependency() and
6671 * #releaseStateDependency() methods or the smart AutoStateDependency
6672 * template.
6673 *
6674 * @note This method must be called from under this object's read or write
6675 * lock.
6676 */
6677HRESULT Machine::checkStateDependency(StateDependency aDepType)
6678{
6679 switch (aDepType)
6680 {
6681 case AnyStateDep:
6682 {
6683 break;
6684 }
6685 case MutableStateDep:
6686 {
6687 if ( mData->mRegistered
6688 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6689 || ( mData->mMachineState != MachineState_Paused
6690 && mData->mMachineState != MachineState_Running
6691 && mData->mMachineState != MachineState_Aborted
6692 && mData->mMachineState != MachineState_Teleported
6693 && mData->mMachineState != MachineState_PoweredOff
6694 )
6695 )
6696 )
6697 return setError(VBOX_E_INVALID_VM_STATE,
6698 tr("The machine is not mutable (state is %s)"),
6699 Global::stringifyMachineState(mData->mMachineState));
6700 break;
6701 }
6702 case MutableOrSavedStateDep:
6703 {
6704 if ( mData->mRegistered
6705 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6706 || ( mData->mMachineState != MachineState_Paused
6707 && mData->mMachineState != MachineState_Running
6708 && mData->mMachineState != MachineState_Aborted
6709 && mData->mMachineState != MachineState_Teleported
6710 && mData->mMachineState != MachineState_Saved
6711 && mData->mMachineState != MachineState_PoweredOff
6712 )
6713 )
6714 )
6715 return setError(VBOX_E_INVALID_VM_STATE,
6716 tr("The machine is not mutable (state is %s)"),
6717 Global::stringifyMachineState(mData->mMachineState));
6718 break;
6719 }
6720 }
6721
6722 return S_OK;
6723}
6724
6725/**
6726 * Helper to initialize all associated child objects and allocate data
6727 * structures.
6728 *
6729 * This method must be called as a part of the object's initialization procedure
6730 * (usually done in the #init() method).
6731 *
6732 * @note Must be called only from #init() or from #registeredInit().
6733 */
6734HRESULT Machine::initDataAndChildObjects()
6735{
6736 AutoCaller autoCaller(this);
6737 AssertComRCReturnRC(autoCaller.rc());
6738 AssertComRCReturn(autoCaller.state() == InInit ||
6739 autoCaller.state() == Limited, E_FAIL);
6740
6741 AssertReturn(!mData->mAccessible, E_FAIL);
6742
6743 /* allocate data structures */
6744 mSSData.allocate();
6745 mUserData.allocate();
6746 mHWData.allocate();
6747 mMediaData.allocate();
6748 mStorageControllers.allocate();
6749
6750 /* initialize mOSTypeId */
6751 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6752
6753 /* create associated BIOS settings object */
6754 unconst(mBIOSSettings).createObject();
6755 mBIOSSettings->init(this);
6756
6757 /* create an associated VRDE object (default is disabled) */
6758 unconst(mVRDEServer).createObject();
6759 mVRDEServer->init(this);
6760
6761 /* create associated serial port objects */
6762 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6763 {
6764 unconst(mSerialPorts[slot]).createObject();
6765 mSerialPorts[slot]->init(this, slot);
6766 }
6767
6768 /* create associated parallel port objects */
6769 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6770 {
6771 unconst(mParallelPorts[slot]).createObject();
6772 mParallelPorts[slot]->init(this, slot);
6773 }
6774
6775 /* create the audio adapter object (always present, default is disabled) */
6776 unconst(mAudioAdapter).createObject();
6777 mAudioAdapter->init(this);
6778
6779 /* create the USB controller object (always present, default is disabled) */
6780 unconst(mUSBController).createObject();
6781 mUSBController->init(this);
6782
6783 /* create associated network adapter objects */
6784 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6785 {
6786 unconst(mNetworkAdapters[slot]).createObject();
6787 mNetworkAdapters[slot]->init(this, slot);
6788 }
6789
6790 /* create the bandwidth control */
6791 unconst(mBandwidthControl).createObject();
6792 mBandwidthControl->init(this);
6793
6794 return S_OK;
6795}
6796
6797/**
6798 * Helper to uninitialize all associated child objects and to free all data
6799 * structures.
6800 *
6801 * This method must be called as a part of the object's uninitialization
6802 * procedure (usually done in the #uninit() method).
6803 *
6804 * @note Must be called only from #uninit() or from #registeredInit().
6805 */
6806void Machine::uninitDataAndChildObjects()
6807{
6808 AutoCaller autoCaller(this);
6809 AssertComRCReturnVoid(autoCaller.rc());
6810 AssertComRCReturnVoid( autoCaller.state() == InUninit
6811 || autoCaller.state() == Limited);
6812
6813 /* tell all our other child objects we've been uninitialized */
6814 if (mBandwidthControl)
6815 {
6816 mBandwidthControl->uninit();
6817 unconst(mBandwidthControl).setNull();
6818 }
6819
6820 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6821 {
6822 if (mNetworkAdapters[slot])
6823 {
6824 mNetworkAdapters[slot]->uninit();
6825 unconst(mNetworkAdapters[slot]).setNull();
6826 }
6827 }
6828
6829 if (mUSBController)
6830 {
6831 mUSBController->uninit();
6832 unconst(mUSBController).setNull();
6833 }
6834
6835 if (mAudioAdapter)
6836 {
6837 mAudioAdapter->uninit();
6838 unconst(mAudioAdapter).setNull();
6839 }
6840
6841 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6842 {
6843 if (mParallelPorts[slot])
6844 {
6845 mParallelPorts[slot]->uninit();
6846 unconst(mParallelPorts[slot]).setNull();
6847 }
6848 }
6849
6850 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6851 {
6852 if (mSerialPorts[slot])
6853 {
6854 mSerialPorts[slot]->uninit();
6855 unconst(mSerialPorts[slot]).setNull();
6856 }
6857 }
6858
6859 if (mVRDEServer)
6860 {
6861 mVRDEServer->uninit();
6862 unconst(mVRDEServer).setNull();
6863 }
6864
6865 if (mBIOSSettings)
6866 {
6867 mBIOSSettings->uninit();
6868 unconst(mBIOSSettings).setNull();
6869 }
6870
6871 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6872 * instance is uninitialized; SessionMachine instances refer to real
6873 * Machine hard disks). This is necessary for a clean re-initialization of
6874 * the VM after successfully re-checking the accessibility state. Note
6875 * that in case of normal Machine or SnapshotMachine uninitialization (as
6876 * a result of unregistering or deleting the snapshot), outdated hard
6877 * disk attachments will already be uninitialized and deleted, so this
6878 * code will not affect them. */
6879 if ( !!mMediaData
6880 && (!isSessionMachine())
6881 )
6882 {
6883 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6884 it != mMediaData->mAttachments.end();
6885 ++it)
6886 {
6887 ComObjPtr<Medium> hd = (*it)->getMedium();
6888 if (hd.isNull())
6889 continue;
6890 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6891 AssertComRC(rc);
6892 }
6893 }
6894
6895 if (!isSessionMachine() && !isSnapshotMachine())
6896 {
6897 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6898 if (mData->mFirstSnapshot)
6899 {
6900 // snapshots tree is protected by media write lock; strictly
6901 // this isn't necessary here since we're deleting the entire
6902 // machine, but otherwise we assert in Snapshot::uninit()
6903 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6904 mData->mFirstSnapshot->uninit();
6905 mData->mFirstSnapshot.setNull();
6906 }
6907
6908 mData->mCurrentSnapshot.setNull();
6909 }
6910
6911 /* free data structures (the essential mData structure is not freed here
6912 * since it may be still in use) */
6913 mMediaData.free();
6914 mStorageControllers.free();
6915 mHWData.free();
6916 mUserData.free();
6917 mSSData.free();
6918}
6919
6920/**
6921 * Returns a pointer to the Machine object for this machine that acts like a
6922 * parent for complex machine data objects such as shared folders, etc.
6923 *
6924 * For primary Machine objects and for SnapshotMachine objects, returns this
6925 * object's pointer itself. For SessionMachine objects, returns the peer
6926 * (primary) machine pointer.
6927 */
6928Machine* Machine::getMachine()
6929{
6930 if (isSessionMachine())
6931 return (Machine*)mPeer;
6932 return this;
6933}
6934
6935/**
6936 * Makes sure that there are no machine state dependents. If necessary, waits
6937 * for the number of dependents to drop to zero.
6938 *
6939 * Make sure this method is called from under this object's write lock to
6940 * guarantee that no new dependents may be added when this method returns
6941 * control to the caller.
6942 *
6943 * @note Locks this object for writing. The lock will be released while waiting
6944 * (if necessary).
6945 *
6946 * @warning To be used only in methods that change the machine state!
6947 */
6948void Machine::ensureNoStateDependencies()
6949{
6950 AssertReturnVoid(isWriteLockOnCurrentThread());
6951
6952 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6953
6954 /* Wait for all state dependents if necessary */
6955 if (mData->mMachineStateDeps != 0)
6956 {
6957 /* lazy semaphore creation */
6958 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6959 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6960
6961 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6962 mData->mMachineStateDeps));
6963
6964 ++mData->mMachineStateChangePending;
6965
6966 /* reset the semaphore before waiting, the last dependent will signal
6967 * it */
6968 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6969
6970 alock.leave();
6971
6972 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6973
6974 alock.enter();
6975
6976 -- mData->mMachineStateChangePending;
6977 }
6978}
6979
6980/**
6981 * Changes the machine state and informs callbacks.
6982 *
6983 * This method is not intended to fail so it either returns S_OK or asserts (and
6984 * returns a failure).
6985 *
6986 * @note Locks this object for writing.
6987 */
6988HRESULT Machine::setMachineState(MachineState_T aMachineState)
6989{
6990 LogFlowThisFuncEnter();
6991 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6992
6993 AutoCaller autoCaller(this);
6994 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6995
6996 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6997
6998 /* wait for state dependents to drop to zero */
6999 ensureNoStateDependencies();
7000
7001 if (mData->mMachineState != aMachineState)
7002 {
7003 mData->mMachineState = aMachineState;
7004
7005 RTTimeNow(&mData->mLastStateChange);
7006
7007 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7008 }
7009
7010 LogFlowThisFuncLeave();
7011 return S_OK;
7012}
7013
7014/**
7015 * Searches for a shared folder with the given logical name
7016 * in the collection of shared folders.
7017 *
7018 * @param aName logical name of the shared folder
7019 * @param aSharedFolder where to return the found object
7020 * @param aSetError whether to set the error info if the folder is
7021 * not found
7022 * @return
7023 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7024 *
7025 * @note
7026 * must be called from under the object's lock!
7027 */
7028HRESULT Machine::findSharedFolder(CBSTR aName,
7029 ComObjPtr<SharedFolder> &aSharedFolder,
7030 bool aSetError /* = false */)
7031{
7032 bool found = false;
7033 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7034 !found && it != mHWData->mSharedFolders.end();
7035 ++it)
7036 {
7037 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
7038 found = (*it)->getName() == aName;
7039 if (found)
7040 aSharedFolder = *it;
7041 }
7042
7043 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
7044
7045 if (aSetError && !found)
7046 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
7047
7048 return rc;
7049}
7050
7051/**
7052 * Initializes all machine instance data from the given settings structures
7053 * from XML. The exception is the machine UUID which needs special handling
7054 * depending on the caller's use case, so the caller needs to set that herself.
7055 *
7056 * This gets called in several contexts during machine initialization:
7057 *
7058 * -- When machine XML exists on disk already and needs to be loaded into memory,
7059 * for example, from registeredInit() to load all registered machines on
7060 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7061 * attached to the machine should be part of some media registry already.
7062 *
7063 * -- During OVF import, when a machine config has been constructed from an
7064 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7065 * ensure that the media listed as attachments in the config (which have
7066 * been imported from the OVF) receive the correct registry ID.
7067 *
7068 * @param config Machine settings from XML.
7069 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7070 * @return
7071 */
7072HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7073 const Guid *puuidRegistry)
7074{
7075 // copy name, description, OS type, teleporter, UTC etc.
7076 mUserData->s = config.machineUserData;
7077
7078 // look up the object by Id to check it is valid
7079 ComPtr<IGuestOSType> guestOSType;
7080 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7081 guestOSType.asOutParam());
7082 if (FAILED(rc)) return rc;
7083
7084 // stateFile (optional)
7085 if (config.strStateFile.isEmpty())
7086 mSSData->mStateFilePath.setNull();
7087 else
7088 {
7089 Utf8Str stateFilePathFull(config.strStateFile);
7090 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7091 if (RT_FAILURE(vrc))
7092 return setError(E_FAIL,
7093 tr("Invalid saved state file path '%s' (%Rrc)"),
7094 config.strStateFile.c_str(),
7095 vrc);
7096 mSSData->mStateFilePath = stateFilePathFull;
7097 }
7098
7099 // snapshot folder needs special processing so set it again
7100 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7101 if (FAILED(rc)) return rc;
7102
7103 /* currentStateModified (optional, default is true) */
7104 mData->mCurrentStateModified = config.fCurrentStateModified;
7105
7106 mData->mLastStateChange = config.timeLastStateChange;
7107
7108 /*
7109 * note: all mUserData members must be assigned prior this point because
7110 * we need to commit changes in order to let mUserData be shared by all
7111 * snapshot machine instances.
7112 */
7113 mUserData.commitCopy();
7114
7115 // machine registry, if present (must be loaded before snapshots)
7116 if (config.canHaveOwnMediaRegistry())
7117 {
7118 // determine machine folder
7119 Utf8Str strMachineFolder = getSettingsFileFull();
7120 strMachineFolder.stripFilename();
7121 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7122 config.mediaRegistry,
7123 strMachineFolder);
7124 if (FAILED(rc)) return rc;
7125 }
7126
7127 /* Snapshot node (optional) */
7128 size_t cRootSnapshots;
7129 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7130 {
7131 // there must be only one root snapshot
7132 Assert(cRootSnapshots == 1);
7133
7134 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7135
7136 rc = loadSnapshot(snap,
7137 config.uuidCurrentSnapshot,
7138 NULL); // no parent == first snapshot
7139 if (FAILED(rc)) return rc;
7140 }
7141
7142 // hardware data
7143 rc = loadHardware(config.hardwareMachine);
7144 if (FAILED(rc)) return rc;
7145
7146 // load storage controllers
7147 rc = loadStorageControllers(config.storageMachine,
7148 puuidRegistry,
7149 NULL /* puuidSnapshot */);
7150 if (FAILED(rc)) return rc;
7151
7152 /*
7153 * NOTE: the assignment below must be the last thing to do,
7154 * otherwise it will be not possible to change the settings
7155 * somewhere in the code above because all setters will be
7156 * blocked by checkStateDependency(MutableStateDep).
7157 */
7158
7159 /* set the machine state to Aborted or Saved when appropriate */
7160 if (config.fAborted)
7161 {
7162 Assert(!mSSData->mStateFilePath.isEmpty());
7163 mSSData->mStateFilePath.setNull();
7164
7165 /* no need to use setMachineState() during init() */
7166 mData->mMachineState = MachineState_Aborted;
7167 }
7168 else if (!mSSData->mStateFilePath.isEmpty())
7169 {
7170 /* no need to use setMachineState() during init() */
7171 mData->mMachineState = MachineState_Saved;
7172 }
7173
7174 // after loading settings, we are no longer different from the XML on disk
7175 mData->flModifications = 0;
7176
7177 return S_OK;
7178}
7179
7180/**
7181 * Recursively loads all snapshots starting from the given.
7182 *
7183 * @param aNode <Snapshot> node.
7184 * @param aCurSnapshotId Current snapshot ID from the settings file.
7185 * @param aParentSnapshot Parent snapshot.
7186 */
7187HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7188 const Guid &aCurSnapshotId,
7189 Snapshot *aParentSnapshot)
7190{
7191 AssertReturn(!isSnapshotMachine(), E_FAIL);
7192 AssertReturn(!isSessionMachine(), E_FAIL);
7193
7194 HRESULT rc = S_OK;
7195
7196 Utf8Str strStateFile;
7197 if (!data.strStateFile.isEmpty())
7198 {
7199 /* optional */
7200 strStateFile = data.strStateFile;
7201 int vrc = calculateFullPath(strStateFile, strStateFile);
7202 if (RT_FAILURE(vrc))
7203 return setError(E_FAIL,
7204 tr("Invalid saved state file path '%s' (%Rrc)"),
7205 strStateFile.c_str(),
7206 vrc);
7207 }
7208
7209 /* create a snapshot machine object */
7210 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7211 pSnapshotMachine.createObject();
7212 rc = pSnapshotMachine->init(this,
7213 data.hardware,
7214 data.storage,
7215 data.uuid.ref(),
7216 strStateFile);
7217 if (FAILED(rc)) return rc;
7218
7219 /* create a snapshot object */
7220 ComObjPtr<Snapshot> pSnapshot;
7221 pSnapshot.createObject();
7222 /* initialize the snapshot */
7223 rc = pSnapshot->init(mParent, // VirtualBox object
7224 data.uuid,
7225 data.strName,
7226 data.strDescription,
7227 data.timestamp,
7228 pSnapshotMachine,
7229 aParentSnapshot);
7230 if (FAILED(rc)) return rc;
7231
7232 /* memorize the first snapshot if necessary */
7233 if (!mData->mFirstSnapshot)
7234 mData->mFirstSnapshot = pSnapshot;
7235
7236 /* memorize the current snapshot when appropriate */
7237 if ( !mData->mCurrentSnapshot
7238 && pSnapshot->getId() == aCurSnapshotId
7239 )
7240 mData->mCurrentSnapshot = pSnapshot;
7241
7242 // now create the children
7243 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7244 it != data.llChildSnapshots.end();
7245 ++it)
7246 {
7247 const settings::Snapshot &childData = *it;
7248 // recurse
7249 rc = loadSnapshot(childData,
7250 aCurSnapshotId,
7251 pSnapshot); // parent = the one we created above
7252 if (FAILED(rc)) return rc;
7253 }
7254
7255 return rc;
7256}
7257
7258/**
7259 * @param aNode <Hardware> node.
7260 */
7261HRESULT Machine::loadHardware(const settings::Hardware &data)
7262{
7263 AssertReturn(!isSessionMachine(), E_FAIL);
7264
7265 HRESULT rc = S_OK;
7266
7267 try
7268 {
7269 /* The hardware version attribute (optional). */
7270 mHWData->mHWVersion = data.strVersion;
7271 mHWData->mHardwareUUID = data.uuid;
7272
7273 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7274 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7275 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7276 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7277 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7278 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7279 mHWData->mPAEEnabled = data.fPAE;
7280 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7281
7282 mHWData->mCPUCount = data.cCPUs;
7283 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7284 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7285
7286 // cpu
7287 if (mHWData->mCPUHotPlugEnabled)
7288 {
7289 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7290 it != data.llCpus.end();
7291 ++it)
7292 {
7293 const settings::Cpu &cpu = *it;
7294
7295 mHWData->mCPUAttached[cpu.ulId] = true;
7296 }
7297 }
7298
7299 // cpuid leafs
7300 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7301 it != data.llCpuIdLeafs.end();
7302 ++it)
7303 {
7304 const settings::CpuIdLeaf &leaf = *it;
7305
7306 switch (leaf.ulId)
7307 {
7308 case 0x0:
7309 case 0x1:
7310 case 0x2:
7311 case 0x3:
7312 case 0x4:
7313 case 0x5:
7314 case 0x6:
7315 case 0x7:
7316 case 0x8:
7317 case 0x9:
7318 case 0xA:
7319 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7320 break;
7321
7322 case 0x80000000:
7323 case 0x80000001:
7324 case 0x80000002:
7325 case 0x80000003:
7326 case 0x80000004:
7327 case 0x80000005:
7328 case 0x80000006:
7329 case 0x80000007:
7330 case 0x80000008:
7331 case 0x80000009:
7332 case 0x8000000A:
7333 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7334 break;
7335
7336 default:
7337 /* just ignore */
7338 break;
7339 }
7340 }
7341
7342 mHWData->mMemorySize = data.ulMemorySizeMB;
7343 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7344
7345 // boot order
7346 for (size_t i = 0;
7347 i < RT_ELEMENTS(mHWData->mBootOrder);
7348 i++)
7349 {
7350 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7351 if (it == data.mapBootOrder.end())
7352 mHWData->mBootOrder[i] = DeviceType_Null;
7353 else
7354 mHWData->mBootOrder[i] = it->second;
7355 }
7356
7357 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7358 mHWData->mMonitorCount = data.cMonitors;
7359 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7360 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7361 mHWData->mFirmwareType = data.firmwareType;
7362 mHWData->mPointingHidType = data.pointingHidType;
7363 mHWData->mKeyboardHidType = data.keyboardHidType;
7364 mHWData->mChipsetType = data.chipsetType;
7365 mHWData->mHpetEnabled = data.fHpetEnabled;
7366
7367 /* VRDEServer */
7368 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7369 if (FAILED(rc)) return rc;
7370
7371 /* BIOS */
7372 rc = mBIOSSettings->loadSettings(data.biosSettings);
7373 if (FAILED(rc)) return rc;
7374
7375 /* USB Controller */
7376 rc = mUSBController->loadSettings(data.usbController);
7377 if (FAILED(rc)) return rc;
7378
7379 // network adapters
7380 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7381 it != data.llNetworkAdapters.end();
7382 ++it)
7383 {
7384 const settings::NetworkAdapter &nic = *it;
7385
7386 /* slot unicity is guaranteed by XML Schema */
7387 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7388 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7389 if (FAILED(rc)) return rc;
7390 }
7391
7392 // serial ports
7393 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7394 it != data.llSerialPorts.end();
7395 ++it)
7396 {
7397 const settings::SerialPort &s = *it;
7398
7399 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7400 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7401 if (FAILED(rc)) return rc;
7402 }
7403
7404 // parallel ports (optional)
7405 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7406 it != data.llParallelPorts.end();
7407 ++it)
7408 {
7409 const settings::ParallelPort &p = *it;
7410
7411 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7412 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7413 if (FAILED(rc)) return rc;
7414 }
7415
7416 /* AudioAdapter */
7417 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7418 if (FAILED(rc)) return rc;
7419
7420 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7421 it != data.llSharedFolders.end();
7422 ++it)
7423 {
7424 const settings::SharedFolder &sf = *it;
7425 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7426 Bstr(sf.strHostPath).raw(),
7427 sf.fWritable, sf.fAutoMount);
7428 if (FAILED(rc)) return rc;
7429 }
7430
7431 // Clipboard
7432 mHWData->mClipboardMode = data.clipboardMode;
7433
7434 // guest settings
7435 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7436
7437 // IO settings
7438 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7439 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7440
7441 // Bandwidth control
7442 rc = mBandwidthControl->loadSettings(data.ioSettings);
7443 if (FAILED(rc)) return rc;
7444
7445#ifdef VBOX_WITH_GUEST_PROPS
7446 /* Guest properties (optional) */
7447 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7448 it != data.llGuestProperties.end();
7449 ++it)
7450 {
7451 const settings::GuestProperty &prop = *it;
7452 uint32_t fFlags = guestProp::NILFLAG;
7453 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7454 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7455 mHWData->mGuestProperties.push_back(property);
7456 }
7457
7458 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7459#endif /* VBOX_WITH_GUEST_PROPS defined */
7460 }
7461 catch(std::bad_alloc &)
7462 {
7463 return E_OUTOFMEMORY;
7464 }
7465
7466 AssertComRC(rc);
7467 return rc;
7468}
7469
7470/**
7471 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7472 *
7473 * @param data
7474 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7475 * @param puuidSnapshot
7476 * @return
7477 */
7478HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7479 const Guid *puuidRegistry,
7480 const Guid *puuidSnapshot)
7481{
7482 AssertReturn(!isSessionMachine(), E_FAIL);
7483
7484 HRESULT rc = S_OK;
7485
7486 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7487 it != data.llStorageControllers.end();
7488 ++it)
7489 {
7490 const settings::StorageController &ctlData = *it;
7491
7492 ComObjPtr<StorageController> pCtl;
7493 /* Try to find one with the name first. */
7494 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7495 if (SUCCEEDED(rc))
7496 return setError(VBOX_E_OBJECT_IN_USE,
7497 tr("Storage controller named '%s' already exists"),
7498 ctlData.strName.c_str());
7499
7500 pCtl.createObject();
7501 rc = pCtl->init(this,
7502 ctlData.strName,
7503 ctlData.storageBus,
7504 ctlData.ulInstance,
7505 ctlData.fBootable);
7506 if (FAILED(rc)) return rc;
7507
7508 mStorageControllers->push_back(pCtl);
7509
7510 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7511 if (FAILED(rc)) return rc;
7512
7513 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7514 if (FAILED(rc)) return rc;
7515
7516 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7517 if (FAILED(rc)) return rc;
7518
7519 /* Set IDE emulation settings (only for AHCI controller). */
7520 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7521 {
7522 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7523 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7524 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7525 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7526 )
7527 return rc;
7528 }
7529
7530 /* Load the attached devices now. */
7531 rc = loadStorageDevices(pCtl,
7532 ctlData,
7533 puuidRegistry,
7534 puuidSnapshot);
7535 if (FAILED(rc)) return rc;
7536 }
7537
7538 return S_OK;
7539}
7540
7541/**
7542 * Called from loadStorageControllers for a controller's devices.
7543 *
7544 * @param aStorageController
7545 * @param data
7546 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7547 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7548 * @return
7549 */
7550HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7551 const settings::StorageController &data,
7552 const Guid *puuidRegistry,
7553 const Guid *puuidSnapshot)
7554{
7555 HRESULT rc = S_OK;
7556
7557 /* paranoia: detect duplicate attachments */
7558 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7559 it != data.llAttachedDevices.end();
7560 ++it)
7561 {
7562 const settings::AttachedDevice &ad = *it;
7563
7564 for (settings::AttachedDevicesList::const_iterator it2 = it;
7565 it2 != data.llAttachedDevices.end();
7566 ++it2)
7567 {
7568 if (it == it2)
7569 continue;
7570
7571 const settings::AttachedDevice &ad2 = *it2;
7572
7573 if ( ad.lPort == ad2.lPort
7574 && ad.lDevice == ad2.lDevice)
7575 {
7576 return setError(E_FAIL,
7577 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7578 aStorageController->getName().c_str(),
7579 ad.lPort,
7580 ad.lDevice,
7581 mUserData->s.strName.c_str());
7582 }
7583 }
7584 }
7585
7586 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7587 it != data.llAttachedDevices.end();
7588 ++it)
7589 {
7590 const settings::AttachedDevice &dev = *it;
7591 ComObjPtr<Medium> medium;
7592
7593 switch (dev.deviceType)
7594 {
7595 case DeviceType_Floppy:
7596 case DeviceType_DVD:
7597 rc = mParent->findRemoveableMedium(dev.deviceType, dev.uuid, false /* fRefresh */, medium);
7598 if (FAILED(rc))
7599 return rc;
7600 break;
7601
7602 case DeviceType_HardDisk:
7603 {
7604 /* find a hard disk by UUID */
7605 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7606 if (FAILED(rc))
7607 {
7608 if (isSnapshotMachine())
7609 {
7610 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7611 // so the user knows that the bad disk is in a snapshot somewhere
7612 com::ErrorInfo info;
7613 return setError(E_FAIL,
7614 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7615 puuidSnapshot->raw(),
7616 info.getText().raw());
7617 }
7618 else
7619 return rc;
7620 }
7621
7622 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7623
7624 if (medium->getType() == MediumType_Immutable)
7625 {
7626 if (isSnapshotMachine())
7627 return setError(E_FAIL,
7628 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7629 "of the virtual machine '%s' ('%s')"),
7630 medium->getLocationFull().c_str(),
7631 dev.uuid.raw(),
7632 puuidSnapshot->raw(),
7633 mUserData->s.strName.c_str(),
7634 mData->m_strConfigFileFull.c_str());
7635
7636 return setError(E_FAIL,
7637 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7638 medium->getLocationFull().c_str(),
7639 dev.uuid.raw(),
7640 mUserData->s.strName.c_str(),
7641 mData->m_strConfigFileFull.c_str());
7642 }
7643
7644 if (medium->getType() == MediumType_MultiAttach)
7645 {
7646 if (isSnapshotMachine())
7647 return setError(E_FAIL,
7648 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7649 "of the virtual machine '%s' ('%s')"),
7650 medium->getLocationFull().c_str(),
7651 dev.uuid.raw(),
7652 puuidSnapshot->raw(),
7653 mUserData->s.strName.c_str(),
7654 mData->m_strConfigFileFull.c_str());
7655
7656 return setError(E_FAIL,
7657 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7658 medium->getLocationFull().c_str(),
7659 dev.uuid.raw(),
7660 mUserData->s.strName.c_str(),
7661 mData->m_strConfigFileFull.c_str());
7662 }
7663
7664 if ( !isSnapshotMachine()
7665 && medium->getChildren().size() != 0
7666 )
7667 return setError(E_FAIL,
7668 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7669 "because it has %d differencing child hard disks"),
7670 medium->getLocationFull().c_str(),
7671 dev.uuid.raw(),
7672 mUserData->s.strName.c_str(),
7673 mData->m_strConfigFileFull.c_str(),
7674 medium->getChildren().size());
7675
7676 if (findAttachment(mMediaData->mAttachments,
7677 medium))
7678 return setError(E_FAIL,
7679 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7680 medium->getLocationFull().c_str(),
7681 dev.uuid.raw(),
7682 mUserData->s.strName.c_str(),
7683 mData->m_strConfigFileFull.c_str());
7684
7685 break;
7686 }
7687
7688 default:
7689 return setError(E_FAIL,
7690 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7691 medium->getLocationFull().c_str(),
7692 mUserData->s.strName.c_str(),
7693 mData->m_strConfigFileFull.c_str());
7694 }
7695
7696 if (FAILED(rc))
7697 break;
7698
7699 /* Bandwidth groups are loaded at this point. */
7700 ComObjPtr<BandwidthGroup> pBwGroup;
7701
7702 if (!dev.strBwGroup.isEmpty())
7703 {
7704 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
7705 if (FAILED(rc))
7706 return setError(E_FAIL,
7707 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
7708 medium->getLocationFull().c_str(),
7709 dev.strBwGroup.c_str(),
7710 mUserData->s.strName.c_str(),
7711 mData->m_strConfigFileFull.c_str());
7712 }
7713
7714 const Bstr controllerName = aStorageController->getName();
7715 ComObjPtr<MediumAttachment> pAttachment;
7716 pAttachment.createObject();
7717 rc = pAttachment->init(this,
7718 medium,
7719 controllerName,
7720 dev.lPort,
7721 dev.lDevice,
7722 dev.deviceType,
7723 dev.fPassThrough,
7724 pBwGroup);
7725 if (FAILED(rc)) break;
7726
7727 /* associate the medium with this machine and snapshot */
7728 if (!medium.isNull())
7729 {
7730 if (isSnapshotMachine())
7731 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7732 else
7733 rc = medium->addBackReference(mData->mUuid);
7734
7735 if (puuidRegistry)
7736 // caller wants registry ID to be set on all attached media (OVF import case)
7737 medium->addRegistry(*puuidRegistry);
7738 }
7739
7740 if (FAILED(rc))
7741 break;
7742
7743 /* back up mMediaData to let registeredInit() properly rollback on failure
7744 * (= limited accessibility) */
7745 setModified(IsModified_Storage);
7746 mMediaData.backup();
7747 mMediaData->mAttachments.push_back(pAttachment);
7748 }
7749
7750 return rc;
7751}
7752
7753/**
7754 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7755 *
7756 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7757 * @param aSnapshot where to return the found snapshot
7758 * @param aSetError true to set extended error info on failure
7759 */
7760HRESULT Machine::findSnapshotById(const Guid &aId,
7761 ComObjPtr<Snapshot> &aSnapshot,
7762 bool aSetError /* = false */)
7763{
7764 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7765
7766 if (!mData->mFirstSnapshot)
7767 {
7768 if (aSetError)
7769 return setError(E_FAIL, tr("This machine does not have any snapshots"));
7770 return E_FAIL;
7771 }
7772
7773 if (aId.isEmpty())
7774 aSnapshot = mData->mFirstSnapshot;
7775 else
7776 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
7777
7778 if (!aSnapshot)
7779 {
7780 if (aSetError)
7781 return setError(E_FAIL,
7782 tr("Could not find a snapshot with UUID {%s}"),
7783 aId.toString().c_str());
7784 return E_FAIL;
7785 }
7786
7787 return S_OK;
7788}
7789
7790/**
7791 * Returns the snapshot with the given name or fails of no such snapshot.
7792 *
7793 * @param aName snapshot name to find
7794 * @param aSnapshot where to return the found snapshot
7795 * @param aSetError true to set extended error info on failure
7796 */
7797HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
7798 ComObjPtr<Snapshot> &aSnapshot,
7799 bool aSetError /* = false */)
7800{
7801 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
7802
7803 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7804
7805 if (!mData->mFirstSnapshot)
7806 {
7807 if (aSetError)
7808 return setError(VBOX_E_OBJECT_NOT_FOUND,
7809 tr("This machine does not have any snapshots"));
7810 return VBOX_E_OBJECT_NOT_FOUND;
7811 }
7812
7813 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
7814
7815 if (!aSnapshot)
7816 {
7817 if (aSetError)
7818 return setError(VBOX_E_OBJECT_NOT_FOUND,
7819 tr("Could not find a snapshot named '%s'"), strName.c_str());
7820 return VBOX_E_OBJECT_NOT_FOUND;
7821 }
7822
7823 return S_OK;
7824}
7825
7826/**
7827 * Returns a storage controller object with the given name.
7828 *
7829 * @param aName storage controller name to find
7830 * @param aStorageController where to return the found storage controller
7831 * @param aSetError true to set extended error info on failure
7832 */
7833HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7834 ComObjPtr<StorageController> &aStorageController,
7835 bool aSetError /* = false */)
7836{
7837 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7838
7839 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7840 it != mStorageControllers->end();
7841 ++it)
7842 {
7843 if ((*it)->getName() == aName)
7844 {
7845 aStorageController = (*it);
7846 return S_OK;
7847 }
7848 }
7849
7850 if (aSetError)
7851 return setError(VBOX_E_OBJECT_NOT_FOUND,
7852 tr("Could not find a storage controller named '%s'"),
7853 aName.c_str());
7854 return VBOX_E_OBJECT_NOT_FOUND;
7855}
7856
7857HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7858 MediaData::AttachmentList &atts)
7859{
7860 AutoCaller autoCaller(this);
7861 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7862
7863 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7864
7865 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7866 it != mMediaData->mAttachments.end();
7867 ++it)
7868 {
7869 const ComObjPtr<MediumAttachment> &pAtt = *it;
7870
7871 // should never happen, but deal with NULL pointers in the list.
7872 AssertStmt(!pAtt.isNull(), continue);
7873
7874 // getControllerName() needs caller+read lock
7875 AutoCaller autoAttCaller(pAtt);
7876 if (FAILED(autoAttCaller.rc()))
7877 {
7878 atts.clear();
7879 return autoAttCaller.rc();
7880 }
7881 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7882
7883 if (pAtt->getControllerName() == aName)
7884 atts.push_back(pAtt);
7885 }
7886
7887 return S_OK;
7888}
7889
7890/**
7891 * Helper for #saveSettings. Cares about renaming the settings directory and
7892 * file if the machine name was changed and about creating a new settings file
7893 * if this is a new machine.
7894 *
7895 * @note Must be never called directly but only from #saveSettings().
7896 */
7897HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7898{
7899 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7900
7901 HRESULT rc = S_OK;
7902
7903 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7904
7905 /* attempt to rename the settings file if machine name is changed */
7906 if ( mUserData->s.fNameSync
7907 && mUserData.isBackedUp()
7908 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7909 )
7910 {
7911 bool dirRenamed = false;
7912 bool fileRenamed = false;
7913
7914 Utf8Str configFile, newConfigFile;
7915 Utf8Str configDir, newConfigDir;
7916
7917 do
7918 {
7919 int vrc = VINF_SUCCESS;
7920
7921 Utf8Str name = mUserData.backedUpData()->s.strName;
7922 Utf8Str newName = mUserData->s.strName;
7923
7924 configFile = mData->m_strConfigFileFull;
7925
7926 /* first, rename the directory if it matches the machine name */
7927 configDir = configFile;
7928 configDir.stripFilename();
7929 newConfigDir = configDir;
7930 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7931 {
7932 newConfigDir.stripFilename();
7933 newConfigDir.append(RTPATH_DELIMITER);
7934 newConfigDir.append(newName);
7935 /* new dir and old dir cannot be equal here because of 'if'
7936 * above and because name != newName */
7937 Assert(configDir != newConfigDir);
7938 if (!fSettingsFileIsNew)
7939 {
7940 /* perform real rename only if the machine is not new */
7941 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7942 if (RT_FAILURE(vrc))
7943 {
7944 rc = setError(E_FAIL,
7945 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7946 configDir.c_str(),
7947 newConfigDir.c_str(),
7948 vrc);
7949 break;
7950 }
7951 dirRenamed = true;
7952 }
7953 }
7954
7955 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
7956 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7957
7958 /* then try to rename the settings file itself */
7959 if (newConfigFile != configFile)
7960 {
7961 /* get the path to old settings file in renamed directory */
7962 configFile = Utf8StrFmt("%s%c%s",
7963 newConfigDir.c_str(),
7964 RTPATH_DELIMITER,
7965 RTPathFilename(configFile.c_str()));
7966 if (!fSettingsFileIsNew)
7967 {
7968 /* perform real rename only if the machine is not new */
7969 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7970 if (RT_FAILURE(vrc))
7971 {
7972 rc = setError(E_FAIL,
7973 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7974 configFile.c_str(),
7975 newConfigFile.c_str(),
7976 vrc);
7977 break;
7978 }
7979 fileRenamed = true;
7980 }
7981 }
7982
7983 // update m_strConfigFileFull amd mConfigFile
7984 mData->m_strConfigFileFull = newConfigFile;
7985 // compute the relative path too
7986 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7987
7988 // store the old and new so that VirtualBox::saveSettings() can update
7989 // the media registry
7990 if ( mData->mRegistered
7991 && configDir != newConfigDir)
7992 {
7993 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7994
7995 if (pfNeedsGlobalSaveSettings)
7996 *pfNeedsGlobalSaveSettings = true;
7997 }
7998
7999 /* update the saved state file path */
8000 Utf8Str path = mSSData->mStateFilePath;
8001 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
8002 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
8003 newConfigDir.c_str(),
8004 path.c_str() + configDir.length());
8005
8006 /* Update saved state file paths of all online snapshots.
8007 * Note that saveSettings() will recognize name change
8008 * and will save all snapshots in this case. */
8009 if (mData->mFirstSnapshot)
8010 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8011 newConfigDir.c_str());
8012 }
8013 while (0);
8014
8015 if (FAILED(rc))
8016 {
8017 /* silently try to rename everything back */
8018 if (fileRenamed)
8019 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8020 if (dirRenamed)
8021 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8022 }
8023
8024 if (FAILED(rc)) return rc;
8025 }
8026
8027 if (fSettingsFileIsNew)
8028 {
8029 /* create a virgin config file */
8030 int vrc = VINF_SUCCESS;
8031
8032 /* ensure the settings directory exists */
8033 Utf8Str path(mData->m_strConfigFileFull);
8034 path.stripFilename();
8035 if (!RTDirExists(path.c_str()))
8036 {
8037 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8038 if (RT_FAILURE(vrc))
8039 {
8040 return setError(E_FAIL,
8041 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8042 path.c_str(),
8043 vrc);
8044 }
8045 }
8046
8047 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8048 path = Utf8Str(mData->m_strConfigFileFull);
8049 RTFILE f = NIL_RTFILE;
8050 vrc = RTFileOpen(&f, path.c_str(),
8051 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8052 if (RT_FAILURE(vrc))
8053 return setError(E_FAIL,
8054 tr("Could not create the settings file '%s' (%Rrc)"),
8055 path.c_str(),
8056 vrc);
8057 RTFileClose(f);
8058 }
8059
8060 return rc;
8061}
8062
8063/**
8064 * Saves and commits machine data, user data and hardware data.
8065 *
8066 * Note that on failure, the data remains uncommitted.
8067 *
8068 * @a aFlags may combine the following flags:
8069 *
8070 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8071 * Used when saving settings after an operation that makes them 100%
8072 * correspond to the settings from the current snapshot.
8073 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8074 * #isReallyModified() returns false. This is necessary for cases when we
8075 * change machine data directly, not through the backup()/commit() mechanism.
8076 * - SaveS_Force: settings will be saved without doing a deep compare of the
8077 * settings structures. This is used when this is called because snapshots
8078 * have changed to avoid the overhead of the deep compare.
8079 *
8080 * @note Must be called from under this object's write lock. Locks children for
8081 * writing.
8082 *
8083 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8084 * initialized to false and that will be set to true by this function if
8085 * the caller must invoke VirtualBox::saveSettings() because the global
8086 * settings have changed. This will happen if a machine rename has been
8087 * saved and the global machine and media registries will therefore need
8088 * updating.
8089 */
8090HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8091 int aFlags /*= 0*/)
8092{
8093 LogFlowThisFuncEnter();
8094
8095 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8096
8097 /* make sure child objects are unable to modify the settings while we are
8098 * saving them */
8099 ensureNoStateDependencies();
8100
8101 AssertReturn(!isSnapshotMachine(),
8102 E_FAIL);
8103
8104 HRESULT rc = S_OK;
8105 bool fNeedsWrite = false;
8106
8107 /* First, prepare to save settings. It will care about renaming the
8108 * settings directory and file if the machine name was changed and about
8109 * creating a new settings file if this is a new machine. */
8110 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8111 if (FAILED(rc)) return rc;
8112
8113 // keep a pointer to the current settings structures
8114 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8115 settings::MachineConfigFile *pNewConfig = NULL;
8116
8117 try
8118 {
8119 // make a fresh one to have everyone write stuff into
8120 pNewConfig = new settings::MachineConfigFile(NULL);
8121 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8122
8123 // now go and copy all the settings data from COM to the settings structures
8124 // (this calles saveSettings() on all the COM objects in the machine)
8125 copyMachineDataToSettings(*pNewConfig);
8126
8127 if (aFlags & SaveS_ResetCurStateModified)
8128 {
8129 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8130 mData->mCurrentStateModified = FALSE;
8131 fNeedsWrite = true; // always, no need to compare
8132 }
8133 else if (aFlags & SaveS_Force)
8134 {
8135 fNeedsWrite = true; // always, no need to compare
8136 }
8137 else
8138 {
8139 if (!mData->mCurrentStateModified)
8140 {
8141 // do a deep compare of the settings that we just saved with the settings
8142 // previously stored in the config file; this invokes MachineConfigFile::operator==
8143 // which does a deep compare of all the settings, which is expensive but less expensive
8144 // than writing out XML in vain
8145 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8146
8147 // could still be modified if any settings changed
8148 mData->mCurrentStateModified = fAnySettingsChanged;
8149
8150 fNeedsWrite = fAnySettingsChanged;
8151 }
8152 else
8153 fNeedsWrite = true;
8154 }
8155
8156 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8157
8158 if (fNeedsWrite)
8159 // now spit it all out!
8160 pNewConfig->write(mData->m_strConfigFileFull);
8161
8162 mData->pMachineConfigFile = pNewConfig;
8163 delete pOldConfig;
8164 commit();
8165
8166 // after saving settings, we are no longer different from the XML on disk
8167 mData->flModifications = 0;
8168 }
8169 catch (HRESULT err)
8170 {
8171 // we assume that error info is set by the thrower
8172 rc = err;
8173
8174 // restore old config
8175 delete pNewConfig;
8176 mData->pMachineConfigFile = pOldConfig;
8177 }
8178 catch (...)
8179 {
8180 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8181 }
8182
8183 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8184 {
8185 /* Fire the data change event, even on failure (since we've already
8186 * committed all data). This is done only for SessionMachines because
8187 * mutable Machine instances are always not registered (i.e. private
8188 * to the client process that creates them) and thus don't need to
8189 * inform callbacks. */
8190 if (isSessionMachine())
8191 mParent->onMachineDataChange(mData->mUuid);
8192 }
8193
8194 LogFlowThisFunc(("rc=%08X\n", rc));
8195 LogFlowThisFuncLeave();
8196 return rc;
8197}
8198
8199/**
8200 * Implementation for saving the machine settings into the given
8201 * settings::MachineConfigFile instance. This copies machine extradata
8202 * from the previous machine config file in the instance data, if any.
8203 *
8204 * This gets called from two locations:
8205 *
8206 * -- Machine::saveSettings(), during the regular XML writing;
8207 *
8208 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8209 * exported to OVF and we write the VirtualBox proprietary XML
8210 * into a <vbox:Machine> tag.
8211 *
8212 * This routine fills all the fields in there, including snapshots, *except*
8213 * for the following:
8214 *
8215 * -- fCurrentStateModified. There is some special logic associated with that.
8216 *
8217 * The caller can then call MachineConfigFile::write() or do something else
8218 * with it.
8219 *
8220 * Caller must hold the machine lock!
8221 *
8222 * This throws XML errors and HRESULT, so the caller must have a catch block!
8223 */
8224void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8225{
8226 // deep copy extradata
8227 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8228
8229 config.uuid = mData->mUuid;
8230
8231 // copy name, description, OS type, teleport, UTC etc.
8232 config.machineUserData = mUserData->s;
8233
8234 if ( mData->mMachineState == MachineState_Saved
8235 || mData->mMachineState == MachineState_Restoring
8236 // when deleting a snapshot we may or may not have a saved state in the current state,
8237 // so let's not assert here please
8238 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8239 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8240 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8241 && (!mSSData->mStateFilePath.isEmpty())
8242 )
8243 )
8244 {
8245 Assert(!mSSData->mStateFilePath.isEmpty());
8246 /* try to make the file name relative to the settings file dir */
8247 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
8248 }
8249 else
8250 {
8251 Assert(mSSData->mStateFilePath.isEmpty());
8252 config.strStateFile.setNull();
8253 }
8254
8255 if (mData->mCurrentSnapshot)
8256 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8257 else
8258 config.uuidCurrentSnapshot.clear();
8259
8260 config.timeLastStateChange = mData->mLastStateChange;
8261 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8262 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8263
8264 HRESULT rc = saveHardware(config.hardwareMachine);
8265 if (FAILED(rc)) throw rc;
8266
8267 rc = saveStorageControllers(config.storageMachine);
8268 if (FAILED(rc)) throw rc;
8269
8270 // save machine's media registry if this is VirtualBox 4.0 or later
8271 if (config.canHaveOwnMediaRegistry())
8272 {
8273 // determine machine folder
8274 Utf8Str strMachineFolder = getSettingsFileFull();
8275 strMachineFolder.stripFilename();
8276 mParent->saveMediaRegistry(config.mediaRegistry,
8277 getId(), // only media with registry ID == machine UUID
8278 strMachineFolder);
8279 // this throws HRESULT
8280 }
8281
8282 // save snapshots
8283 rc = saveAllSnapshots(config);
8284 if (FAILED(rc)) throw rc;
8285}
8286
8287/**
8288 * Saves all snapshots of the machine into the given machine config file. Called
8289 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8290 * @param config
8291 * @return
8292 */
8293HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8294{
8295 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8296
8297 HRESULT rc = S_OK;
8298
8299 try
8300 {
8301 config.llFirstSnapshot.clear();
8302
8303 if (mData->mFirstSnapshot)
8304 {
8305 settings::Snapshot snapNew;
8306 config.llFirstSnapshot.push_back(snapNew);
8307
8308 // get reference to the fresh copy of the snapshot on the list and
8309 // work on that copy directly to avoid excessive copying later
8310 settings::Snapshot &snap = config.llFirstSnapshot.front();
8311
8312 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8313 if (FAILED(rc)) throw rc;
8314 }
8315
8316// if (mType == IsSessionMachine)
8317// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8318
8319 }
8320 catch (HRESULT err)
8321 {
8322 /* we assume that error info is set by the thrower */
8323 rc = err;
8324 }
8325 catch (...)
8326 {
8327 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8328 }
8329
8330 return rc;
8331}
8332
8333/**
8334 * Saves the VM hardware configuration. It is assumed that the
8335 * given node is empty.
8336 *
8337 * @param aNode <Hardware> node to save the VM hardware configuration to.
8338 */
8339HRESULT Machine::saveHardware(settings::Hardware &data)
8340{
8341 HRESULT rc = S_OK;
8342
8343 try
8344 {
8345 /* The hardware version attribute (optional).
8346 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8347 if ( mHWData->mHWVersion == "1"
8348 && mSSData->mStateFilePath.isEmpty()
8349 )
8350 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. */
8351
8352 data.strVersion = mHWData->mHWVersion;
8353 data.uuid = mHWData->mHardwareUUID;
8354
8355 // CPU
8356 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8357 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8358 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8359 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8360 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8361 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8362 data.fPAE = !!mHWData->mPAEEnabled;
8363 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8364
8365 /* Standard and Extended CPUID leafs. */
8366 data.llCpuIdLeafs.clear();
8367 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8368 {
8369 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8370 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8371 }
8372 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8373 {
8374 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8375 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8376 }
8377
8378 data.cCPUs = mHWData->mCPUCount;
8379 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8380 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8381
8382 data.llCpus.clear();
8383 if (data.fCpuHotPlug)
8384 {
8385 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8386 {
8387 if (mHWData->mCPUAttached[idx])
8388 {
8389 settings::Cpu cpu;
8390 cpu.ulId = idx;
8391 data.llCpus.push_back(cpu);
8392 }
8393 }
8394 }
8395
8396 // memory
8397 data.ulMemorySizeMB = mHWData->mMemorySize;
8398 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8399
8400 // firmware
8401 data.firmwareType = mHWData->mFirmwareType;
8402
8403 // HID
8404 data.pointingHidType = mHWData->mPointingHidType;
8405 data.keyboardHidType = mHWData->mKeyboardHidType;
8406
8407 // chipset
8408 data.chipsetType = mHWData->mChipsetType;
8409
8410 // HPET
8411 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8412
8413 // boot order
8414 data.mapBootOrder.clear();
8415 for (size_t i = 0;
8416 i < RT_ELEMENTS(mHWData->mBootOrder);
8417 ++i)
8418 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8419
8420 // display
8421 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8422 data.cMonitors = mHWData->mMonitorCount;
8423 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8424 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8425
8426 /* VRDEServer settings (optional) */
8427 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8428 if (FAILED(rc)) throw rc;
8429
8430 /* BIOS (required) */
8431 rc = mBIOSSettings->saveSettings(data.biosSettings);
8432 if (FAILED(rc)) throw rc;
8433
8434 /* USB Controller (required) */
8435 rc = mUSBController->saveSettings(data.usbController);
8436 if (FAILED(rc)) throw rc;
8437
8438 /* Network adapters (required) */
8439 data.llNetworkAdapters.clear();
8440 for (ULONG slot = 0;
8441 slot < RT_ELEMENTS(mNetworkAdapters);
8442 ++slot)
8443 {
8444 settings::NetworkAdapter nic;
8445 nic.ulSlot = slot;
8446 rc = mNetworkAdapters[slot]->saveSettings(nic);
8447 if (FAILED(rc)) throw rc;
8448
8449 data.llNetworkAdapters.push_back(nic);
8450 }
8451
8452 /* Serial ports */
8453 data.llSerialPorts.clear();
8454 for (ULONG slot = 0;
8455 slot < RT_ELEMENTS(mSerialPorts);
8456 ++slot)
8457 {
8458 settings::SerialPort s;
8459 s.ulSlot = slot;
8460 rc = mSerialPorts[slot]->saveSettings(s);
8461 if (FAILED(rc)) return rc;
8462
8463 data.llSerialPorts.push_back(s);
8464 }
8465
8466 /* Parallel ports */
8467 data.llParallelPorts.clear();
8468 for (ULONG slot = 0;
8469 slot < RT_ELEMENTS(mParallelPorts);
8470 ++slot)
8471 {
8472 settings::ParallelPort p;
8473 p.ulSlot = slot;
8474 rc = mParallelPorts[slot]->saveSettings(p);
8475 if (FAILED(rc)) return rc;
8476
8477 data.llParallelPorts.push_back(p);
8478 }
8479
8480 /* Audio adapter */
8481 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8482 if (FAILED(rc)) return rc;
8483
8484 /* Shared folders */
8485 data.llSharedFolders.clear();
8486 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8487 it != mHWData->mSharedFolders.end();
8488 ++it)
8489 {
8490 ComObjPtr<SharedFolder> pFolder = *it;
8491 settings::SharedFolder sf;
8492 sf.strName = pFolder->getName();
8493 sf.strHostPath = pFolder->getHostPath();
8494 sf.fWritable = !!pFolder->isWritable();
8495 sf.fAutoMount = !!pFolder->isAutoMounted();
8496
8497 data.llSharedFolders.push_back(sf);
8498 }
8499
8500 // clipboard
8501 data.clipboardMode = mHWData->mClipboardMode;
8502
8503 /* Guest */
8504 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8505
8506 // IO settings
8507 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8508 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8509
8510 /* BandwidthControl (required) */
8511 rc = mBandwidthControl->saveSettings(data.ioSettings);
8512 if (FAILED(rc)) throw rc;
8513
8514 // guest properties
8515 data.llGuestProperties.clear();
8516#ifdef VBOX_WITH_GUEST_PROPS
8517 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8518 it != mHWData->mGuestProperties.end();
8519 ++it)
8520 {
8521 HWData::GuestProperty property = *it;
8522
8523 /* Remove transient guest properties at shutdown unless we
8524 * are saving state */
8525 if ( ( mData->mMachineState == MachineState_PoweredOff
8526 || mData->mMachineState == MachineState_Aborted
8527 || mData->mMachineState == MachineState_Teleported)
8528 && property.mFlags & guestProp::TRANSIENT)
8529 continue;
8530 settings::GuestProperty prop;
8531 prop.strName = property.strName;
8532 prop.strValue = property.strValue;
8533 prop.timestamp = property.mTimestamp;
8534 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8535 guestProp::writeFlags(property.mFlags, szFlags);
8536 prop.strFlags = szFlags;
8537
8538 data.llGuestProperties.push_back(prop);
8539 }
8540
8541 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8542 /* I presume this doesn't require a backup(). */
8543 mData->mGuestPropertiesModified = FALSE;
8544#endif /* VBOX_WITH_GUEST_PROPS defined */
8545 }
8546 catch(std::bad_alloc &)
8547 {
8548 return E_OUTOFMEMORY;
8549 }
8550
8551 AssertComRC(rc);
8552 return rc;
8553}
8554
8555/**
8556 * Saves the storage controller configuration.
8557 *
8558 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8559 */
8560HRESULT Machine::saveStorageControllers(settings::Storage &data)
8561{
8562 data.llStorageControllers.clear();
8563
8564 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8565 it != mStorageControllers->end();
8566 ++it)
8567 {
8568 HRESULT rc;
8569 ComObjPtr<StorageController> pCtl = *it;
8570
8571 settings::StorageController ctl;
8572 ctl.strName = pCtl->getName();
8573 ctl.controllerType = pCtl->getControllerType();
8574 ctl.storageBus = pCtl->getStorageBus();
8575 ctl.ulInstance = pCtl->getInstance();
8576 ctl.fBootable = pCtl->getBootable();
8577
8578 /* Save the port count. */
8579 ULONG portCount;
8580 rc = pCtl->COMGETTER(PortCount)(&portCount);
8581 ComAssertComRCRet(rc, rc);
8582 ctl.ulPortCount = portCount;
8583
8584 /* Save fUseHostIOCache */
8585 BOOL fUseHostIOCache;
8586 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8587 ComAssertComRCRet(rc, rc);
8588 ctl.fUseHostIOCache = !!fUseHostIOCache;
8589
8590 /* Save IDE emulation settings. */
8591 if (ctl.controllerType == StorageControllerType_IntelAhci)
8592 {
8593 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8594 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8595 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8596 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8597 )
8598 ComAssertComRCRet(rc, rc);
8599 }
8600
8601 /* save the devices now. */
8602 rc = saveStorageDevices(pCtl, ctl);
8603 ComAssertComRCRet(rc, rc);
8604
8605 data.llStorageControllers.push_back(ctl);
8606 }
8607
8608 return S_OK;
8609}
8610
8611/**
8612 * Saves the hard disk configuration.
8613 */
8614HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8615 settings::StorageController &data)
8616{
8617 MediaData::AttachmentList atts;
8618
8619 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8620 if (FAILED(rc)) return rc;
8621
8622 data.llAttachedDevices.clear();
8623 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8624 it != atts.end();
8625 ++it)
8626 {
8627 settings::AttachedDevice dev;
8628
8629 MediumAttachment *pAttach = *it;
8630 Medium *pMedium = pAttach->getMedium();
8631 BandwidthGroup *pBwGroup = pAttach->getBandwidthGroup();
8632
8633 dev.deviceType = pAttach->getType();
8634 dev.lPort = pAttach->getPort();
8635 dev.lDevice = pAttach->getDevice();
8636 if (pMedium)
8637 {
8638 if (pMedium->isHostDrive())
8639 dev.strHostDriveSrc = pMedium->getLocationFull();
8640 else
8641 dev.uuid = pMedium->getId();
8642 dev.fPassThrough = pAttach->getPassthrough();
8643 }
8644
8645 if (pBwGroup)
8646 {
8647 dev.strBwGroup = pBwGroup->getName();
8648 }
8649
8650 data.llAttachedDevices.push_back(dev);
8651 }
8652
8653 return S_OK;
8654}
8655
8656/**
8657 * Saves machine state settings as defined by aFlags
8658 * (SaveSTS_* values).
8659 *
8660 * @param aFlags Combination of SaveSTS_* flags.
8661 *
8662 * @note Locks objects for writing.
8663 */
8664HRESULT Machine::saveStateSettings(int aFlags)
8665{
8666 if (aFlags == 0)
8667 return S_OK;
8668
8669 AutoCaller autoCaller(this);
8670 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8671
8672 /* This object's write lock is also necessary to serialize file access
8673 * (prevent concurrent reads and writes) */
8674 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8675
8676 HRESULT rc = S_OK;
8677
8678 Assert(mData->pMachineConfigFile);
8679
8680 try
8681 {
8682 if (aFlags & SaveSTS_CurStateModified)
8683 mData->pMachineConfigFile->fCurrentStateModified = true;
8684
8685 if (aFlags & SaveSTS_StateFilePath)
8686 {
8687 if (!mSSData->mStateFilePath.isEmpty())
8688 /* try to make the file name relative to the settings file dir */
8689 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8690 else
8691 mData->pMachineConfigFile->strStateFile.setNull();
8692 }
8693
8694 if (aFlags & SaveSTS_StateTimeStamp)
8695 {
8696 Assert( mData->mMachineState != MachineState_Aborted
8697 || mSSData->mStateFilePath.isEmpty());
8698
8699 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8700
8701 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8702//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8703 }
8704
8705 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8706 }
8707 catch (...)
8708 {
8709 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8710 }
8711
8712 return rc;
8713}
8714
8715/**
8716 * Creates differencing hard disks for all normal hard disks attached to this
8717 * machine and a new set of attachments to refer to created disks.
8718 *
8719 * Used when taking a snapshot or when deleting the current state. Gets called
8720 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8721 *
8722 * This method assumes that mMediaData contains the original hard disk attachments
8723 * it needs to create diffs for. On success, these attachments will be replaced
8724 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8725 * called to delete created diffs which will also rollback mMediaData and restore
8726 * whatever was backed up before calling this method.
8727 *
8728 * Attachments with non-normal hard disks are left as is.
8729 *
8730 * If @a aOnline is @c false then the original hard disks that require implicit
8731 * diffs will be locked for reading. Otherwise it is assumed that they are
8732 * already locked for writing (when the VM was started). Note that in the latter
8733 * case it is responsibility of the caller to lock the newly created diffs for
8734 * writing if this method succeeds.
8735 *
8736 * @param aProgress Progress object to run (must contain at least as
8737 * many operations left as the number of hard disks
8738 * attached).
8739 * @param aOnline Whether the VM was online prior to this operation.
8740 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
8741 *
8742 * @note The progress object is not marked as completed, neither on success nor
8743 * on failure. This is a responsibility of the caller.
8744 *
8745 * @note Locks this object for writing.
8746 */
8747HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8748 ULONG aWeight,
8749 bool aOnline,
8750 GuidList *pllRegistriesThatNeedSaving)
8751{
8752 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8753
8754 AutoCaller autoCaller(this);
8755 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8756
8757 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8758
8759 /* must be in a protective state because we leave the lock below */
8760 AssertReturn( mData->mMachineState == MachineState_Saving
8761 || mData->mMachineState == MachineState_LiveSnapshotting
8762 || mData->mMachineState == MachineState_RestoringSnapshot
8763 || mData->mMachineState == MachineState_DeletingSnapshot
8764 , E_FAIL);
8765
8766 HRESULT rc = S_OK;
8767
8768 MediumLockListMap lockedMediaOffline;
8769 MediumLockListMap *lockedMediaMap;
8770 if (aOnline)
8771 lockedMediaMap = &mData->mSession.mLockedMedia;
8772 else
8773 lockedMediaMap = &lockedMediaOffline;
8774
8775 try
8776 {
8777 if (!aOnline)
8778 {
8779 /* lock all attached hard disks early to detect "in use"
8780 * situations before creating actual diffs */
8781 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8782 it != mMediaData->mAttachments.end();
8783 ++it)
8784 {
8785 MediumAttachment* pAtt = *it;
8786 if (pAtt->getType() == DeviceType_HardDisk)
8787 {
8788 Medium* pMedium = pAtt->getMedium();
8789 Assert(pMedium);
8790
8791 MediumLockList *pMediumLockList(new MediumLockList());
8792 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8793 false /* fMediumLockWrite */,
8794 NULL,
8795 *pMediumLockList);
8796 if (FAILED(rc))
8797 {
8798 delete pMediumLockList;
8799 throw rc;
8800 }
8801 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8802 if (FAILED(rc))
8803 {
8804 throw setError(rc,
8805 tr("Collecting locking information for all attached media failed"));
8806 }
8807 }
8808 }
8809
8810 /* Now lock all media. If this fails, nothing is locked. */
8811 rc = lockedMediaMap->Lock();
8812 if (FAILED(rc))
8813 {
8814 throw setError(rc,
8815 tr("Locking of attached media failed"));
8816 }
8817 }
8818
8819 /* remember the current list (note that we don't use backup() since
8820 * mMediaData may be already backed up) */
8821 MediaData::AttachmentList atts = mMediaData->mAttachments;
8822
8823 /* start from scratch */
8824 mMediaData->mAttachments.clear();
8825
8826 /* go through remembered attachments and create diffs for normal hard
8827 * disks and attach them */
8828 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8829 it != atts.end();
8830 ++it)
8831 {
8832 MediumAttachment* pAtt = *it;
8833
8834 DeviceType_T devType = pAtt->getType();
8835 Medium* pMedium = pAtt->getMedium();
8836
8837 if ( devType != DeviceType_HardDisk
8838 || pMedium == NULL
8839 || pMedium->getType() != MediumType_Normal)
8840 {
8841 /* copy the attachment as is */
8842
8843 /** @todo the progress object created in Console::TakeSnaphot
8844 * only expects operations for hard disks. Later other
8845 * device types need to show up in the progress as well. */
8846 if (devType == DeviceType_HardDisk)
8847 {
8848 if (pMedium == NULL)
8849 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
8850 aWeight); // weight
8851 else
8852 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8853 pMedium->getBase()->getName().c_str()).raw(),
8854 aWeight); // weight
8855 }
8856
8857 mMediaData->mAttachments.push_back(pAtt);
8858 continue;
8859 }
8860
8861 /* need a diff */
8862 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8863 pMedium->getBase()->getName().c_str()).raw(),
8864 aWeight); // weight
8865
8866 Utf8Str strFullSnapshotFolder;
8867 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
8868
8869 ComObjPtr<Medium> diff;
8870 diff.createObject();
8871 rc = diff->init(mParent,
8872 pMedium->getPreferredDiffFormat(),
8873 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
8874 pMedium->getFirstRegistryMachineId(), // store the diff in the same registry as the parent
8875 pllRegistriesThatNeedSaving);
8876 if (FAILED(rc)) throw rc;
8877
8878 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8879 * the push_back? Looks like we're going to leave medium with the
8880 * wrong kind of lock (general issue with if we fail anywhere at all)
8881 * and an orphaned VDI in the snapshots folder. */
8882
8883 /* update the appropriate lock list */
8884 MediumLockList *pMediumLockList;
8885 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8886 AssertComRCThrowRC(rc);
8887 if (aOnline)
8888 {
8889 rc = pMediumLockList->Update(pMedium, false);
8890 AssertComRCThrowRC(rc);
8891 }
8892
8893 /* leave the lock before the potentially lengthy operation */
8894 alock.leave();
8895 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8896 pMediumLockList,
8897 NULL /* aProgress */,
8898 true /* aWait */,
8899 pllRegistriesThatNeedSaving);
8900 alock.enter();
8901 if (FAILED(rc)) throw rc;
8902
8903 rc = lockedMediaMap->Unlock();
8904 AssertComRCThrowRC(rc);
8905 rc = pMediumLockList->Append(diff, true);
8906 AssertComRCThrowRC(rc);
8907 rc = lockedMediaMap->Lock();
8908 AssertComRCThrowRC(rc);
8909
8910 rc = diff->addBackReference(mData->mUuid);
8911 AssertComRCThrowRC(rc);
8912
8913 /* add a new attachment */
8914 ComObjPtr<MediumAttachment> attachment;
8915 attachment.createObject();
8916 rc = attachment->init(this,
8917 diff,
8918 pAtt->getControllerName(),
8919 pAtt->getPort(),
8920 pAtt->getDevice(),
8921 DeviceType_HardDisk,
8922 true /* aImplicit */,
8923 pAtt->getBandwidthGroup());
8924 if (FAILED(rc)) throw rc;
8925
8926 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8927 AssertComRCThrowRC(rc);
8928 mMediaData->mAttachments.push_back(attachment);
8929 }
8930 }
8931 catch (HRESULT aRC) { rc = aRC; }
8932
8933 /* unlock all hard disks we locked */
8934 if (!aOnline)
8935 {
8936 ErrorInfoKeeper eik;
8937
8938 rc = lockedMediaMap->Clear();
8939 AssertComRC(rc);
8940 }
8941
8942 if (FAILED(rc))
8943 {
8944 MultiResult mrc = rc;
8945
8946 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
8947 }
8948
8949 return rc;
8950}
8951
8952/**
8953 * Deletes implicit differencing hard disks created either by
8954 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8955 *
8956 * Note that to delete hard disks created by #AttachMedium() this method is
8957 * called from #fixupMedia() when the changes are rolled back.
8958 *
8959 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8960 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8961 *
8962 * @note Locks this object for writing.
8963 */
8964HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
8965{
8966 AutoCaller autoCaller(this);
8967 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8968
8969 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8970 LogFlowThisFuncEnter();
8971
8972 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8973
8974 HRESULT rc = S_OK;
8975
8976 MediaData::AttachmentList implicitAtts;
8977
8978 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8979
8980 /* enumerate new attachments */
8981 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8982 it != mMediaData->mAttachments.end();
8983 ++it)
8984 {
8985 ComObjPtr<Medium> hd = (*it)->getMedium();
8986 if (hd.isNull())
8987 continue;
8988
8989 if ((*it)->isImplicit())
8990 {
8991 /* deassociate and mark for deletion */
8992 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8993 rc = hd->removeBackReference(mData->mUuid);
8994 AssertComRC(rc);
8995 implicitAtts.push_back(*it);
8996 continue;
8997 }
8998
8999 /* was this hard disk attached before? */
9000 if (!findAttachment(oldAtts, hd))
9001 {
9002 /* no: de-associate */
9003 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9004 rc = hd->removeBackReference(mData->mUuid);
9005 AssertComRC(rc);
9006 continue;
9007 }
9008 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9009 }
9010
9011 /* rollback hard disk changes */
9012 mMediaData.rollback();
9013
9014 MultiResult mrc(S_OK);
9015
9016 /* delete unused implicit diffs */
9017 if (implicitAtts.size() != 0)
9018 {
9019 /* will leave the lock before the potentially lengthy
9020 * operation, so protect with the special state (unless already
9021 * protected) */
9022 MachineState_T oldState = mData->mMachineState;
9023 if ( oldState != MachineState_Saving
9024 && oldState != MachineState_LiveSnapshotting
9025 && oldState != MachineState_RestoringSnapshot
9026 && oldState != MachineState_DeletingSnapshot
9027 && oldState != MachineState_DeletingSnapshotOnline
9028 && oldState != MachineState_DeletingSnapshotPaused
9029 )
9030 setMachineState(MachineState_SettingUp);
9031
9032 alock.leave();
9033
9034 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9035 it != implicitAtts.end();
9036 ++it)
9037 {
9038 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9039 ComObjPtr<Medium> hd = (*it)->getMedium();
9040
9041 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9042 pllRegistriesThatNeedSaving);
9043 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9044 mrc = rc;
9045 }
9046
9047 alock.enter();
9048
9049 if (mData->mMachineState == MachineState_SettingUp)
9050 setMachineState(oldState);
9051 }
9052
9053 return mrc;
9054}
9055
9056/**
9057 * Looks through the given list of media attachments for one with the given parameters
9058 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9059 * can be searched as well if needed.
9060 *
9061 * @param list
9062 * @param aControllerName
9063 * @param aControllerPort
9064 * @param aDevice
9065 * @return
9066 */
9067MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9068 IN_BSTR aControllerName,
9069 LONG aControllerPort,
9070 LONG aDevice)
9071{
9072 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9073 it != ll.end();
9074 ++it)
9075 {
9076 MediumAttachment *pAttach = *it;
9077 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9078 return pAttach;
9079 }
9080
9081 return NULL;
9082}
9083
9084/**
9085 * Looks through the given list of media attachments for one with the given parameters
9086 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9087 * can be searched as well if needed.
9088 *
9089 * @param list
9090 * @param aControllerName
9091 * @param aControllerPort
9092 * @param aDevice
9093 * @return
9094 */
9095MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9096 ComObjPtr<Medium> pMedium)
9097{
9098 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9099 it != ll.end();
9100 ++it)
9101 {
9102 MediumAttachment *pAttach = *it;
9103 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9104 if (pMediumThis == pMedium)
9105 return pAttach;
9106 }
9107
9108 return NULL;
9109}
9110
9111/**
9112 * Looks through the given list of media attachments for one with the given parameters
9113 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9114 * can be searched as well if needed.
9115 *
9116 * @param list
9117 * @param aControllerName
9118 * @param aControllerPort
9119 * @param aDevice
9120 * @return
9121 */
9122MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9123 Guid &id)
9124{
9125 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9126 it != ll.end();
9127 ++it)
9128 {
9129 MediumAttachment *pAttach = *it;
9130 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9131 if (pMediumThis->getId() == id)
9132 return pAttach;
9133 }
9134
9135 return NULL;
9136}
9137
9138/**
9139 * Main implementation for Machine::DetachDevice. This also gets called
9140 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9141 *
9142 * @param pAttach Medium attachment to detach.
9143 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9144 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9145 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9146 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9147 * @return
9148 */
9149HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9150 AutoWriteLock &writeLock,
9151 Snapshot *pSnapshot,
9152 GuidList *pllRegistriesThatNeedSaving)
9153{
9154 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9155 DeviceType_T mediumType = pAttach->getType();
9156
9157 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9158
9159 if (pAttach->isImplicit())
9160 {
9161 /* attempt to implicitly delete the implicitly created diff */
9162
9163 /// @todo move the implicit flag from MediumAttachment to Medium
9164 /// and forbid any hard disk operation when it is implicit. Or maybe
9165 /// a special media state for it to make it even more simple.
9166
9167 Assert(mMediaData.isBackedUp());
9168
9169 /* will leave the lock before the potentially lengthy operation, so
9170 * protect with the special state */
9171 MachineState_T oldState = mData->mMachineState;
9172 setMachineState(MachineState_SettingUp);
9173
9174 writeLock.release();
9175
9176 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9177 pllRegistriesThatNeedSaving);
9178
9179 writeLock.acquire();
9180
9181 setMachineState(oldState);
9182
9183 if (FAILED(rc)) return rc;
9184 }
9185
9186 setModified(IsModified_Storage);
9187 mMediaData.backup();
9188
9189 // we cannot use erase (it) below because backup() above will create
9190 // a copy of the list and make this copy active, but the iterator
9191 // still refers to the original and is not valid for the copy
9192 mMediaData->mAttachments.remove(pAttach);
9193
9194 if (!oldmedium.isNull())
9195 {
9196 // if this is from a snapshot, do not defer detachment to commitMedia()
9197 if (pSnapshot)
9198 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9199 // else if non-hard disk media, do not defer detachment to commitMedia() either
9200 else if (mediumType != DeviceType_HardDisk)
9201 oldmedium->removeBackReference(mData->mUuid);
9202 }
9203
9204 return S_OK;
9205}
9206
9207/**
9208 * Goes thru all medium attachments of the list and calls detachDevice() on each
9209 * of them and attaches all Medium objects found in the process to the given list,
9210 * depending on cleanupMode.
9211 *
9212 * This gets called from Machine::Unregister, both for the actual Machine and
9213 * the SnapshotMachine objects that might be found in the snapshots.
9214 *
9215 * Requires caller and locking.
9216 *
9217 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9218 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9219 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9220 * otherwise no media get added.
9221 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9222 * @return
9223 */
9224HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9225 Snapshot *pSnapshot,
9226 CleanupMode_T cleanupMode,
9227 MediaList &llMedia)
9228{
9229 Assert(isWriteLockOnCurrentThread());
9230
9231 HRESULT rc;
9232
9233 // make a temporary list because detachDevice invalidates iterators into
9234 // mMediaData->mAttachments
9235 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9236
9237 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9238 it != llAttachments2.end();
9239 ++it)
9240 {
9241 ComObjPtr<MediumAttachment> pAttach = *it;
9242 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9243
9244 if (!pMedium.isNull())
9245 {
9246 DeviceType_T devType = pMedium->getDeviceType();
9247 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9248 && devType == DeviceType_HardDisk)
9249 || (cleanupMode == CleanupMode_Full)
9250 )
9251 llMedia.push_back(pMedium);
9252 }
9253
9254 // real machine: then we need to use the proper method
9255 rc = detachDevice(pAttach,
9256 writeLock,
9257 pSnapshot,
9258 NULL /* pfNeedsSaveSettings */);
9259
9260 if (FAILED(rc))
9261 return rc;
9262 }
9263
9264 return S_OK;
9265}
9266
9267/**
9268 * Perform deferred hard disk detachments.
9269 *
9270 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9271 * backed up).
9272 *
9273 * If @a aOnline is @c true then this method will also unlock the old hard disks
9274 * for which the new implicit diffs were created and will lock these new diffs for
9275 * writing.
9276 *
9277 * @param aOnline Whether the VM was online prior to this operation.
9278 *
9279 * @note Locks this object for writing!
9280 */
9281void Machine::commitMedia(bool aOnline /*= false*/)
9282{
9283 AutoCaller autoCaller(this);
9284 AssertComRCReturnVoid(autoCaller.rc());
9285
9286 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9287
9288 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9289
9290 HRESULT rc = S_OK;
9291
9292 /* no attach/detach operations -- nothing to do */
9293 if (!mMediaData.isBackedUp())
9294 return;
9295
9296 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9297 bool fMediaNeedsLocking = false;
9298
9299 /* enumerate new attachments */
9300 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9301 it != mMediaData->mAttachments.end();
9302 ++it)
9303 {
9304 MediumAttachment *pAttach = *it;
9305
9306 pAttach->commit();
9307
9308 Medium* pMedium = pAttach->getMedium();
9309 bool fImplicit = pAttach->isImplicit();
9310
9311 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9312 (pMedium) ? pMedium->getName().c_str() : "NULL",
9313 fImplicit));
9314
9315 /** @todo convert all this Machine-based voodoo to MediumAttachment
9316 * based commit logic. */
9317 if (fImplicit)
9318 {
9319 /* convert implicit attachment to normal */
9320 pAttach->setImplicit(false);
9321
9322 if ( aOnline
9323 && pMedium
9324 && pAttach->getType() == DeviceType_HardDisk
9325 )
9326 {
9327 ComObjPtr<Medium> parent = pMedium->getParent();
9328 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9329
9330 /* update the appropriate lock list */
9331 MediumLockList *pMediumLockList;
9332 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9333 AssertComRC(rc);
9334 if (pMediumLockList)
9335 {
9336 /* unlock if there's a need to change the locking */
9337 if (!fMediaNeedsLocking)
9338 {
9339 rc = mData->mSession.mLockedMedia.Unlock();
9340 AssertComRC(rc);
9341 fMediaNeedsLocking = true;
9342 }
9343 rc = pMediumLockList->Update(parent, false);
9344 AssertComRC(rc);
9345 rc = pMediumLockList->Append(pMedium, true);
9346 AssertComRC(rc);
9347 }
9348 }
9349
9350 continue;
9351 }
9352
9353 if (pMedium)
9354 {
9355 /* was this medium attached before? */
9356 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9357 oldIt != oldAtts.end();
9358 ++oldIt)
9359 {
9360 MediumAttachment *pOldAttach = *oldIt;
9361 if (pOldAttach->getMedium() == pMedium)
9362 {
9363 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9364
9365 /* yes: remove from old to avoid de-association */
9366 oldAtts.erase(oldIt);
9367 break;
9368 }
9369 }
9370 }
9371 }
9372
9373 /* enumerate remaining old attachments and de-associate from the
9374 * current machine state */
9375 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9376 it != oldAtts.end();
9377 ++it)
9378 {
9379 MediumAttachment *pAttach = *it;
9380 Medium* pMedium = pAttach->getMedium();
9381
9382 /* Detach only hard disks, since DVD/floppy media is detached
9383 * instantly in MountMedium. */
9384 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9385 {
9386 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9387
9388 /* now de-associate from the current machine state */
9389 rc = pMedium->removeBackReference(mData->mUuid);
9390 AssertComRC(rc);
9391
9392 if (aOnline)
9393 {
9394 /* unlock since medium is not used anymore */
9395 MediumLockList *pMediumLockList;
9396 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9397 AssertComRC(rc);
9398 if (pMediumLockList)
9399 {
9400 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9401 AssertComRC(rc);
9402 }
9403 }
9404 }
9405 }
9406
9407 /* take media locks again so that the locking state is consistent */
9408 if (fMediaNeedsLocking)
9409 {
9410 Assert(aOnline);
9411 rc = mData->mSession.mLockedMedia.Lock();
9412 AssertComRC(rc);
9413 }
9414
9415 /* commit the hard disk changes */
9416 mMediaData.commit();
9417
9418 if (isSessionMachine())
9419 {
9420 /* attach new data to the primary machine and reshare it */
9421 mPeer->mMediaData.attach(mMediaData);
9422 }
9423
9424 return;
9425}
9426
9427/**
9428 * Perform deferred deletion of implicitly created diffs.
9429 *
9430 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9431 * backed up).
9432 *
9433 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9434 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9435 *
9436 * @note Locks this object for writing!
9437 */
9438void Machine::rollbackMedia()
9439{
9440 AutoCaller autoCaller(this);
9441 AssertComRCReturnVoid (autoCaller.rc());
9442
9443 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9444
9445 LogFlowThisFunc(("Entering\n"));
9446
9447 HRESULT rc = S_OK;
9448
9449 /* no attach/detach operations -- nothing to do */
9450 if (!mMediaData.isBackedUp())
9451 return;
9452
9453 /* enumerate new attachments */
9454 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9455 it != mMediaData->mAttachments.end();
9456 ++it)
9457 {
9458 MediumAttachment *pAttach = *it;
9459 /* Fix up the backrefs for DVD/floppy media. */
9460 if (pAttach->getType() != DeviceType_HardDisk)
9461 {
9462 Medium* pMedium = pAttach->getMedium();
9463 if (pMedium)
9464 {
9465 rc = pMedium->removeBackReference(mData->mUuid);
9466 AssertComRC(rc);
9467 }
9468 }
9469
9470 (*it)->rollback();
9471
9472 pAttach = *it;
9473 /* Fix up the backrefs for DVD/floppy media. */
9474 if (pAttach->getType() != DeviceType_HardDisk)
9475 {
9476 Medium* pMedium = pAttach->getMedium();
9477 if (pMedium)
9478 {
9479 rc = pMedium->addBackReference(mData->mUuid);
9480 AssertComRC(rc);
9481 }
9482 }
9483 }
9484
9485 /** @todo convert all this Machine-based voodoo to MediumAttachment
9486 * based rollback logic. */
9487 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9488 // which gets called if Machine::registeredInit() fails...
9489 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9490
9491 return;
9492}
9493
9494/**
9495 * Returns true if the settings file is located in the directory named exactly
9496 * as the machine; this means, among other things, that the machine directory
9497 * should be auto-renamed.
9498 *
9499 * @param aSettingsDir if not NULL, the full machine settings file directory
9500 * name will be assigned there.
9501 *
9502 * @note Doesn't lock anything.
9503 * @note Not thread safe (must be called from this object's lock).
9504 */
9505bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9506{
9507 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9508 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9509 if (aSettingsDir)
9510 *aSettingsDir = strMachineDirName;
9511 strMachineDirName.stripPath(); // vmname
9512 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9513 strConfigFileOnly.stripPath() // vmname.vbox
9514 .stripExt(); // vmname
9515
9516 AssertReturn(!strMachineDirName.isEmpty(), false);
9517 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9518
9519 return strMachineDirName == strConfigFileOnly;
9520}
9521
9522/**
9523 * Discards all changes to machine settings.
9524 *
9525 * @param aNotify Whether to notify the direct session about changes or not.
9526 *
9527 * @note Locks objects for writing!
9528 */
9529void Machine::rollback(bool aNotify)
9530{
9531 AutoCaller autoCaller(this);
9532 AssertComRCReturn(autoCaller.rc(), (void)0);
9533
9534 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9535
9536 if (!mStorageControllers.isNull())
9537 {
9538 if (mStorageControllers.isBackedUp())
9539 {
9540 /* unitialize all new devices (absent in the backed up list). */
9541 StorageControllerList::const_iterator it = mStorageControllers->begin();
9542 StorageControllerList *backedList = mStorageControllers.backedUpData();
9543 while (it != mStorageControllers->end())
9544 {
9545 if ( std::find(backedList->begin(), backedList->end(), *it)
9546 == backedList->end()
9547 )
9548 {
9549 (*it)->uninit();
9550 }
9551 ++it;
9552 }
9553
9554 /* restore the list */
9555 mStorageControllers.rollback();
9556 }
9557
9558 /* rollback any changes to devices after restoring the list */
9559 if (mData->flModifications & IsModified_Storage)
9560 {
9561 StorageControllerList::const_iterator it = mStorageControllers->begin();
9562 while (it != mStorageControllers->end())
9563 {
9564 (*it)->rollback();
9565 ++it;
9566 }
9567 }
9568 }
9569
9570 mUserData.rollback();
9571
9572 mHWData.rollback();
9573
9574 if (mData->flModifications & IsModified_Storage)
9575 rollbackMedia();
9576
9577 if (mBIOSSettings)
9578 mBIOSSettings->rollback();
9579
9580 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9581 mVRDEServer->rollback();
9582
9583 if (mAudioAdapter)
9584 mAudioAdapter->rollback();
9585
9586 if (mUSBController && (mData->flModifications & IsModified_USB))
9587 mUSBController->rollback();
9588
9589 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
9590 mBandwidthControl->rollback();
9591
9592 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9593 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9594 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9595
9596 if (mData->flModifications & IsModified_NetworkAdapters)
9597 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9598 if ( mNetworkAdapters[slot]
9599 && mNetworkAdapters[slot]->isModified())
9600 {
9601 mNetworkAdapters[slot]->rollback();
9602 networkAdapters[slot] = mNetworkAdapters[slot];
9603 }
9604
9605 if (mData->flModifications & IsModified_SerialPorts)
9606 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9607 if ( mSerialPorts[slot]
9608 && mSerialPorts[slot]->isModified())
9609 {
9610 mSerialPorts[slot]->rollback();
9611 serialPorts[slot] = mSerialPorts[slot];
9612 }
9613
9614 if (mData->flModifications & IsModified_ParallelPorts)
9615 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9616 if ( mParallelPorts[slot]
9617 && mParallelPorts[slot]->isModified())
9618 {
9619 mParallelPorts[slot]->rollback();
9620 parallelPorts[slot] = mParallelPorts[slot];
9621 }
9622
9623 if (aNotify)
9624 {
9625 /* inform the direct session about changes */
9626
9627 ComObjPtr<Machine> that = this;
9628 uint32_t flModifications = mData->flModifications;
9629 alock.leave();
9630
9631 if (flModifications & IsModified_SharedFolders)
9632 that->onSharedFolderChange();
9633
9634 if (flModifications & IsModified_VRDEServer)
9635 that->onVRDEServerChange(/* aRestart */ TRUE);
9636 if (flModifications & IsModified_USB)
9637 that->onUSBControllerChange();
9638
9639 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9640 if (networkAdapters[slot])
9641 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9642 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9643 if (serialPorts[slot])
9644 that->onSerialPortChange(serialPorts[slot]);
9645 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9646 if (parallelPorts[slot])
9647 that->onParallelPortChange(parallelPorts[slot]);
9648
9649 if (flModifications & IsModified_Storage)
9650 that->onStorageControllerChange();
9651
9652#if 0
9653 if (flModifications & IsModified_BandwidthControl)
9654 that->onBandwidthControlChange();
9655#endif
9656 }
9657}
9658
9659/**
9660 * Commits all the changes to machine settings.
9661 *
9662 * Note that this operation is supposed to never fail.
9663 *
9664 * @note Locks this object and children for writing.
9665 */
9666void Machine::commit()
9667{
9668 AutoCaller autoCaller(this);
9669 AssertComRCReturnVoid(autoCaller.rc());
9670
9671 AutoCaller peerCaller(mPeer);
9672 AssertComRCReturnVoid(peerCaller.rc());
9673
9674 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9675
9676 /*
9677 * use safe commit to ensure Snapshot machines (that share mUserData)
9678 * will still refer to a valid memory location
9679 */
9680 mUserData.commitCopy();
9681
9682 mHWData.commit();
9683
9684 if (mMediaData.isBackedUp())
9685 commitMedia();
9686
9687 mBIOSSettings->commit();
9688 mVRDEServer->commit();
9689 mAudioAdapter->commit();
9690 mUSBController->commit();
9691 mBandwidthControl->commit();
9692
9693 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9694 mNetworkAdapters[slot]->commit();
9695 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9696 mSerialPorts[slot]->commit();
9697 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9698 mParallelPorts[slot]->commit();
9699
9700 bool commitStorageControllers = false;
9701
9702 if (mStorageControllers.isBackedUp())
9703 {
9704 mStorageControllers.commit();
9705
9706 if (mPeer)
9707 {
9708 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9709
9710 /* Commit all changes to new controllers (this will reshare data with
9711 * peers for those who have peers) */
9712 StorageControllerList *newList = new StorageControllerList();
9713 StorageControllerList::const_iterator it = mStorageControllers->begin();
9714 while (it != mStorageControllers->end())
9715 {
9716 (*it)->commit();
9717
9718 /* look if this controller has a peer device */
9719 ComObjPtr<StorageController> peer = (*it)->getPeer();
9720 if (!peer)
9721 {
9722 /* no peer means the device is a newly created one;
9723 * create a peer owning data this device share it with */
9724 peer.createObject();
9725 peer->init(mPeer, *it, true /* aReshare */);
9726 }
9727 else
9728 {
9729 /* remove peer from the old list */
9730 mPeer->mStorageControllers->remove(peer);
9731 }
9732 /* and add it to the new list */
9733 newList->push_back(peer);
9734
9735 ++it;
9736 }
9737
9738 /* uninit old peer's controllers that are left */
9739 it = mPeer->mStorageControllers->begin();
9740 while (it != mPeer->mStorageControllers->end())
9741 {
9742 (*it)->uninit();
9743 ++it;
9744 }
9745
9746 /* attach new list of controllers to our peer */
9747 mPeer->mStorageControllers.attach(newList);
9748 }
9749 else
9750 {
9751 /* we have no peer (our parent is the newly created machine);
9752 * just commit changes to devices */
9753 commitStorageControllers = true;
9754 }
9755 }
9756 else
9757 {
9758 /* the list of controllers itself is not changed,
9759 * just commit changes to controllers themselves */
9760 commitStorageControllers = true;
9761 }
9762
9763 if (commitStorageControllers)
9764 {
9765 StorageControllerList::const_iterator it = mStorageControllers->begin();
9766 while (it != mStorageControllers->end())
9767 {
9768 (*it)->commit();
9769 ++it;
9770 }
9771 }
9772
9773 if (isSessionMachine())
9774 {
9775 /* attach new data to the primary machine and reshare it */
9776 mPeer->mUserData.attach(mUserData);
9777 mPeer->mHWData.attach(mHWData);
9778 /* mMediaData is reshared by fixupMedia */
9779 // mPeer->mMediaData.attach(mMediaData);
9780 Assert(mPeer->mMediaData.data() == mMediaData.data());
9781 }
9782}
9783
9784/**
9785 * Copies all the hardware data from the given machine.
9786 *
9787 * Currently, only called when the VM is being restored from a snapshot. In
9788 * particular, this implies that the VM is not running during this method's
9789 * call.
9790 *
9791 * @note This method must be called from under this object's lock.
9792 *
9793 * @note This method doesn't call #commit(), so all data remains backed up and
9794 * unsaved.
9795 */
9796void Machine::copyFrom(Machine *aThat)
9797{
9798 AssertReturnVoid(!isSnapshotMachine());
9799 AssertReturnVoid(aThat->isSnapshotMachine());
9800
9801 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9802
9803 mHWData.assignCopy(aThat->mHWData);
9804
9805 // create copies of all shared folders (mHWData after attaching a copy
9806 // contains just references to original objects)
9807 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9808 it != mHWData->mSharedFolders.end();
9809 ++it)
9810 {
9811 ComObjPtr<SharedFolder> folder;
9812 folder.createObject();
9813 HRESULT rc = folder->initCopy(getMachine(), *it);
9814 AssertComRC(rc);
9815 *it = folder;
9816 }
9817
9818 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9819 mVRDEServer->copyFrom(aThat->mVRDEServer);
9820 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9821 mUSBController->copyFrom(aThat->mUSBController);
9822 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
9823
9824 /* create private copies of all controllers */
9825 mStorageControllers.backup();
9826 mStorageControllers->clear();
9827 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9828 it != aThat->mStorageControllers->end();
9829 ++it)
9830 {
9831 ComObjPtr<StorageController> ctrl;
9832 ctrl.createObject();
9833 ctrl->initCopy(this, *it);
9834 mStorageControllers->push_back(ctrl);
9835 }
9836
9837 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9838 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9839 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9840 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9841 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9842 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9843}
9844
9845#ifdef VBOX_WITH_RESOURCE_USAGE_API
9846
9847void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9848{
9849 AssertReturnVoid(isWriteLockOnCurrentThread());
9850 AssertPtrReturnVoid(aCollector);
9851
9852 pm::CollectorHAL *hal = aCollector->getHAL();
9853 /* Create sub metrics */
9854 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9855 "Percentage of processor time spent in user mode by the VM process.");
9856 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9857 "Percentage of processor time spent in kernel mode by the VM process.");
9858 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9859 "Size of resident portion of VM process in memory.");
9860 /* Create and register base metrics */
9861 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9862 cpuLoadUser, cpuLoadKernel);
9863 aCollector->registerBaseMetric(cpuLoad);
9864 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9865 ramUsageUsed);
9866 aCollector->registerBaseMetric(ramUsage);
9867
9868 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9869 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9870 new pm::AggregateAvg()));
9871 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9872 new pm::AggregateMin()));
9873 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9874 new pm::AggregateMax()));
9875 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9876 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9877 new pm::AggregateAvg()));
9878 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9879 new pm::AggregateMin()));
9880 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9881 new pm::AggregateMax()));
9882
9883 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9884 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9885 new pm::AggregateAvg()));
9886 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9887 new pm::AggregateMin()));
9888 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9889 new pm::AggregateMax()));
9890
9891
9892 /* Guest metrics */
9893 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9894
9895 /* Create sub metrics */
9896 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9897 "Percentage of processor time spent in user mode as seen by the guest.");
9898 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9899 "Percentage of processor time spent in kernel mode as seen by the guest.");
9900 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9901 "Percentage of processor time spent idling as seen by the guest.");
9902
9903 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9904 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9905 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9906 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9907 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9908 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9909
9910 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9911
9912 /* Create and register base metrics */
9913 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9914 aCollector->registerBaseMetric(guestCpuLoad);
9915
9916 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9917 guestMemCache, guestPagedTotal);
9918 aCollector->registerBaseMetric(guestCpuMem);
9919
9920 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9921 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9922 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9923 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9924
9925 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9926 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9927 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9928 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9929
9930 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9931 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9932 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9933 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9934
9935 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9936 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9937 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9938 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9939
9940 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9941 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9942 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9943 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9944
9945 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9946 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9947 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9948 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9949
9950 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9951 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9952 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9953 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9954
9955 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9956 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9957 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9958 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9959
9960 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9961 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9962 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9963 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9964}
9965
9966void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9967{
9968 AssertReturnVoid(isWriteLockOnCurrentThread());
9969
9970 if (aCollector)
9971 {
9972 aCollector->unregisterMetricsFor(aMachine);
9973 aCollector->unregisterBaseMetricsFor(aMachine);
9974 }
9975
9976 if (mGuestHAL)
9977 {
9978 delete mGuestHAL;
9979 mGuestHAL = NULL;
9980 }
9981}
9982
9983#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9984
9985
9986////////////////////////////////////////////////////////////////////////////////
9987
9988DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9989
9990HRESULT SessionMachine::FinalConstruct()
9991{
9992 LogFlowThisFunc(("\n"));
9993
9994#if defined(RT_OS_WINDOWS)
9995 mIPCSem = NULL;
9996#elif defined(RT_OS_OS2)
9997 mIPCSem = NULLHANDLE;
9998#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9999 mIPCSem = -1;
10000#else
10001# error "Port me!"
10002#endif
10003
10004 return S_OK;
10005}
10006
10007void SessionMachine::FinalRelease()
10008{
10009 LogFlowThisFunc(("\n"));
10010
10011 uninit(Uninit::Unexpected);
10012}
10013
10014/**
10015 * @note Must be called only by Machine::openSession() from its own write lock.
10016 */
10017HRESULT SessionMachine::init(Machine *aMachine)
10018{
10019 LogFlowThisFuncEnter();
10020 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10021
10022 AssertReturn(aMachine, E_INVALIDARG);
10023
10024 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10025
10026 /* Enclose the state transition NotReady->InInit->Ready */
10027 AutoInitSpan autoInitSpan(this);
10028 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10029
10030 /* create the interprocess semaphore */
10031#if defined(RT_OS_WINDOWS)
10032 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10033 for (size_t i = 0; i < mIPCSemName.length(); i++)
10034 if (mIPCSemName.raw()[i] == '\\')
10035 mIPCSemName.raw()[i] = '/';
10036 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10037 ComAssertMsgRet(mIPCSem,
10038 ("Cannot create IPC mutex '%ls', err=%d",
10039 mIPCSemName.raw(), ::GetLastError()),
10040 E_FAIL);
10041#elif defined(RT_OS_OS2)
10042 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10043 aMachine->mData->mUuid.raw());
10044 mIPCSemName = ipcSem;
10045 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10046 ComAssertMsgRet(arc == NO_ERROR,
10047 ("Cannot create IPC mutex '%s', arc=%ld",
10048 ipcSem.c_str(), arc),
10049 E_FAIL);
10050#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10051# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10052# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10053 /** @todo Check that this still works correctly. */
10054 AssertCompileSize(key_t, 8);
10055# else
10056 AssertCompileSize(key_t, 4);
10057# endif
10058 key_t key;
10059 mIPCSem = -1;
10060 mIPCKey = "0";
10061 for (uint32_t i = 0; i < 1 << 24; i++)
10062 {
10063 key = ((uint32_t)'V' << 24) | i;
10064 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10065 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10066 {
10067 mIPCSem = sem;
10068 if (sem >= 0)
10069 mIPCKey = BstrFmt("%u", key);
10070 break;
10071 }
10072 }
10073# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10074 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10075 char *pszSemName = NULL;
10076 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10077 key_t key = ::ftok(pszSemName, 'V');
10078 RTStrFree(pszSemName);
10079
10080 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10081# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10082
10083 int errnoSave = errno;
10084 if (mIPCSem < 0 && errnoSave == ENOSYS)
10085 {
10086 setError(E_FAIL,
10087 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10088 "support for SysV IPC. Check the host kernel configuration for "
10089 "CONFIG_SYSVIPC=y"));
10090 return E_FAIL;
10091 }
10092 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10093 * the IPC semaphores */
10094 if (mIPCSem < 0 && errnoSave == ENOSPC)
10095 {
10096#ifdef RT_OS_LINUX
10097 setError(E_FAIL,
10098 tr("Cannot create IPC semaphore because the system limit for the "
10099 "maximum number of semaphore sets (SEMMNI), or the system wide "
10100 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10101 "current set of SysV IPC semaphores can be determined from "
10102 "the file /proc/sysvipc/sem"));
10103#else
10104 setError(E_FAIL,
10105 tr("Cannot create IPC semaphore because the system-imposed limit "
10106 "on the maximum number of allowed semaphores or semaphore "
10107 "identifiers system-wide would be exceeded"));
10108#endif
10109 return E_FAIL;
10110 }
10111 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10112 E_FAIL);
10113 /* set the initial value to 1 */
10114 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10115 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10116 E_FAIL);
10117#else
10118# error "Port me!"
10119#endif
10120
10121 /* memorize the peer Machine */
10122 unconst(mPeer) = aMachine;
10123 /* share the parent pointer */
10124 unconst(mParent) = aMachine->mParent;
10125
10126 /* take the pointers to data to share */
10127 mData.share(aMachine->mData);
10128 mSSData.share(aMachine->mSSData);
10129
10130 mUserData.share(aMachine->mUserData);
10131 mHWData.share(aMachine->mHWData);
10132 mMediaData.share(aMachine->mMediaData);
10133
10134 mStorageControllers.allocate();
10135 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10136 it != aMachine->mStorageControllers->end();
10137 ++it)
10138 {
10139 ComObjPtr<StorageController> ctl;
10140 ctl.createObject();
10141 ctl->init(this, *it);
10142 mStorageControllers->push_back(ctl);
10143 }
10144
10145 unconst(mBIOSSettings).createObject();
10146 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10147 /* create another VRDEServer object that will be mutable */
10148 unconst(mVRDEServer).createObject();
10149 mVRDEServer->init(this, aMachine->mVRDEServer);
10150 /* create another audio adapter object that will be mutable */
10151 unconst(mAudioAdapter).createObject();
10152 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10153 /* create a list of serial ports that will be mutable */
10154 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10155 {
10156 unconst(mSerialPorts[slot]).createObject();
10157 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10158 }
10159 /* create a list of parallel ports that will be mutable */
10160 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10161 {
10162 unconst(mParallelPorts[slot]).createObject();
10163 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10164 }
10165 /* create another USB controller object that will be mutable */
10166 unconst(mUSBController).createObject();
10167 mUSBController->init(this, aMachine->mUSBController);
10168
10169 /* create a list of network adapters that will be mutable */
10170 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10171 {
10172 unconst(mNetworkAdapters[slot]).createObject();
10173 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10174 }
10175
10176 /* create another bandwidth control object that will be mutable */
10177 unconst(mBandwidthControl).createObject();
10178 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10179
10180 /* default is to delete saved state on Saved -> PoweredOff transition */
10181 mRemoveSavedState = true;
10182
10183 /* Confirm a successful initialization when it's the case */
10184 autoInitSpan.setSucceeded();
10185
10186 LogFlowThisFuncLeave();
10187 return S_OK;
10188}
10189
10190/**
10191 * Uninitializes this session object. If the reason is other than
10192 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10193 *
10194 * @param aReason uninitialization reason
10195 *
10196 * @note Locks mParent + this object for writing.
10197 */
10198void SessionMachine::uninit(Uninit::Reason aReason)
10199{
10200 LogFlowThisFuncEnter();
10201 LogFlowThisFunc(("reason=%d\n", aReason));
10202
10203 /*
10204 * Strongly reference ourselves to prevent this object deletion after
10205 * mData->mSession.mMachine.setNull() below (which can release the last
10206 * reference and call the destructor). Important: this must be done before
10207 * accessing any members (and before AutoUninitSpan that does it as well).
10208 * This self reference will be released as the very last step on return.
10209 */
10210 ComObjPtr<SessionMachine> selfRef = this;
10211
10212 /* Enclose the state transition Ready->InUninit->NotReady */
10213 AutoUninitSpan autoUninitSpan(this);
10214 if (autoUninitSpan.uninitDone())
10215 {
10216 LogFlowThisFunc(("Already uninitialized\n"));
10217 LogFlowThisFuncLeave();
10218 return;
10219 }
10220
10221 if (autoUninitSpan.initFailed())
10222 {
10223 /* We've been called by init() because it's failed. It's not really
10224 * necessary (nor it's safe) to perform the regular uninit sequence
10225 * below, the following is enough.
10226 */
10227 LogFlowThisFunc(("Initialization failed.\n"));
10228#if defined(RT_OS_WINDOWS)
10229 if (mIPCSem)
10230 ::CloseHandle(mIPCSem);
10231 mIPCSem = NULL;
10232#elif defined(RT_OS_OS2)
10233 if (mIPCSem != NULLHANDLE)
10234 ::DosCloseMutexSem(mIPCSem);
10235 mIPCSem = NULLHANDLE;
10236#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10237 if (mIPCSem >= 0)
10238 ::semctl(mIPCSem, 0, IPC_RMID);
10239 mIPCSem = -1;
10240# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10241 mIPCKey = "0";
10242# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10243#else
10244# error "Port me!"
10245#endif
10246 uninitDataAndChildObjects();
10247 mData.free();
10248 unconst(mParent) = NULL;
10249 unconst(mPeer) = NULL;
10250 LogFlowThisFuncLeave();
10251 return;
10252 }
10253
10254 MachineState_T lastState;
10255 {
10256 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10257 lastState = mData->mMachineState;
10258 }
10259 NOREF(lastState);
10260
10261#ifdef VBOX_WITH_USB
10262 // release all captured USB devices, but do this before requesting the locks below
10263 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10264 {
10265 /* Console::captureUSBDevices() is called in the VM process only after
10266 * setting the machine state to Starting or Restoring.
10267 * Console::detachAllUSBDevices() will be called upon successful
10268 * termination. So, we need to release USB devices only if there was
10269 * an abnormal termination of a running VM.
10270 *
10271 * This is identical to SessionMachine::DetachAllUSBDevices except
10272 * for the aAbnormal argument. */
10273 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10274 AssertComRC(rc);
10275 NOREF(rc);
10276
10277 USBProxyService *service = mParent->host()->usbProxyService();
10278 if (service)
10279 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10280 }
10281#endif /* VBOX_WITH_USB */
10282
10283 // we need to lock this object in uninit() because the lock is shared
10284 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10285 // and others need mParent lock, and USB needs host lock.
10286 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10287
10288 // Trigger async cleanup tasks, avoid doing things here which are not
10289 // vital to be done immediately and maybe need more locks. This calls
10290 // Machine::unregisterMetrics().
10291 mParent->onMachineUninit(mPeer);
10292
10293 if (aReason == Uninit::Abnormal)
10294 {
10295 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10296 Global::IsOnlineOrTransient(lastState)));
10297
10298 /* reset the state to Aborted */
10299 if (mData->mMachineState != MachineState_Aborted)
10300 setMachineState(MachineState_Aborted);
10301 }
10302
10303 // any machine settings modified?
10304 if (mData->flModifications)
10305 {
10306 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10307 rollback(false /* aNotify */);
10308 }
10309
10310 Assert(mConsoleTaskData.mStateFilePath.isEmpty() || !mConsoleTaskData.mSnapshot);
10311 if (!mConsoleTaskData.mStateFilePath.isEmpty())
10312 {
10313 LogWarningThisFunc(("canceling failed save state request!\n"));
10314 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10315 }
10316 else if (!mConsoleTaskData.mSnapshot.isNull())
10317 {
10318 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10319
10320 /* delete all differencing hard disks created (this will also attach
10321 * their parents back by rolling back mMediaData) */
10322 rollbackMedia();
10323 /* delete the saved state file (it might have been already created) */
10324 if (mConsoleTaskData.mSnapshot->stateFilePath().length())
10325 RTFileDelete(mConsoleTaskData.mSnapshot->stateFilePath().c_str());
10326
10327 mConsoleTaskData.mSnapshot->uninit();
10328 }
10329
10330 if (!mData->mSession.mType.isEmpty())
10331 {
10332 /* mType is not null when this machine's process has been started by
10333 * Machine::launchVMProcess(), therefore it is our child. We
10334 * need to queue the PID to reap the process (and avoid zombies on
10335 * Linux). */
10336 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10337 mParent->addProcessToReap(mData->mSession.mPid);
10338 }
10339
10340 mData->mSession.mPid = NIL_RTPROCESS;
10341
10342 if (aReason == Uninit::Unexpected)
10343 {
10344 /* Uninitialization didn't come from #checkForDeath(), so tell the
10345 * client watcher thread to update the set of machines that have open
10346 * sessions. */
10347 mParent->updateClientWatcher();
10348 }
10349
10350 /* uninitialize all remote controls */
10351 if (mData->mSession.mRemoteControls.size())
10352 {
10353 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10354 mData->mSession.mRemoteControls.size()));
10355
10356 Data::Session::RemoteControlList::iterator it =
10357 mData->mSession.mRemoteControls.begin();
10358 while (it != mData->mSession.mRemoteControls.end())
10359 {
10360 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10361 HRESULT rc = (*it)->Uninitialize();
10362 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10363 if (FAILED(rc))
10364 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10365 ++it;
10366 }
10367 mData->mSession.mRemoteControls.clear();
10368 }
10369
10370 /*
10371 * An expected uninitialization can come only from #checkForDeath().
10372 * Otherwise it means that something's gone really wrong (for example,
10373 * the Session implementation has released the VirtualBox reference
10374 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10375 * etc). However, it's also possible, that the client releases the IPC
10376 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10377 * but the VirtualBox release event comes first to the server process.
10378 * This case is practically possible, so we should not assert on an
10379 * unexpected uninit, just log a warning.
10380 */
10381
10382 if ((aReason == Uninit::Unexpected))
10383 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10384
10385 if (aReason != Uninit::Normal)
10386 {
10387 mData->mSession.mDirectControl.setNull();
10388 }
10389 else
10390 {
10391 /* this must be null here (see #OnSessionEnd()) */
10392 Assert(mData->mSession.mDirectControl.isNull());
10393 Assert(mData->mSession.mState == SessionState_Unlocking);
10394 Assert(!mData->mSession.mProgress.isNull());
10395 }
10396 if (mData->mSession.mProgress)
10397 {
10398 if (aReason == Uninit::Normal)
10399 mData->mSession.mProgress->notifyComplete(S_OK);
10400 else
10401 mData->mSession.mProgress->notifyComplete(E_FAIL,
10402 COM_IIDOF(ISession),
10403 getComponentName(),
10404 tr("The VM session was aborted"));
10405 mData->mSession.mProgress.setNull();
10406 }
10407
10408 /* remove the association between the peer machine and this session machine */
10409 Assert( (SessionMachine*)mData->mSession.mMachine == this
10410 || aReason == Uninit::Unexpected);
10411
10412 /* reset the rest of session data */
10413 mData->mSession.mMachine.setNull();
10414 mData->mSession.mState = SessionState_Unlocked;
10415 mData->mSession.mType.setNull();
10416
10417 /* close the interprocess semaphore before leaving the exclusive lock */
10418#if defined(RT_OS_WINDOWS)
10419 if (mIPCSem)
10420 ::CloseHandle(mIPCSem);
10421 mIPCSem = NULL;
10422#elif defined(RT_OS_OS2)
10423 if (mIPCSem != NULLHANDLE)
10424 ::DosCloseMutexSem(mIPCSem);
10425 mIPCSem = NULLHANDLE;
10426#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10427 if (mIPCSem >= 0)
10428 ::semctl(mIPCSem, 0, IPC_RMID);
10429 mIPCSem = -1;
10430# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10431 mIPCKey = "0";
10432# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10433#else
10434# error "Port me!"
10435#endif
10436
10437 /* fire an event */
10438 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10439
10440 uninitDataAndChildObjects();
10441
10442 /* free the essential data structure last */
10443 mData.free();
10444
10445#if 1 /** @todo Please review this change! (bird) */
10446 /* drop the exclusive lock before setting the below two to NULL */
10447 multilock.release();
10448#else
10449 /* leave the exclusive lock before setting the below two to NULL */
10450 multilock.leave();
10451#endif
10452
10453 unconst(mParent) = NULL;
10454 unconst(mPeer) = NULL;
10455
10456 LogFlowThisFuncLeave();
10457}
10458
10459// util::Lockable interface
10460////////////////////////////////////////////////////////////////////////////////
10461
10462/**
10463 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10464 * with the primary Machine instance (mPeer).
10465 */
10466RWLockHandle *SessionMachine::lockHandle() const
10467{
10468 AssertReturn(mPeer != NULL, NULL);
10469 return mPeer->lockHandle();
10470}
10471
10472// IInternalMachineControl methods
10473////////////////////////////////////////////////////////////////////////////////
10474
10475/**
10476 * @note Locks this object for writing.
10477 */
10478STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10479{
10480 AutoCaller autoCaller(this);
10481 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10482
10483 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10484
10485 mRemoveSavedState = aRemove;
10486
10487 return S_OK;
10488}
10489
10490/**
10491 * @note Locks the same as #setMachineState() does.
10492 */
10493STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10494{
10495 return setMachineState(aMachineState);
10496}
10497
10498/**
10499 * @note Locks this object for reading.
10500 */
10501STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10502{
10503 AutoCaller autoCaller(this);
10504 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10505
10506 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10507
10508#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10509 mIPCSemName.cloneTo(aId);
10510 return S_OK;
10511#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10512# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10513 mIPCKey.cloneTo(aId);
10514# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10515 mData->m_strConfigFileFull.cloneTo(aId);
10516# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10517 return S_OK;
10518#else
10519# error "Port me!"
10520#endif
10521}
10522
10523/**
10524 * @note Locks this object for writing.
10525 */
10526STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10527{
10528 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10529 AutoCaller autoCaller(this);
10530 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10531
10532 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10533
10534 if (mData->mSession.mState != SessionState_Locked)
10535 return VBOX_E_INVALID_OBJECT_STATE;
10536
10537 if (!mData->mSession.mProgress.isNull())
10538 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10539
10540 LogFlowThisFunc(("returns S_OK.\n"));
10541 return S_OK;
10542}
10543
10544
10545/**
10546 * @note Locks this object for writing.
10547 */
10548STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10549{
10550 AutoCaller autoCaller(this);
10551 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10552
10553 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10554
10555 if (mData->mSession.mState != SessionState_Locked)
10556 return VBOX_E_INVALID_OBJECT_STATE;
10557
10558 /* Finalize the openRemoteSession progress object. */
10559 if (mData->mSession.mProgress)
10560 {
10561 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10562 mData->mSession.mProgress.setNull();
10563 }
10564
10565 if (SUCCEEDED((HRESULT)iResult))
10566 {
10567#ifdef VBOX_WITH_RESOURCE_USAGE_API
10568 /* The VM has been powered up successfully, so it makes sense
10569 * now to offer the performance metrics for a running machine
10570 * object. Doing it earlier wouldn't be safe. */
10571 registerMetrics(mParent->performanceCollector(), mPeer,
10572 mData->mSession.mPid);
10573#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10574 }
10575
10576 return S_OK;
10577}
10578
10579/**
10580 * Goes through the USB filters of the given machine to see if the given
10581 * device matches any filter or not.
10582 *
10583 * @note Locks the same as USBController::hasMatchingFilter() does.
10584 */
10585STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10586 BOOL *aMatched,
10587 ULONG *aMaskedIfs)
10588{
10589 LogFlowThisFunc(("\n"));
10590
10591 CheckComArgNotNull(aUSBDevice);
10592 CheckComArgOutPointerValid(aMatched);
10593
10594 AutoCaller autoCaller(this);
10595 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10596
10597#ifdef VBOX_WITH_USB
10598 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10599#else
10600 NOREF(aUSBDevice);
10601 NOREF(aMaskedIfs);
10602 *aMatched = FALSE;
10603#endif
10604
10605 return S_OK;
10606}
10607
10608/**
10609 * @note Locks the same as Host::captureUSBDevice() does.
10610 */
10611STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10612{
10613 LogFlowThisFunc(("\n"));
10614
10615 AutoCaller autoCaller(this);
10616 AssertComRCReturnRC(autoCaller.rc());
10617
10618#ifdef VBOX_WITH_USB
10619 /* if captureDeviceForVM() fails, it must have set extended error info */
10620 MultiResult rc = mParent->host()->checkUSBProxyService();
10621 if (FAILED(rc)) return rc;
10622
10623 USBProxyService *service = mParent->host()->usbProxyService();
10624 AssertReturn(service, E_FAIL);
10625 return service->captureDeviceForVM(this, Guid(aId).ref());
10626#else
10627 NOREF(aId);
10628 return E_NOTIMPL;
10629#endif
10630}
10631
10632/**
10633 * @note Locks the same as Host::detachUSBDevice() does.
10634 */
10635STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10636{
10637 LogFlowThisFunc(("\n"));
10638
10639 AutoCaller autoCaller(this);
10640 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10641
10642#ifdef VBOX_WITH_USB
10643 USBProxyService *service = mParent->host()->usbProxyService();
10644 AssertReturn(service, E_FAIL);
10645 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10646#else
10647 NOREF(aId);
10648 NOREF(aDone);
10649 return E_NOTIMPL;
10650#endif
10651}
10652
10653/**
10654 * Inserts all machine filters to the USB proxy service and then calls
10655 * Host::autoCaptureUSBDevices().
10656 *
10657 * Called by Console from the VM process upon VM startup.
10658 *
10659 * @note Locks what called methods lock.
10660 */
10661STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10662{
10663 LogFlowThisFunc(("\n"));
10664
10665 AutoCaller autoCaller(this);
10666 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10667
10668#ifdef VBOX_WITH_USB
10669 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10670 AssertComRC(rc);
10671 NOREF(rc);
10672
10673 USBProxyService *service = mParent->host()->usbProxyService();
10674 AssertReturn(service, E_FAIL);
10675 return service->autoCaptureDevicesForVM(this);
10676#else
10677 return S_OK;
10678#endif
10679}
10680
10681/**
10682 * Removes all machine filters from the USB proxy service and then calls
10683 * Host::detachAllUSBDevices().
10684 *
10685 * Called by Console from the VM process upon normal VM termination or by
10686 * SessionMachine::uninit() upon abnormal VM termination (from under the
10687 * Machine/SessionMachine lock).
10688 *
10689 * @note Locks what called methods lock.
10690 */
10691STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10692{
10693 LogFlowThisFunc(("\n"));
10694
10695 AutoCaller autoCaller(this);
10696 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10697
10698#ifdef VBOX_WITH_USB
10699 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10700 AssertComRC(rc);
10701 NOREF(rc);
10702
10703 USBProxyService *service = mParent->host()->usbProxyService();
10704 AssertReturn(service, E_FAIL);
10705 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10706#else
10707 NOREF(aDone);
10708 return S_OK;
10709#endif
10710}
10711
10712/**
10713 * @note Locks this object for writing.
10714 */
10715STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10716 IProgress **aProgress)
10717{
10718 LogFlowThisFuncEnter();
10719
10720 AssertReturn(aSession, E_INVALIDARG);
10721 AssertReturn(aProgress, E_INVALIDARG);
10722
10723 AutoCaller autoCaller(this);
10724
10725 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10726 /*
10727 * We don't assert below because it might happen that a non-direct session
10728 * informs us it is closed right after we've been uninitialized -- it's ok.
10729 */
10730 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10731
10732 /* get IInternalSessionControl interface */
10733 ComPtr<IInternalSessionControl> control(aSession);
10734
10735 ComAssertRet(!control.isNull(), E_INVALIDARG);
10736
10737 /* Creating a Progress object requires the VirtualBox lock, and
10738 * thus locking it here is required by the lock order rules. */
10739 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10740
10741 if (control == mData->mSession.mDirectControl)
10742 {
10743 ComAssertRet(aProgress, E_POINTER);
10744
10745 /* The direct session is being normally closed by the client process
10746 * ----------------------------------------------------------------- */
10747
10748 /* go to the closing state (essential for all open*Session() calls and
10749 * for #checkForDeath()) */
10750 Assert(mData->mSession.mState == SessionState_Locked);
10751 mData->mSession.mState = SessionState_Unlocking;
10752
10753 /* set direct control to NULL to release the remote instance */
10754 mData->mSession.mDirectControl.setNull();
10755 LogFlowThisFunc(("Direct control is set to NULL\n"));
10756
10757 if (mData->mSession.mProgress)
10758 {
10759 /* finalize the progress, someone might wait if a frontend
10760 * closes the session before powering on the VM. */
10761 mData->mSession.mProgress->notifyComplete(E_FAIL,
10762 COM_IIDOF(ISession),
10763 getComponentName(),
10764 tr("The VM session was closed before any attempt to power it on"));
10765 mData->mSession.mProgress.setNull();
10766 }
10767
10768 /* Create the progress object the client will use to wait until
10769 * #checkForDeath() is called to uninitialize this session object after
10770 * it releases the IPC semaphore.
10771 * Note! Because we're "reusing" mProgress here, this must be a proxy
10772 * object just like for openRemoteSession. */
10773 Assert(mData->mSession.mProgress.isNull());
10774 ComObjPtr<ProgressProxy> progress;
10775 progress.createObject();
10776 ComPtr<IUnknown> pPeer(mPeer);
10777 progress->init(mParent, pPeer,
10778 Bstr(tr("Closing session")).raw(),
10779 FALSE /* aCancelable */);
10780 progress.queryInterfaceTo(aProgress);
10781 mData->mSession.mProgress = progress;
10782 }
10783 else
10784 {
10785 /* the remote session is being normally closed */
10786 Data::Session::RemoteControlList::iterator it =
10787 mData->mSession.mRemoteControls.begin();
10788 while (it != mData->mSession.mRemoteControls.end())
10789 {
10790 if (control == *it)
10791 break;
10792 ++it;
10793 }
10794 BOOL found = it != mData->mSession.mRemoteControls.end();
10795 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10796 E_INVALIDARG);
10797 mData->mSession.mRemoteControls.remove(*it);
10798 }
10799
10800 LogFlowThisFuncLeave();
10801 return S_OK;
10802}
10803
10804/**
10805 * @note Locks this object for writing.
10806 */
10807STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
10808{
10809 LogFlowThisFuncEnter();
10810
10811 CheckComArgOutPointerValid(aProgress);
10812 CheckComArgOutPointerValid(aStateFilePath);
10813
10814 AutoCaller autoCaller(this);
10815 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10816
10817 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10818
10819 AssertReturn( mData->mMachineState == MachineState_Paused
10820 && mConsoleTaskData.mLastState == MachineState_Null
10821 && mConsoleTaskData.mStateFilePath.isEmpty(),
10822 E_FAIL);
10823
10824 /* create a progress object to track operation completion */
10825 ComObjPtr<Progress> pProgress;
10826 pProgress.createObject();
10827 pProgress->init(getVirtualBox(),
10828 static_cast<IMachine *>(this) /* aInitiator */,
10829 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
10830 FALSE /* aCancelable */);
10831
10832 Bstr stateFilePath;
10833 /* stateFilePath is null when the machine is not running */
10834 if (mData->mMachineState == MachineState_Paused)
10835 {
10836 Utf8Str strFullSnapshotFolder;
10837 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10838 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10839 strFullSnapshotFolder.c_str(),
10840 RTPATH_DELIMITER,
10841 mData->mUuid.raw());
10842 }
10843
10844 /* fill in the snapshot data */
10845 mConsoleTaskData.mLastState = mData->mMachineState;
10846 mConsoleTaskData.mStateFilePath = stateFilePath;
10847 mConsoleTaskData.mProgress = pProgress;
10848
10849 /* set the state to Saving (this is expected by Console::SaveState()) */
10850 setMachineState(MachineState_Saving);
10851
10852 stateFilePath.cloneTo(aStateFilePath);
10853 pProgress.queryInterfaceTo(aProgress);
10854
10855 return S_OK;
10856}
10857
10858/**
10859 * @note Locks mParent + this object for writing.
10860 */
10861STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
10862{
10863 LogFlowThisFunc(("\n"));
10864
10865 AutoCaller autoCaller(this);
10866 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10867
10868 /* endSavingState() need mParent lock */
10869 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10870
10871 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
10872 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
10873 && mConsoleTaskData.mLastState != MachineState_Null
10874 && !mConsoleTaskData.mStateFilePath.isEmpty(),
10875 E_FAIL);
10876
10877 /*
10878 * On failure, set the state to the state we had when BeginSavingState()
10879 * was called (this is expected by Console::SaveState() and the associated
10880 * task). On success the VM process already changed the state to
10881 * MachineState_Saved, so no need to do anything.
10882 */
10883 if (FAILED(iResult))
10884 setMachineState(mConsoleTaskData.mLastState);
10885
10886 return endSavingState(iResult, aErrMsg);
10887}
10888
10889/**
10890 * @note Locks this object for writing.
10891 */
10892STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10893{
10894 LogFlowThisFunc(("\n"));
10895
10896 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10897
10898 AutoCaller autoCaller(this);
10899 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10900
10901 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10902
10903 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10904 || mData->mMachineState == MachineState_Teleported
10905 || mData->mMachineState == MachineState_Aborted
10906 , E_FAIL); /** @todo setError. */
10907
10908 Utf8Str stateFilePathFull = aSavedStateFile;
10909 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10910 if (RT_FAILURE(vrc))
10911 return setError(VBOX_E_FILE_ERROR,
10912 tr("Invalid saved state file path '%ls' (%Rrc)"),
10913 aSavedStateFile,
10914 vrc);
10915
10916 mSSData->mStateFilePath = stateFilePathFull;
10917
10918 /* The below setMachineState() will detect the state transition and will
10919 * update the settings file */
10920
10921 return setMachineState(MachineState_Saved);
10922}
10923
10924STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10925 ComSafeArrayOut(BSTR, aValues),
10926 ComSafeArrayOut(LONG64, aTimestamps),
10927 ComSafeArrayOut(BSTR, aFlags))
10928{
10929 LogFlowThisFunc(("\n"));
10930
10931#ifdef VBOX_WITH_GUEST_PROPS
10932 using namespace guestProp;
10933
10934 AutoCaller autoCaller(this);
10935 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10936
10937 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10938
10939 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10940 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10941 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10942 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10943
10944 size_t cEntries = mHWData->mGuestProperties.size();
10945 com::SafeArray<BSTR> names(cEntries);
10946 com::SafeArray<BSTR> values(cEntries);
10947 com::SafeArray<LONG64> timestamps(cEntries);
10948 com::SafeArray<BSTR> flags(cEntries);
10949 unsigned i = 0;
10950 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10951 it != mHWData->mGuestProperties.end();
10952 ++it)
10953 {
10954 char szFlags[MAX_FLAGS_LEN + 1];
10955 it->strName.cloneTo(&names[i]);
10956 it->strValue.cloneTo(&values[i]);
10957 timestamps[i] = it->mTimestamp;
10958 /* If it is NULL, keep it NULL. */
10959 if (it->mFlags)
10960 {
10961 writeFlags(it->mFlags, szFlags);
10962 Bstr(szFlags).cloneTo(&flags[i]);
10963 }
10964 else
10965 flags[i] = NULL;
10966 ++i;
10967 }
10968 names.detachTo(ComSafeArrayOutArg(aNames));
10969 values.detachTo(ComSafeArrayOutArg(aValues));
10970 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10971 flags.detachTo(ComSafeArrayOutArg(aFlags));
10972 return S_OK;
10973#else
10974 ReturnComNotImplemented();
10975#endif
10976}
10977
10978STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10979 IN_BSTR aValue,
10980 LONG64 aTimestamp,
10981 IN_BSTR aFlags)
10982{
10983 LogFlowThisFunc(("\n"));
10984
10985#ifdef VBOX_WITH_GUEST_PROPS
10986 using namespace guestProp;
10987
10988 CheckComArgStrNotEmptyOrNull(aName);
10989 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10990 return E_POINTER; /* aValue can be NULL to indicate deletion */
10991
10992 try
10993 {
10994 /*
10995 * Convert input up front.
10996 */
10997 Utf8Str utf8Name(aName);
10998 uint32_t fFlags = NILFLAG;
10999 if (aFlags)
11000 {
11001 Utf8Str utf8Flags(aFlags);
11002 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11003 AssertRCReturn(vrc, E_INVALIDARG);
11004 }
11005
11006 /*
11007 * Now grab the object lock, validate the state and do the update.
11008 */
11009 AutoCaller autoCaller(this);
11010 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11011
11012 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11013
11014 switch (mData->mMachineState)
11015 {
11016 case MachineState_Paused:
11017 case MachineState_Running:
11018 case MachineState_Teleporting:
11019 case MachineState_TeleportingPausedVM:
11020 case MachineState_LiveSnapshotting:
11021 case MachineState_DeletingSnapshotOnline:
11022 case MachineState_DeletingSnapshotPaused:
11023 case MachineState_Saving:
11024 break;
11025
11026 default:
11027#ifndef DEBUG_sunlover
11028 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11029 VBOX_E_INVALID_VM_STATE);
11030#else
11031 return VBOX_E_INVALID_VM_STATE;
11032#endif
11033 }
11034
11035 setModified(IsModified_MachineData);
11036 mHWData.backup();
11037
11038 /** @todo r=bird: The careful memory handling doesn't work out here because
11039 * the catch block won't undo any damage we've done. So, if push_back throws
11040 * bad_alloc then you've lost the value.
11041 *
11042 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11043 * since values that changes actually bubbles to the end of the list. Using
11044 * something that has an efficient lookup and can tolerate a bit of updates
11045 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11046 * combination of RTStrCache (for sharing names and getting uniqueness into
11047 * the bargain) and hash/tree is another. */
11048 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11049 iter != mHWData->mGuestProperties.end();
11050 ++iter)
11051 if (utf8Name == iter->strName)
11052 {
11053 mHWData->mGuestProperties.erase(iter);
11054 mData->mGuestPropertiesModified = TRUE;
11055 break;
11056 }
11057 if (aValue != NULL)
11058 {
11059 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11060 mHWData->mGuestProperties.push_back(property);
11061 mData->mGuestPropertiesModified = TRUE;
11062 }
11063
11064 /*
11065 * Send a callback notification if appropriate
11066 */
11067 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11068 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11069 RTSTR_MAX,
11070 utf8Name.c_str(),
11071 RTSTR_MAX, NULL)
11072 )
11073 {
11074 alock.leave();
11075
11076 mParent->onGuestPropertyChange(mData->mUuid,
11077 aName,
11078 aValue,
11079 aFlags);
11080 }
11081 }
11082 catch (...)
11083 {
11084 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11085 }
11086 return S_OK;
11087#else
11088 ReturnComNotImplemented();
11089#endif
11090}
11091
11092// public methods only for internal purposes
11093/////////////////////////////////////////////////////////////////////////////
11094
11095/**
11096 * Called from the client watcher thread to check for expected or unexpected
11097 * death of the client process that has a direct session to this machine.
11098 *
11099 * On Win32 and on OS/2, this method is called only when we've got the
11100 * mutex (i.e. the client has either died or terminated normally) so it always
11101 * returns @c true (the client is terminated, the session machine is
11102 * uninitialized).
11103 *
11104 * On other platforms, the method returns @c true if the client process has
11105 * terminated normally or abnormally and the session machine was uninitialized,
11106 * and @c false if the client process is still alive.
11107 *
11108 * @note Locks this object for writing.
11109 */
11110bool SessionMachine::checkForDeath()
11111{
11112 Uninit::Reason reason;
11113 bool terminated = false;
11114
11115 /* Enclose autoCaller with a block because calling uninit() from under it
11116 * will deadlock. */
11117 {
11118 AutoCaller autoCaller(this);
11119 if (!autoCaller.isOk())
11120 {
11121 /* return true if not ready, to cause the client watcher to exclude
11122 * the corresponding session from watching */
11123 LogFlowThisFunc(("Already uninitialized!\n"));
11124 return true;
11125 }
11126
11127 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11128
11129 /* Determine the reason of death: if the session state is Closing here,
11130 * everything is fine. Otherwise it means that the client did not call
11131 * OnSessionEnd() before it released the IPC semaphore. This may happen
11132 * either because the client process has abnormally terminated, or
11133 * because it simply forgot to call ISession::Close() before exiting. We
11134 * threat the latter also as an abnormal termination (see
11135 * Session::uninit() for details). */
11136 reason = mData->mSession.mState == SessionState_Unlocking ?
11137 Uninit::Normal :
11138 Uninit::Abnormal;
11139
11140#if defined(RT_OS_WINDOWS)
11141
11142 AssertMsg(mIPCSem, ("semaphore must be created"));
11143
11144 /* release the IPC mutex */
11145 ::ReleaseMutex(mIPCSem);
11146
11147 terminated = true;
11148
11149#elif defined(RT_OS_OS2)
11150
11151 AssertMsg(mIPCSem, ("semaphore must be created"));
11152
11153 /* release the IPC mutex */
11154 ::DosReleaseMutexSem(mIPCSem);
11155
11156 terminated = true;
11157
11158#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11159
11160 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11161
11162 int val = ::semctl(mIPCSem, 0, GETVAL);
11163 if (val > 0)
11164 {
11165 /* the semaphore is signaled, meaning the session is terminated */
11166 terminated = true;
11167 }
11168
11169#else
11170# error "Port me!"
11171#endif
11172
11173 } /* AutoCaller block */
11174
11175 if (terminated)
11176 uninit(reason);
11177
11178 return terminated;
11179}
11180
11181/**
11182 * @note Locks this object for reading.
11183 */
11184HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11185{
11186 LogFlowThisFunc(("\n"));
11187
11188 AutoCaller autoCaller(this);
11189 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11190
11191 ComPtr<IInternalSessionControl> directControl;
11192 {
11193 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11194 directControl = mData->mSession.mDirectControl;
11195 }
11196
11197 /* ignore notifications sent after #OnSessionEnd() is called */
11198 if (!directControl)
11199 return S_OK;
11200
11201 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11202}
11203
11204/**
11205 * @note Locks this object for reading.
11206 */
11207HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11208 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
11209{
11210 LogFlowThisFunc(("\n"));
11211
11212 AutoCaller autoCaller(this);
11213 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11214
11215 ComPtr<IInternalSessionControl> directControl;
11216 {
11217 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11218 directControl = mData->mSession.mDirectControl;
11219 }
11220
11221 /* ignore notifications sent after #OnSessionEnd() is called */
11222 if (!directControl)
11223 return S_OK;
11224 /*
11225 * instead acting like callback we ask IVirtualBox deliver corresponding event
11226 */
11227
11228 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
11229 return S_OK;
11230}
11231
11232/**
11233 * @note Locks this object for reading.
11234 */
11235HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
11236{
11237 LogFlowThisFunc(("\n"));
11238
11239 AutoCaller autoCaller(this);
11240 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11241
11242 ComPtr<IInternalSessionControl> directControl;
11243 {
11244 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11245 directControl = mData->mSession.mDirectControl;
11246 }
11247
11248 /* ignore notifications sent after #OnSessionEnd() is called */
11249 if (!directControl)
11250 return S_OK;
11251
11252 return directControl->OnSerialPortChange(serialPort);
11253}
11254
11255/**
11256 * @note Locks this object for reading.
11257 */
11258HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
11259{
11260 LogFlowThisFunc(("\n"));
11261
11262 AutoCaller autoCaller(this);
11263 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11264
11265 ComPtr<IInternalSessionControl> directControl;
11266 {
11267 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11268 directControl = mData->mSession.mDirectControl;
11269 }
11270
11271 /* ignore notifications sent after #OnSessionEnd() is called */
11272 if (!directControl)
11273 return S_OK;
11274
11275 return directControl->OnParallelPortChange(parallelPort);
11276}
11277
11278/**
11279 * @note Locks this object for reading.
11280 */
11281HRESULT SessionMachine::onStorageControllerChange()
11282{
11283 LogFlowThisFunc(("\n"));
11284
11285 AutoCaller autoCaller(this);
11286 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11287
11288 ComPtr<IInternalSessionControl> directControl;
11289 {
11290 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11291 directControl = mData->mSession.mDirectControl;
11292 }
11293
11294 /* ignore notifications sent after #OnSessionEnd() is called */
11295 if (!directControl)
11296 return S_OK;
11297
11298 return directControl->OnStorageControllerChange();
11299}
11300
11301/**
11302 * @note Locks this object for reading.
11303 */
11304HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11305{
11306 LogFlowThisFunc(("\n"));
11307
11308 AutoCaller autoCaller(this);
11309 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11310
11311 ComPtr<IInternalSessionControl> directControl;
11312 {
11313 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11314 directControl = mData->mSession.mDirectControl;
11315 }
11316
11317 /* ignore notifications sent after #OnSessionEnd() is called */
11318 if (!directControl)
11319 return S_OK;
11320
11321 return directControl->OnMediumChange(aAttachment, aForce);
11322}
11323
11324/**
11325 * @note Locks this object for reading.
11326 */
11327HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11328{
11329 LogFlowThisFunc(("\n"));
11330
11331 AutoCaller autoCaller(this);
11332 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11333
11334 ComPtr<IInternalSessionControl> directControl;
11335 {
11336 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11337 directControl = mData->mSession.mDirectControl;
11338 }
11339
11340 /* ignore notifications sent after #OnSessionEnd() is called */
11341 if (!directControl)
11342 return S_OK;
11343
11344 return directControl->OnCPUChange(aCPU, aRemove);
11345}
11346
11347HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11348{
11349 LogFlowThisFunc(("\n"));
11350
11351 AutoCaller autoCaller(this);
11352 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11353
11354 ComPtr<IInternalSessionControl> directControl;
11355 {
11356 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11357 directControl = mData->mSession.mDirectControl;
11358 }
11359
11360 /* ignore notifications sent after #OnSessionEnd() is called */
11361 if (!directControl)
11362 return S_OK;
11363
11364 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11365}
11366
11367/**
11368 * @note Locks this object for reading.
11369 */
11370HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11371{
11372 LogFlowThisFunc(("\n"));
11373
11374 AutoCaller autoCaller(this);
11375 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11376
11377 ComPtr<IInternalSessionControl> directControl;
11378 {
11379 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11380 directControl = mData->mSession.mDirectControl;
11381 }
11382
11383 /* ignore notifications sent after #OnSessionEnd() is called */
11384 if (!directControl)
11385 return S_OK;
11386
11387 return directControl->OnVRDEServerChange(aRestart);
11388}
11389
11390/**
11391 * @note Locks this object for reading.
11392 */
11393HRESULT SessionMachine::onUSBControllerChange()
11394{
11395 LogFlowThisFunc(("\n"));
11396
11397 AutoCaller autoCaller(this);
11398 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11399
11400 ComPtr<IInternalSessionControl> directControl;
11401 {
11402 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11403 directControl = mData->mSession.mDirectControl;
11404 }
11405
11406 /* ignore notifications sent after #OnSessionEnd() is called */
11407 if (!directControl)
11408 return S_OK;
11409
11410 return directControl->OnUSBControllerChange();
11411}
11412
11413/**
11414 * @note Locks this object for reading.
11415 */
11416HRESULT SessionMachine::onSharedFolderChange()
11417{
11418 LogFlowThisFunc(("\n"));
11419
11420 AutoCaller autoCaller(this);
11421 AssertComRCReturnRC(autoCaller.rc());
11422
11423 ComPtr<IInternalSessionControl> directControl;
11424 {
11425 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11426 directControl = mData->mSession.mDirectControl;
11427 }
11428
11429 /* ignore notifications sent after #OnSessionEnd() is called */
11430 if (!directControl)
11431 return S_OK;
11432
11433 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11434}
11435
11436/**
11437 * @note Locks this object for reading.
11438 */
11439HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
11440{
11441 LogFlowThisFunc(("\n"));
11442
11443 AutoCaller autoCaller(this);
11444 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11445
11446 ComPtr<IInternalSessionControl> directControl;
11447 {
11448 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11449 directControl = mData->mSession.mDirectControl;
11450 }
11451
11452 /* ignore notifications sent after #OnSessionEnd() is called */
11453 if (!directControl)
11454 return S_OK;
11455
11456 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
11457}
11458
11459/**
11460 * Returns @c true if this machine's USB controller reports it has a matching
11461 * filter for the given USB device and @c false otherwise.
11462 *
11463 * @note Caller must have requested machine read lock.
11464 */
11465bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11466{
11467 AutoCaller autoCaller(this);
11468 /* silently return if not ready -- this method may be called after the
11469 * direct machine session has been called */
11470 if (!autoCaller.isOk())
11471 return false;
11472
11473
11474#ifdef VBOX_WITH_USB
11475 switch (mData->mMachineState)
11476 {
11477 case MachineState_Starting:
11478 case MachineState_Restoring:
11479 case MachineState_TeleportingIn:
11480 case MachineState_Paused:
11481 case MachineState_Running:
11482 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11483 * elsewhere... */
11484 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11485 default: break;
11486 }
11487#else
11488 NOREF(aDevice);
11489 NOREF(aMaskedIfs);
11490#endif
11491 return false;
11492}
11493
11494/**
11495 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11496 */
11497HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11498 IVirtualBoxErrorInfo *aError,
11499 ULONG aMaskedIfs)
11500{
11501 LogFlowThisFunc(("\n"));
11502
11503 AutoCaller autoCaller(this);
11504
11505 /* This notification may happen after the machine object has been
11506 * uninitialized (the session was closed), so don't assert. */
11507 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11508
11509 ComPtr<IInternalSessionControl> directControl;
11510 {
11511 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11512 directControl = mData->mSession.mDirectControl;
11513 }
11514
11515 /* fail on notifications sent after #OnSessionEnd() is called, it is
11516 * expected by the caller */
11517 if (!directControl)
11518 return E_FAIL;
11519
11520 /* No locks should be held at this point. */
11521 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11522 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11523
11524 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11525}
11526
11527/**
11528 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11529 */
11530HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11531 IVirtualBoxErrorInfo *aError)
11532{
11533 LogFlowThisFunc(("\n"));
11534
11535 AutoCaller autoCaller(this);
11536
11537 /* This notification may happen after the machine object has been
11538 * uninitialized (the session was closed), so don't assert. */
11539 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11540
11541 ComPtr<IInternalSessionControl> directControl;
11542 {
11543 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11544 directControl = mData->mSession.mDirectControl;
11545 }
11546
11547 /* fail on notifications sent after #OnSessionEnd() is called, it is
11548 * expected by the caller */
11549 if (!directControl)
11550 return E_FAIL;
11551
11552 /* No locks should be held at this point. */
11553 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11554 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11555
11556 return directControl->OnUSBDeviceDetach(aId, aError);
11557}
11558
11559// protected methods
11560/////////////////////////////////////////////////////////////////////////////
11561
11562/**
11563 * Helper method to finalize saving the state.
11564 *
11565 * @note Must be called from under this object's lock.
11566 *
11567 * @param aRc S_OK if the snapshot has been taken successfully
11568 * @param aErrMsg human readable error message for failure
11569 *
11570 * @note Locks mParent + this objects for writing.
11571 */
11572HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
11573{
11574 LogFlowThisFuncEnter();
11575
11576 AutoCaller autoCaller(this);
11577 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11578
11579 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11580
11581 HRESULT rc = S_OK;
11582
11583 if (SUCCEEDED(aRc))
11584 {
11585 mSSData->mStateFilePath = mConsoleTaskData.mStateFilePath;
11586
11587 /* save all VM settings */
11588 rc = saveSettings(NULL);
11589 // no need to check whether VirtualBox.xml needs saving also since
11590 // we can't have a name change pending at this point
11591 }
11592 else
11593 {
11594 /* delete the saved state file (it might have been already created) */
11595 RTFileDelete(mConsoleTaskData.mStateFilePath.c_str());
11596 }
11597
11598 /* notify the progress object about operation completion */
11599 Assert(mConsoleTaskData.mProgress);
11600 if (SUCCEEDED(aRc))
11601 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11602 else
11603 {
11604 if (aErrMsg.length())
11605 mConsoleTaskData.mProgress->notifyComplete(aRc,
11606 COM_IIDOF(ISession),
11607 getComponentName(),
11608 aErrMsg.c_str());
11609 else
11610 mConsoleTaskData.mProgress->notifyComplete(aRc);
11611 }
11612
11613 /* clear out the temporary saved state data */
11614 mConsoleTaskData.mLastState = MachineState_Null;
11615 mConsoleTaskData.mStateFilePath.setNull();
11616 mConsoleTaskData.mProgress.setNull();
11617
11618 LogFlowThisFuncLeave();
11619 return rc;
11620}
11621
11622/**
11623 * Locks the attached media.
11624 *
11625 * All attached hard disks are locked for writing and DVD/floppy are locked for
11626 * reading. Parents of attached hard disks (if any) are locked for reading.
11627 *
11628 * This method also performs accessibility check of all media it locks: if some
11629 * media is inaccessible, the method will return a failure and a bunch of
11630 * extended error info objects per each inaccessible medium.
11631 *
11632 * Note that this method is atomic: if it returns a success, all media are
11633 * locked as described above; on failure no media is locked at all (all
11634 * succeeded individual locks will be undone).
11635 *
11636 * This method is intended to be called when the machine is in Starting or
11637 * Restoring state and asserts otherwise.
11638 *
11639 * The locks made by this method must be undone by calling #unlockMedia() when
11640 * no more needed.
11641 */
11642HRESULT SessionMachine::lockMedia()
11643{
11644 AutoCaller autoCaller(this);
11645 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11646
11647 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11648
11649 AssertReturn( mData->mMachineState == MachineState_Starting
11650 || mData->mMachineState == MachineState_Restoring
11651 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11652 /* bail out if trying to lock things with already set up locking */
11653 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11654
11655 MultiResult mrc(S_OK);
11656
11657 /* Collect locking information for all medium objects attached to the VM. */
11658 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11659 it != mMediaData->mAttachments.end();
11660 ++it)
11661 {
11662 MediumAttachment* pAtt = *it;
11663 DeviceType_T devType = pAtt->getType();
11664 Medium *pMedium = pAtt->getMedium();
11665
11666 MediumLockList *pMediumLockList(new MediumLockList());
11667 // There can be attachments without a medium (floppy/dvd), and thus
11668 // it's impossible to create a medium lock list. It still makes sense
11669 // to have the empty medium lock list in the map in case a medium is
11670 // attached later.
11671 if (pMedium != NULL)
11672 {
11673 MediumType_T mediumType = pMedium->getType();
11674 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
11675 || mediumType == MediumType_Shareable;
11676 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11677
11678 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11679 !fIsReadOnlyLock /* fMediumLockWrite */,
11680 NULL,
11681 *pMediumLockList);
11682 if (FAILED(mrc))
11683 {
11684 delete pMediumLockList;
11685 mData->mSession.mLockedMedia.Clear();
11686 break;
11687 }
11688 }
11689
11690 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11691 if (FAILED(rc))
11692 {
11693 mData->mSession.mLockedMedia.Clear();
11694 mrc = setError(rc,
11695 tr("Collecting locking information for all attached media failed"));
11696 break;
11697 }
11698 }
11699
11700 if (SUCCEEDED(mrc))
11701 {
11702 /* Now lock all media. If this fails, nothing is locked. */
11703 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11704 if (FAILED(rc))
11705 {
11706 mrc = setError(rc,
11707 tr("Locking of attached media failed"));
11708 }
11709 }
11710
11711 return mrc;
11712}
11713
11714/**
11715 * Undoes the locks made by by #lockMedia().
11716 */
11717void SessionMachine::unlockMedia()
11718{
11719 AutoCaller autoCaller(this);
11720 AssertComRCReturnVoid(autoCaller.rc());
11721
11722 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11723
11724 /* we may be holding important error info on the current thread;
11725 * preserve it */
11726 ErrorInfoKeeper eik;
11727
11728 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11729 AssertComRC(rc);
11730}
11731
11732/**
11733 * Helper to change the machine state (reimplementation).
11734 *
11735 * @note Locks this object for writing.
11736 */
11737HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11738{
11739 LogFlowThisFuncEnter();
11740 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11741
11742 AutoCaller autoCaller(this);
11743 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11744
11745 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11746
11747 MachineState_T oldMachineState = mData->mMachineState;
11748
11749 AssertMsgReturn(oldMachineState != aMachineState,
11750 ("oldMachineState=%s, aMachineState=%s\n",
11751 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11752 E_FAIL);
11753
11754 HRESULT rc = S_OK;
11755
11756 int stsFlags = 0;
11757 bool deleteSavedState = false;
11758
11759 /* detect some state transitions */
11760
11761 if ( ( oldMachineState == MachineState_Saved
11762 && aMachineState == MachineState_Restoring)
11763 || ( ( oldMachineState == MachineState_PoweredOff
11764 || oldMachineState == MachineState_Teleported
11765 || oldMachineState == MachineState_Aborted
11766 )
11767 && ( aMachineState == MachineState_TeleportingIn
11768 || aMachineState == MachineState_Starting
11769 )
11770 )
11771 )
11772 {
11773 /* The EMT thread is about to start */
11774
11775 /* Nothing to do here for now... */
11776
11777 /// @todo NEWMEDIA don't let mDVDDrive and other children
11778 /// change anything when in the Starting/Restoring state
11779 }
11780 else if ( ( oldMachineState == MachineState_Running
11781 || oldMachineState == MachineState_Paused
11782 || oldMachineState == MachineState_Teleporting
11783 || oldMachineState == MachineState_LiveSnapshotting
11784 || oldMachineState == MachineState_Stuck
11785 || oldMachineState == MachineState_Starting
11786 || oldMachineState == MachineState_Stopping
11787 || oldMachineState == MachineState_Saving
11788 || oldMachineState == MachineState_Restoring
11789 || oldMachineState == MachineState_TeleportingPausedVM
11790 || oldMachineState == MachineState_TeleportingIn
11791 )
11792 && ( aMachineState == MachineState_PoweredOff
11793 || aMachineState == MachineState_Saved
11794 || aMachineState == MachineState_Teleported
11795 || aMachineState == MachineState_Aborted
11796 )
11797 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11798 * snapshot */
11799 && ( mConsoleTaskData.mSnapshot.isNull()
11800 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11801 )
11802 )
11803 {
11804 /* The EMT thread has just stopped, unlock attached media. Note that as
11805 * opposed to locking that is done from Console, we do unlocking here
11806 * because the VM process may have aborted before having a chance to
11807 * properly unlock all media it locked. */
11808
11809 unlockMedia();
11810 }
11811
11812 if (oldMachineState == MachineState_Restoring)
11813 {
11814 if (aMachineState != MachineState_Saved)
11815 {
11816 /*
11817 * delete the saved state file once the machine has finished
11818 * restoring from it (note that Console sets the state from
11819 * Restoring to Saved if the VM couldn't restore successfully,
11820 * to give the user an ability to fix an error and retry --
11821 * we keep the saved state file in this case)
11822 */
11823 deleteSavedState = true;
11824 }
11825 }
11826 else if ( oldMachineState == MachineState_Saved
11827 && ( aMachineState == MachineState_PoweredOff
11828 || aMachineState == MachineState_Aborted
11829 || aMachineState == MachineState_Teleported
11830 )
11831 )
11832 {
11833 /*
11834 * delete the saved state after Console::ForgetSavedState() is called
11835 * or if the VM process (owning a direct VM session) crashed while the
11836 * VM was Saved
11837 */
11838
11839 /// @todo (dmik)
11840 // Not sure that deleting the saved state file just because of the
11841 // client death before it attempted to restore the VM is a good
11842 // thing. But when it crashes we need to go to the Aborted state
11843 // which cannot have the saved state file associated... The only
11844 // way to fix this is to make the Aborted condition not a VM state
11845 // but a bool flag: i.e., when a crash occurs, set it to true and
11846 // change the state to PoweredOff or Saved depending on the
11847 // saved state presence.
11848
11849 deleteSavedState = true;
11850 mData->mCurrentStateModified = TRUE;
11851 stsFlags |= SaveSTS_CurStateModified;
11852 }
11853
11854 if ( aMachineState == MachineState_Starting
11855 || aMachineState == MachineState_Restoring
11856 || aMachineState == MachineState_TeleportingIn
11857 )
11858 {
11859 /* set the current state modified flag to indicate that the current
11860 * state is no more identical to the state in the
11861 * current snapshot */
11862 if (!mData->mCurrentSnapshot.isNull())
11863 {
11864 mData->mCurrentStateModified = TRUE;
11865 stsFlags |= SaveSTS_CurStateModified;
11866 }
11867 }
11868
11869 if (deleteSavedState)
11870 {
11871 if (mRemoveSavedState)
11872 {
11873 Assert(!mSSData->mStateFilePath.isEmpty());
11874 RTFileDelete(mSSData->mStateFilePath.c_str());
11875 }
11876 mSSData->mStateFilePath.setNull();
11877 stsFlags |= SaveSTS_StateFilePath;
11878 }
11879
11880 /* redirect to the underlying peer machine */
11881 mPeer->setMachineState(aMachineState);
11882
11883 if ( aMachineState == MachineState_PoweredOff
11884 || aMachineState == MachineState_Teleported
11885 || aMachineState == MachineState_Aborted
11886 || aMachineState == MachineState_Saved)
11887 {
11888 /* the machine has stopped execution
11889 * (or the saved state file was adopted) */
11890 stsFlags |= SaveSTS_StateTimeStamp;
11891 }
11892
11893 if ( ( oldMachineState == MachineState_PoweredOff
11894 || oldMachineState == MachineState_Aborted
11895 || oldMachineState == MachineState_Teleported
11896 )
11897 && aMachineState == MachineState_Saved)
11898 {
11899 /* the saved state file was adopted */
11900 Assert(!mSSData->mStateFilePath.isEmpty());
11901 stsFlags |= SaveSTS_StateFilePath;
11902 }
11903
11904#ifdef VBOX_WITH_GUEST_PROPS
11905 if ( aMachineState == MachineState_PoweredOff
11906 || aMachineState == MachineState_Aborted
11907 || aMachineState == MachineState_Teleported)
11908 {
11909 /* Make sure any transient guest properties get removed from the
11910 * property store on shutdown. */
11911
11912 HWData::GuestPropertyList::iterator it;
11913 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11914 if (!fNeedsSaving)
11915 for (it = mHWData->mGuestProperties.begin();
11916 it != mHWData->mGuestProperties.end(); ++it)
11917 if (it->mFlags & guestProp::TRANSIENT)
11918 {
11919 fNeedsSaving = true;
11920 break;
11921 }
11922 if (fNeedsSaving)
11923 {
11924 mData->mCurrentStateModified = TRUE;
11925 stsFlags |= SaveSTS_CurStateModified;
11926 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11927 }
11928 }
11929#endif
11930
11931 rc = saveStateSettings(stsFlags);
11932
11933 if ( ( oldMachineState != MachineState_PoweredOff
11934 && oldMachineState != MachineState_Aborted
11935 && oldMachineState != MachineState_Teleported
11936 )
11937 && ( aMachineState == MachineState_PoweredOff
11938 || aMachineState == MachineState_Aborted
11939 || aMachineState == MachineState_Teleported
11940 )
11941 )
11942 {
11943 /* we've been shut down for any reason */
11944 /* no special action so far */
11945 }
11946
11947 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11948 LogFlowThisFuncLeave();
11949 return rc;
11950}
11951
11952/**
11953 * Sends the current machine state value to the VM process.
11954 *
11955 * @note Locks this object for reading, then calls a client process.
11956 */
11957HRESULT SessionMachine::updateMachineStateOnClient()
11958{
11959 AutoCaller autoCaller(this);
11960 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11961
11962 ComPtr<IInternalSessionControl> directControl;
11963 {
11964 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11965 AssertReturn(!!mData, E_FAIL);
11966 directControl = mData->mSession.mDirectControl;
11967
11968 /* directControl may be already set to NULL here in #OnSessionEnd()
11969 * called too early by the direct session process while there is still
11970 * some operation (like deleting the snapshot) in progress. The client
11971 * process in this case is waiting inside Session::close() for the
11972 * "end session" process object to complete, while #uninit() called by
11973 * #checkForDeath() on the Watcher thread is waiting for the pending
11974 * operation to complete. For now, we accept this inconsistent behavior
11975 * and simply do nothing here. */
11976
11977 if (mData->mSession.mState == SessionState_Unlocking)
11978 return S_OK;
11979
11980 AssertReturn(!directControl.isNull(), E_FAIL);
11981 }
11982
11983 return directControl->UpdateMachineState(mData->mMachineState);
11984}
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