VirtualBox

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

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

Main. QT/FE: fix long standing COM issue

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 397.2 KB
Line 
1/* $Id: MachineImpl.cpp 35638 2011-01-19 19:10:49Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2011 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
53#ifdef VBOX_WITH_USB
54# include "USBProxyService.h"
55#endif
56
57#include "AutoCaller.h"
58#include "Performance.h"
59
60#include <iprt/asm.h>
61#include <iprt/path.h>
62#include <iprt/dir.h>
63#include <iprt/env.h>
64#include <iprt/lockvalidator.h>
65#include <iprt/process.h>
66#include <iprt/cpp/utils.h>
67#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
68#include <iprt/string.h>
69
70#include <VBox/com/array.h>
71
72#include <VBox/err.h>
73#include <VBox/param.h>
74#include <VBox/settings.h>
75#include <VBox/vmm/ssm.h>
76
77#ifdef VBOX_WITH_GUEST_PROPS
78# include <VBox/HostServices/GuestPropertySvc.h>
79# include <VBox/com/array.h>
80#endif
81
82#include "VBox/com/MultiResult.h"
83
84#include <algorithm>
85
86#include <typeinfo>
87
88#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
89# define HOSTSUFF_EXE ".exe"
90#else /* !RT_OS_WINDOWS */
91# define HOSTSUFF_EXE ""
92#endif /* !RT_OS_WINDOWS */
93
94// defines / prototypes
95/////////////////////////////////////////////////////////////////////////////
96
97/////////////////////////////////////////////////////////////////////////////
98// Machine::Data structure
99/////////////////////////////////////////////////////////////////////////////
100
101Machine::Data::Data()
102{
103 mRegistered = FALSE;
104 pMachineConfigFile = NULL;
105 flModifications = 0;
106 mAccessible = FALSE;
107 /* mUuid is initialized in Machine::init() */
108
109 mMachineState = MachineState_PoweredOff;
110 RTTimeNow(&mLastStateChange);
111
112 mMachineStateDeps = 0;
113 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
114 mMachineStateChangePending = 0;
115
116 mCurrentStateModified = TRUE;
117 mGuestPropertiesModified = FALSE;
118
119 mSession.mPid = NIL_RTPROCESS;
120 mSession.mState = SessionState_Unlocked;
121}
122
123Machine::Data::~Data()
124{
125 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
126 {
127 RTSemEventMultiDestroy(mMachineStateDepsSem);
128 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
129 }
130 if (pMachineConfigFile)
131 {
132 delete pMachineConfigFile;
133 pMachineConfigFile = NULL;
134 }
135}
136
137/////////////////////////////////////////////////////////////////////////////
138// Machine::HWData structure
139/////////////////////////////////////////////////////////////////////////////
140
141Machine::HWData::HWData()
142{
143 /* default values for a newly created machine */
144 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
145 mMemorySize = 128;
146 mCPUCount = 1;
147 mCPUHotPlugEnabled = false;
148 mMemoryBalloonSize = 0;
149 mPageFusionEnabled = false;
150 mVRAMSize = 8;
151 mAccelerate3DEnabled = false;
152 mAccelerate2DVideoEnabled = false;
153 mMonitorCount = 1;
154 mHWVirtExEnabled = true;
155 mHWVirtExNestedPagingEnabled = true;
156#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
157 mHWVirtExLargePagesEnabled = true;
158#else
159 /* Not supported on 32 bits hosts. */
160 mHWVirtExLargePagesEnabled = false;
161#endif
162 mHWVirtExVPIDEnabled = true;
163 mHWVirtExForceEnabled = false;
164#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
165 mHWVirtExExclusive = false;
166#else
167 mHWVirtExExclusive = true;
168#endif
169#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
170 mPAEEnabled = true;
171#else
172 mPAEEnabled = false;
173#endif
174 mSyntheticCpu = false;
175 mHpetEnabled = false;
176
177 /* default boot order: floppy - DVD - HDD */
178 mBootOrder[0] = DeviceType_Floppy;
179 mBootOrder[1] = DeviceType_DVD;
180 mBootOrder[2] = DeviceType_HardDisk;
181 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
182 mBootOrder[i] = DeviceType_Null;
183
184 mClipboardMode = ClipboardMode_Bidirectional;
185 mGuestPropertyNotificationPatterns = "";
186
187 mFirmwareType = FirmwareType_BIOS;
188 mKeyboardHidType = KeyboardHidType_PS2Keyboard;
189 mPointingHidType = PointingHidType_PS2Mouse;
190 mChipsetType = ChipsetType_PIIX3;
191
192 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); i++)
193 mCPUAttached[i] = false;
194
195 mIoCacheEnabled = true;
196 mIoCacheSize = 5; /* 5MB */
197
198 /* Maximum CPU execution cap by default. */
199 mCpuExecutionCap = 100;
200}
201
202Machine::HWData::~HWData()
203{
204}
205
206/////////////////////////////////////////////////////////////////////////////
207// Machine::HDData structure
208/////////////////////////////////////////////////////////////////////////////
209
210Machine::MediaData::MediaData()
211{
212}
213
214Machine::MediaData::~MediaData()
215{
216}
217
218/////////////////////////////////////////////////////////////////////////////
219// Machine class
220/////////////////////////////////////////////////////////////////////////////
221
222// constructor / destructor
223/////////////////////////////////////////////////////////////////////////////
224
225Machine::Machine()
226 : mGuestHAL(NULL),
227 mPeer(NULL),
228 mParent(NULL)
229{}
230
231Machine::~Machine()
232{}
233
234HRESULT Machine::FinalConstruct()
235{
236 LogFlowThisFunc(("\n"));
237 return BaseFinalConstruct();
238}
239
240void Machine::FinalRelease()
241{
242 LogFlowThisFunc(("\n"));
243 uninit();
244 BaseFinalRelease();
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
5814STDMETHODIMP Machine::AttachHostPciDevice(LONG hostAddress, LONG desiredGuestAddress, IEventContext * /*eventContext*/, BOOL /*tryToUnbind*/)
5815{
5816 AutoCaller autoCaller(this);
5817 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5818 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5819
5820 ComObjPtr<PciDeviceAttachment> pda;
5821 char name[32];
5822
5823 pda.createObject();
5824 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (hostAddress>>8) & 0xff, (hostAddress & 0xf8) >> 3, hostAddress & 7);
5825 Bstr bname(name);
5826 pda.createObject();
5827 pda->init(this, bname, hostAddress, desiredGuestAddress, TRUE);
5828
5829 mPciDeviceAssignments.push_back(pda);
5830 return S_OK;
5831}
5832
5833STDMETHODIMP Machine::DetachHostPciDevice(LONG /*hostAddress*/)
5834{
5835 AutoCaller autoCaller(this);
5836 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5837 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5838
5839 return E_NOTIMPL;
5840}
5841
5842STDMETHODIMP Machine::COMGETTER(PciDeviceAssignments)(ComSafeArrayOut(IPciDeviceAttachment *, aAssignments))
5843{
5844 CheckComArgOutSafeArrayPointerValid(aAssignments);
5845
5846 AutoCaller autoCaller(this);
5847 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5848
5849 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5850
5851 SafeIfaceArray<IPciDeviceAttachment> assignments(mPciDeviceAssignments);
5852 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
5853
5854 return S_OK;
5855}
5856
5857STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
5858{
5859 CheckComArgOutPointerValid(aBandwidthControl);
5860
5861 AutoCaller autoCaller(this);
5862 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5863
5864 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
5865
5866 return S_OK;
5867}
5868
5869// public methods for internal purposes
5870/////////////////////////////////////////////////////////////////////////////
5871
5872/**
5873 * Adds the given IsModified_* flag to the dirty flags of the machine.
5874 * This must be called either during loadSettings or under the machine write lock.
5875 * @param fl
5876 */
5877void Machine::setModified(uint32_t fl)
5878{
5879 mData->flModifications |= fl;
5880}
5881
5882/**
5883 * Saves the registry entry of this machine to the given configuration node.
5884 *
5885 * @param aEntryNode Node to save the registry entry to.
5886 *
5887 * @note locks this object for reading.
5888 */
5889HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5890{
5891 AutoLimitedCaller autoCaller(this);
5892 AssertComRCReturnRC(autoCaller.rc());
5893
5894 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5895
5896 data.uuid = mData->mUuid;
5897 data.strSettingsFile = mData->m_strConfigFile;
5898
5899 return S_OK;
5900}
5901
5902/**
5903 * Calculates the absolute path of the given path taking the directory of the
5904 * machine settings file as the current directory.
5905 *
5906 * @param aPath Path to calculate the absolute path for.
5907 * @param aResult Where to put the result (used only on success, can be the
5908 * same Utf8Str instance as passed in @a aPath).
5909 * @return IPRT result.
5910 *
5911 * @note Locks this object for reading.
5912 */
5913int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5914{
5915 AutoCaller autoCaller(this);
5916 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5917
5918 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5919
5920 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5921
5922 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5923
5924 strSettingsDir.stripFilename();
5925 char folder[RTPATH_MAX];
5926 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5927 if (RT_SUCCESS(vrc))
5928 aResult = folder;
5929
5930 return vrc;
5931}
5932
5933/**
5934 * Copies strSource to strTarget, making it relative to the machine folder
5935 * if it is a subdirectory thereof, or simply copying it otherwise.
5936 *
5937 * @param strSource Path to evaluate and copy.
5938 * @param strTarget Buffer to receive target path.
5939 *
5940 * @note Locks this object for reading.
5941 */
5942void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5943 Utf8Str &strTarget)
5944{
5945 AutoCaller autoCaller(this);
5946 AssertComRCReturn(autoCaller.rc(), (void)0);
5947
5948 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5949
5950 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5951 // use strTarget as a temporary buffer to hold the machine settings dir
5952 strTarget = mData->m_strConfigFileFull;
5953 strTarget.stripFilename();
5954 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5955 // is relative: then append what's left
5956 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
5957 else
5958 // is not relative: then overwrite
5959 strTarget = strSource;
5960}
5961
5962/**
5963 * Returns the full path to the machine's log folder in the
5964 * \a aLogFolder argument.
5965 */
5966void Machine::getLogFolder(Utf8Str &aLogFolder)
5967{
5968 AutoCaller autoCaller(this);
5969 AssertComRCReturnVoid(autoCaller.rc());
5970
5971 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5972
5973 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
5974 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
5975 aLogFolder.append(RTPATH_DELIMITER);
5976 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
5977}
5978
5979/**
5980 * Returns the full path to the machine's log file for an given index.
5981 */
5982Utf8Str Machine::queryLogFilename(ULONG idx)
5983{
5984 Utf8Str logFolder;
5985 getLogFolder(logFolder);
5986 Assert(logFolder.length());
5987 Utf8Str log;
5988 if (idx == 0)
5989 log = Utf8StrFmt("%s%cVBox.log",
5990 logFolder.c_str(), RTPATH_DELIMITER);
5991 else
5992 log = Utf8StrFmt("%s%cVBox.log.%d",
5993 logFolder.c_str(), RTPATH_DELIMITER, idx);
5994 return log;
5995}
5996
5997/**
5998 * @note Locks this object for writing, calls the client process
5999 * (inside the lock).
6000 */
6001HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
6002 IN_BSTR aType,
6003 IN_BSTR aEnvironment,
6004 ProgressProxy *aProgress)
6005{
6006 LogFlowThisFuncEnter();
6007
6008 AssertReturn(aControl, E_FAIL);
6009 AssertReturn(aProgress, E_FAIL);
6010
6011 AutoCaller autoCaller(this);
6012 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6013
6014 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6015
6016 if (!mData->mRegistered)
6017 return setError(E_UNEXPECTED,
6018 tr("The machine '%s' is not registered"),
6019 mUserData->s.strName.c_str());
6020
6021 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6022
6023 if ( mData->mSession.mState == SessionState_Locked
6024 || mData->mSession.mState == SessionState_Spawning
6025 || mData->mSession.mState == SessionState_Unlocking)
6026 return setError(VBOX_E_INVALID_OBJECT_STATE,
6027 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6028 mUserData->s.strName.c_str());
6029
6030 /* may not be busy */
6031 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6032
6033 /* get the path to the executable */
6034 char szPath[RTPATH_MAX];
6035 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6036 size_t sz = strlen(szPath);
6037 szPath[sz++] = RTPATH_DELIMITER;
6038 szPath[sz] = 0;
6039 char *cmd = szPath + sz;
6040 sz = RTPATH_MAX - sz;
6041
6042 int vrc = VINF_SUCCESS;
6043 RTPROCESS pid = NIL_RTPROCESS;
6044
6045 RTENV env = RTENV_DEFAULT;
6046
6047 if (aEnvironment != NULL && *aEnvironment)
6048 {
6049 char *newEnvStr = NULL;
6050
6051 do
6052 {
6053 /* clone the current environment */
6054 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6055 AssertRCBreakStmt(vrc2, vrc = vrc2);
6056
6057 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
6058 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6059
6060 /* put new variables to the environment
6061 * (ignore empty variable names here since RTEnv API
6062 * intentionally doesn't do that) */
6063 char *var = newEnvStr;
6064 for (char *p = newEnvStr; *p; ++p)
6065 {
6066 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6067 {
6068 *p = '\0';
6069 if (*var)
6070 {
6071 char *val = strchr(var, '=');
6072 if (val)
6073 {
6074 *val++ = '\0';
6075 vrc2 = RTEnvSetEx(env, var, val);
6076 }
6077 else
6078 vrc2 = RTEnvUnsetEx(env, var);
6079 if (RT_FAILURE(vrc2))
6080 break;
6081 }
6082 var = p + 1;
6083 }
6084 }
6085 if (RT_SUCCESS(vrc2) && *var)
6086 vrc2 = RTEnvPutEx(env, var);
6087
6088 AssertRCBreakStmt(vrc2, vrc = vrc2);
6089 }
6090 while (0);
6091
6092 if (newEnvStr != NULL)
6093 RTStrFree(newEnvStr);
6094 }
6095
6096 Utf8Str strType(aType);
6097
6098 /* Qt is default */
6099#ifdef VBOX_WITH_QTGUI
6100 if (strType == "gui" || strType == "GUI/Qt")
6101 {
6102# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6103 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6104# else
6105 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6106# endif
6107 Assert(sz >= sizeof(VirtualBox_exe));
6108 strcpy(cmd, VirtualBox_exe);
6109
6110 Utf8Str idStr = mData->mUuid.toString();
6111 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6112 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6113 }
6114#else /* !VBOX_WITH_QTGUI */
6115 if (0)
6116 ;
6117#endif /* VBOX_WITH_QTGUI */
6118
6119 else
6120
6121#ifdef VBOX_WITH_VBOXSDL
6122 if (strType == "sdl" || strType == "GUI/SDL")
6123 {
6124 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6125 Assert(sz >= sizeof(VBoxSDL_exe));
6126 strcpy(cmd, VBoxSDL_exe);
6127
6128 Utf8Str idStr = mData->mUuid.toString();
6129 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6130 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6131 }
6132#else /* !VBOX_WITH_VBOXSDL */
6133 if (0)
6134 ;
6135#endif /* !VBOX_WITH_VBOXSDL */
6136
6137 else
6138
6139#ifdef VBOX_WITH_HEADLESS
6140 if ( strType == "headless"
6141 || strType == "capture"
6142 || strType == "vrdp" /* Deprecated. Same as headless. */
6143 )
6144 {
6145 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6146 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6147 * and a VM works even if the server has not been installed.
6148 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6149 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6150 * differently in 4.0 and 3.x.
6151 */
6152 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6153 Assert(sz >= sizeof(VBoxHeadless_exe));
6154 strcpy(cmd, VBoxHeadless_exe);
6155
6156 Utf8Str idStr = mData->mUuid.toString();
6157 /* Leave space for "--capture" arg. */
6158 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0, 0 };
6159 if (strType == "capture")
6160 {
6161 unsigned pos = RT_ELEMENTS(args) - 2;
6162 args[pos] = "--capture";
6163 }
6164 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6165 }
6166#else /* !VBOX_WITH_HEADLESS */
6167 if (0)
6168 ;
6169#endif /* !VBOX_WITH_HEADLESS */
6170 else
6171 {
6172 RTEnvDestroy(env);
6173 return setError(E_INVALIDARG,
6174 tr("Invalid session type: '%s'"),
6175 strType.c_str());
6176 }
6177
6178 RTEnvDestroy(env);
6179
6180 if (RT_FAILURE(vrc))
6181 return setError(VBOX_E_IPRT_ERROR,
6182 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6183 mUserData->s.strName.c_str(), vrc);
6184
6185 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6186
6187 /*
6188 * Note that we don't leave the lock here before calling the client,
6189 * because it doesn't need to call us back if called with a NULL argument.
6190 * Leaving the lock here is dangerous because we didn't prepare the
6191 * launch data yet, but the client we've just started may happen to be
6192 * too fast and call openSession() that will fail (because of PID, etc.),
6193 * so that the Machine will never get out of the Spawning session state.
6194 */
6195
6196 /* inform the session that it will be a remote one */
6197 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6198 HRESULT rc = aControl->AssignMachine(NULL);
6199 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6200
6201 if (FAILED(rc))
6202 {
6203 /* restore the session state */
6204 mData->mSession.mState = SessionState_Unlocked;
6205 /* The failure may occur w/o any error info (from RPC), so provide one */
6206 return setError(VBOX_E_VM_ERROR,
6207 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6208 }
6209
6210 /* attach launch data to the machine */
6211 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6212 mData->mSession.mRemoteControls.push_back (aControl);
6213 mData->mSession.mProgress = aProgress;
6214 mData->mSession.mPid = pid;
6215 mData->mSession.mState = SessionState_Spawning;
6216 mData->mSession.mType = strType;
6217
6218 LogFlowThisFuncLeave();
6219 return S_OK;
6220}
6221
6222/**
6223 * Returns @c true if the given machine has an open direct session and returns
6224 * the session machine instance and additional session data (on some platforms)
6225 * if so.
6226 *
6227 * Note that when the method returns @c false, the arguments remain unchanged.
6228 *
6229 * @param aMachine Session machine object.
6230 * @param aControl Direct session control object (optional).
6231 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6232 *
6233 * @note locks this object for reading.
6234 */
6235#if defined(RT_OS_WINDOWS)
6236bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6237 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6238 HANDLE *aIPCSem /*= NULL*/,
6239 bool aAllowClosing /*= false*/)
6240#elif defined(RT_OS_OS2)
6241bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6242 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6243 HMTX *aIPCSem /*= NULL*/,
6244 bool aAllowClosing /*= false*/)
6245#else
6246bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6247 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6248 bool aAllowClosing /*= false*/)
6249#endif
6250{
6251 AutoLimitedCaller autoCaller(this);
6252 AssertComRCReturn(autoCaller.rc(), false);
6253
6254 /* just return false for inaccessible machines */
6255 if (autoCaller.state() != Ready)
6256 return false;
6257
6258 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6259
6260 if ( mData->mSession.mState == SessionState_Locked
6261 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6262 )
6263 {
6264 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6265
6266 aMachine = mData->mSession.mMachine;
6267
6268 if (aControl != NULL)
6269 *aControl = mData->mSession.mDirectControl;
6270
6271#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6272 /* Additional session data */
6273 if (aIPCSem != NULL)
6274 *aIPCSem = aMachine->mIPCSem;
6275#endif
6276 return true;
6277 }
6278
6279 return false;
6280}
6281
6282/**
6283 * Returns @c true if the given machine has an spawning direct session and
6284 * returns and additional session data (on some platforms) if so.
6285 *
6286 * Note that when the method returns @c false, the arguments remain unchanged.
6287 *
6288 * @param aPID PID of the spawned direct session process.
6289 *
6290 * @note locks this object for reading.
6291 */
6292#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6293bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6294#else
6295bool Machine::isSessionSpawning()
6296#endif
6297{
6298 AutoLimitedCaller autoCaller(this);
6299 AssertComRCReturn(autoCaller.rc(), false);
6300
6301 /* just return false for inaccessible machines */
6302 if (autoCaller.state() != Ready)
6303 return false;
6304
6305 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6306
6307 if (mData->mSession.mState == SessionState_Spawning)
6308 {
6309#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6310 /* Additional session data */
6311 if (aPID != NULL)
6312 {
6313 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6314 *aPID = mData->mSession.mPid;
6315 }
6316#endif
6317 return true;
6318 }
6319
6320 return false;
6321}
6322
6323/**
6324 * Called from the client watcher thread to check for unexpected client process
6325 * death during Session_Spawning state (e.g. before it successfully opened a
6326 * direct session).
6327 *
6328 * On Win32 and on OS/2, this method is called only when we've got the
6329 * direct client's process termination notification, so it always returns @c
6330 * true.
6331 *
6332 * On other platforms, this method returns @c true if the client process is
6333 * terminated and @c false if it's still alive.
6334 *
6335 * @note Locks this object for writing.
6336 */
6337bool Machine::checkForSpawnFailure()
6338{
6339 AutoCaller autoCaller(this);
6340 if (!autoCaller.isOk())
6341 {
6342 /* nothing to do */
6343 LogFlowThisFunc(("Already uninitialized!\n"));
6344 return true;
6345 }
6346
6347 /* VirtualBox::addProcessToReap() needs a write lock */
6348 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6349
6350 if (mData->mSession.mState != SessionState_Spawning)
6351 {
6352 /* nothing to do */
6353 LogFlowThisFunc(("Not spawning any more!\n"));
6354 return true;
6355 }
6356
6357 HRESULT rc = S_OK;
6358
6359#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6360
6361 /* the process was already unexpectedly terminated, we just need to set an
6362 * error and finalize session spawning */
6363 rc = setError(E_FAIL,
6364 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6365 getName().c_str());
6366#else
6367
6368 /* PID not yet initialized, skip check. */
6369 if (mData->mSession.mPid == NIL_RTPROCESS)
6370 return false;
6371
6372 RTPROCSTATUS status;
6373 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6374 &status);
6375
6376 if (vrc != VERR_PROCESS_RUNNING)
6377 {
6378 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6379 rc = setError(E_FAIL,
6380 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6381 getName().c_str(), status.iStatus);
6382 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6383 rc = setError(E_FAIL,
6384 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6385 getName().c_str(), status.iStatus);
6386 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6387 rc = setError(E_FAIL,
6388 tr("The virtual machine '%s' has terminated abnormally"),
6389 getName().c_str(), status.iStatus);
6390 else
6391 rc = setError(E_FAIL,
6392 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6393 getName().c_str(), rc);
6394 }
6395
6396#endif
6397
6398 if (FAILED(rc))
6399 {
6400 /* Close the remote session, remove the remote control from the list
6401 * and reset session state to Closed (@note keep the code in sync with
6402 * the relevant part in checkForSpawnFailure()). */
6403
6404 Assert(mData->mSession.mRemoteControls.size() == 1);
6405 if (mData->mSession.mRemoteControls.size() == 1)
6406 {
6407 ErrorInfoKeeper eik;
6408 mData->mSession.mRemoteControls.front()->Uninitialize();
6409 }
6410
6411 mData->mSession.mRemoteControls.clear();
6412 mData->mSession.mState = SessionState_Unlocked;
6413
6414 /* finalize the progress after setting the state */
6415 if (!mData->mSession.mProgress.isNull())
6416 {
6417 mData->mSession.mProgress->notifyComplete(rc);
6418 mData->mSession.mProgress.setNull();
6419 }
6420
6421 mParent->addProcessToReap(mData->mSession.mPid);
6422 mData->mSession.mPid = NIL_RTPROCESS;
6423
6424 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6425 return true;
6426 }
6427
6428 return false;
6429}
6430
6431/**
6432 * Checks whether the machine can be registered. If so, commits and saves
6433 * all settings.
6434 *
6435 * @note Must be called from mParent's write lock. Locks this object and
6436 * children for writing.
6437 */
6438HRESULT Machine::prepareRegister()
6439{
6440 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6441
6442 AutoLimitedCaller autoCaller(this);
6443 AssertComRCReturnRC(autoCaller.rc());
6444
6445 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6446
6447 /* wait for state dependents to drop to zero */
6448 ensureNoStateDependencies();
6449
6450 if (!mData->mAccessible)
6451 return setError(VBOX_E_INVALID_OBJECT_STATE,
6452 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6453 mUserData->s.strName.c_str(),
6454 mData->mUuid.toString().c_str());
6455
6456 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6457
6458 if (mData->mRegistered)
6459 return setError(VBOX_E_INVALID_OBJECT_STATE,
6460 tr("The machine '%s' with UUID {%s} is already registered"),
6461 mUserData->s.strName.c_str(),
6462 mData->mUuid.toString().c_str());
6463
6464 HRESULT rc = S_OK;
6465
6466 // Ensure the settings are saved. If we are going to be registered and
6467 // no config file exists yet, create it by calling saveSettings() too.
6468 if ( (mData->flModifications)
6469 || (!mData->pMachineConfigFile->fileExists())
6470 )
6471 {
6472 rc = saveSettings(NULL);
6473 // no need to check whether VirtualBox.xml needs saving too since
6474 // we can't have a machine XML file rename pending
6475 if (FAILED(rc)) return rc;
6476 }
6477
6478 /* more config checking goes here */
6479
6480 if (SUCCEEDED(rc))
6481 {
6482 /* we may have had implicit modifications we want to fix on success */
6483 commit();
6484
6485 mData->mRegistered = true;
6486 }
6487 else
6488 {
6489 /* we may have had implicit modifications we want to cancel on failure*/
6490 rollback(false /* aNotify */);
6491 }
6492
6493 return rc;
6494}
6495
6496/**
6497 * Increases the number of objects dependent on the machine state or on the
6498 * registered state. Guarantees that these two states will not change at least
6499 * until #releaseStateDependency() is called.
6500 *
6501 * Depending on the @a aDepType value, additional state checks may be made.
6502 * These checks will set extended error info on failure. See
6503 * #checkStateDependency() for more info.
6504 *
6505 * If this method returns a failure, the dependency is not added and the caller
6506 * is not allowed to rely on any particular machine state or registration state
6507 * value and may return the failed result code to the upper level.
6508 *
6509 * @param aDepType Dependency type to add.
6510 * @param aState Current machine state (NULL if not interested).
6511 * @param aRegistered Current registered state (NULL if not interested).
6512 *
6513 * @note Locks this object for writing.
6514 */
6515HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6516 MachineState_T *aState /* = NULL */,
6517 BOOL *aRegistered /* = NULL */)
6518{
6519 AutoCaller autoCaller(this);
6520 AssertComRCReturnRC(autoCaller.rc());
6521
6522 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6523
6524 HRESULT rc = checkStateDependency(aDepType);
6525 if (FAILED(rc)) return rc;
6526
6527 {
6528 if (mData->mMachineStateChangePending != 0)
6529 {
6530 /* ensureNoStateDependencies() is waiting for state dependencies to
6531 * drop to zero so don't add more. It may make sense to wait a bit
6532 * and retry before reporting an error (since the pending state
6533 * transition should be really quick) but let's just assert for
6534 * now to see if it ever happens on practice. */
6535
6536 AssertFailed();
6537
6538 return setError(E_ACCESSDENIED,
6539 tr("Machine state change is in progress. Please retry the operation later."));
6540 }
6541
6542 ++mData->mMachineStateDeps;
6543 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6544 }
6545
6546 if (aState)
6547 *aState = mData->mMachineState;
6548 if (aRegistered)
6549 *aRegistered = mData->mRegistered;
6550
6551 return S_OK;
6552}
6553
6554/**
6555 * Decreases the number of objects dependent on the machine state.
6556 * Must always complete the #addStateDependency() call after the state
6557 * dependency is no more necessary.
6558 */
6559void Machine::releaseStateDependency()
6560{
6561 AutoCaller autoCaller(this);
6562 AssertComRCReturnVoid(autoCaller.rc());
6563
6564 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6565
6566 /* releaseStateDependency() w/o addStateDependency()? */
6567 AssertReturnVoid(mData->mMachineStateDeps != 0);
6568 -- mData->mMachineStateDeps;
6569
6570 if (mData->mMachineStateDeps == 0)
6571 {
6572 /* inform ensureNoStateDependencies() that there are no more deps */
6573 if (mData->mMachineStateChangePending != 0)
6574 {
6575 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6576 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6577 }
6578 }
6579}
6580
6581// protected methods
6582/////////////////////////////////////////////////////////////////////////////
6583
6584/**
6585 * Performs machine state checks based on the @a aDepType value. If a check
6586 * fails, this method will set extended error info, otherwise it will return
6587 * S_OK. It is supposed, that on failure, the caller will immediately return
6588 * the return value of this method to the upper level.
6589 *
6590 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6591 *
6592 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6593 * current state of this machine object allows to change settings of the
6594 * machine (i.e. the machine is not registered, or registered but not running
6595 * and not saved). It is useful to call this method from Machine setters
6596 * before performing any change.
6597 *
6598 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6599 * as for MutableStateDep except that if the machine is saved, S_OK is also
6600 * returned. This is useful in setters which allow changing machine
6601 * properties when it is in the saved state.
6602 *
6603 * @param aDepType Dependency type to check.
6604 *
6605 * @note Non Machine based classes should use #addStateDependency() and
6606 * #releaseStateDependency() methods or the smart AutoStateDependency
6607 * template.
6608 *
6609 * @note This method must be called from under this object's read or write
6610 * lock.
6611 */
6612HRESULT Machine::checkStateDependency(StateDependency aDepType)
6613{
6614 switch (aDepType)
6615 {
6616 case AnyStateDep:
6617 {
6618 break;
6619 }
6620 case MutableStateDep:
6621 {
6622 if ( mData->mRegistered
6623 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6624 || ( mData->mMachineState != MachineState_Paused
6625 && mData->mMachineState != MachineState_Running
6626 && mData->mMachineState != MachineState_Aborted
6627 && mData->mMachineState != MachineState_Teleported
6628 && mData->mMachineState != MachineState_PoweredOff
6629 )
6630 )
6631 )
6632 return setError(VBOX_E_INVALID_VM_STATE,
6633 tr("The machine is not mutable (state is %s)"),
6634 Global::stringifyMachineState(mData->mMachineState));
6635 break;
6636 }
6637 case MutableOrSavedStateDep:
6638 {
6639 if ( mData->mRegistered
6640 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6641 || ( mData->mMachineState != MachineState_Paused
6642 && mData->mMachineState != MachineState_Running
6643 && mData->mMachineState != MachineState_Aborted
6644 && mData->mMachineState != MachineState_Teleported
6645 && mData->mMachineState != MachineState_Saved
6646 && mData->mMachineState != MachineState_PoweredOff
6647 )
6648 )
6649 )
6650 return setError(VBOX_E_INVALID_VM_STATE,
6651 tr("The machine is not mutable (state is %s)"),
6652 Global::stringifyMachineState(mData->mMachineState));
6653 break;
6654 }
6655 }
6656
6657 return S_OK;
6658}
6659
6660/**
6661 * Helper to initialize all associated child objects and allocate data
6662 * structures.
6663 *
6664 * This method must be called as a part of the object's initialization procedure
6665 * (usually done in the #init() method).
6666 *
6667 * @note Must be called only from #init() or from #registeredInit().
6668 */
6669HRESULT Machine::initDataAndChildObjects()
6670{
6671 AutoCaller autoCaller(this);
6672 AssertComRCReturnRC(autoCaller.rc());
6673 AssertComRCReturn(autoCaller.state() == InInit ||
6674 autoCaller.state() == Limited, E_FAIL);
6675
6676 AssertReturn(!mData->mAccessible, E_FAIL);
6677
6678 /* allocate data structures */
6679 mSSData.allocate();
6680 mUserData.allocate();
6681 mHWData.allocate();
6682 mMediaData.allocate();
6683 mStorageControllers.allocate();
6684
6685 /* initialize mOSTypeId */
6686 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6687
6688 /* create associated BIOS settings object */
6689 unconst(mBIOSSettings).createObject();
6690 mBIOSSettings->init(this);
6691
6692 /* create an associated VRDE object (default is disabled) */
6693 unconst(mVRDEServer).createObject();
6694 mVRDEServer->init(this);
6695
6696 /* create associated serial port objects */
6697 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6698 {
6699 unconst(mSerialPorts[slot]).createObject();
6700 mSerialPorts[slot]->init(this, slot);
6701 }
6702
6703 /* create associated parallel port objects */
6704 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6705 {
6706 unconst(mParallelPorts[slot]).createObject();
6707 mParallelPorts[slot]->init(this, slot);
6708 }
6709
6710 /* create the audio adapter object (always present, default is disabled) */
6711 unconst(mAudioAdapter).createObject();
6712 mAudioAdapter->init(this);
6713
6714 /* create the USB controller object (always present, default is disabled) */
6715 unconst(mUSBController).createObject();
6716 mUSBController->init(this);
6717
6718 /* create associated network adapter objects */
6719 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6720 {
6721 unconst(mNetworkAdapters[slot]).createObject();
6722 mNetworkAdapters[slot]->init(this, slot);
6723 }
6724
6725 /* create the bandwidth control */
6726 unconst(mBandwidthControl).createObject();
6727 mBandwidthControl->init(this);
6728
6729 return S_OK;
6730}
6731
6732/**
6733 * Helper to uninitialize all associated child objects and to free all data
6734 * structures.
6735 *
6736 * This method must be called as a part of the object's uninitialization
6737 * procedure (usually done in the #uninit() method).
6738 *
6739 * @note Must be called only from #uninit() or from #registeredInit().
6740 */
6741void Machine::uninitDataAndChildObjects()
6742{
6743 AutoCaller autoCaller(this);
6744 AssertComRCReturnVoid(autoCaller.rc());
6745 AssertComRCReturnVoid( autoCaller.state() == InUninit
6746 || autoCaller.state() == Limited);
6747
6748 /* tell all our other child objects we've been uninitialized */
6749 if (mBandwidthControl)
6750 {
6751 mBandwidthControl->uninit();
6752 unconst(mBandwidthControl).setNull();
6753 }
6754
6755 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6756 {
6757 if (mNetworkAdapters[slot])
6758 {
6759 mNetworkAdapters[slot]->uninit();
6760 unconst(mNetworkAdapters[slot]).setNull();
6761 }
6762 }
6763
6764 if (mUSBController)
6765 {
6766 mUSBController->uninit();
6767 unconst(mUSBController).setNull();
6768 }
6769
6770 if (mAudioAdapter)
6771 {
6772 mAudioAdapter->uninit();
6773 unconst(mAudioAdapter).setNull();
6774 }
6775
6776 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6777 {
6778 if (mParallelPorts[slot])
6779 {
6780 mParallelPorts[slot]->uninit();
6781 unconst(mParallelPorts[slot]).setNull();
6782 }
6783 }
6784
6785 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6786 {
6787 if (mSerialPorts[slot])
6788 {
6789 mSerialPorts[slot]->uninit();
6790 unconst(mSerialPorts[slot]).setNull();
6791 }
6792 }
6793
6794 if (mVRDEServer)
6795 {
6796 mVRDEServer->uninit();
6797 unconst(mVRDEServer).setNull();
6798 }
6799
6800 if (mBIOSSettings)
6801 {
6802 mBIOSSettings->uninit();
6803 unconst(mBIOSSettings).setNull();
6804 }
6805
6806 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6807 * instance is uninitialized; SessionMachine instances refer to real
6808 * Machine hard disks). This is necessary for a clean re-initialization of
6809 * the VM after successfully re-checking the accessibility state. Note
6810 * that in case of normal Machine or SnapshotMachine uninitialization (as
6811 * a result of unregistering or deleting the snapshot), outdated hard
6812 * disk attachments will already be uninitialized and deleted, so this
6813 * code will not affect them. */
6814 if ( !!mMediaData
6815 && (!isSessionMachine())
6816 )
6817 {
6818 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6819 it != mMediaData->mAttachments.end();
6820 ++it)
6821 {
6822 ComObjPtr<Medium> hd = (*it)->getMedium();
6823 if (hd.isNull())
6824 continue;
6825 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6826 AssertComRC(rc);
6827 }
6828 }
6829
6830 if (!isSessionMachine() && !isSnapshotMachine())
6831 {
6832 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6833 if (mData->mFirstSnapshot)
6834 {
6835 // snapshots tree is protected by media write lock; strictly
6836 // this isn't necessary here since we're deleting the entire
6837 // machine, but otherwise we assert in Snapshot::uninit()
6838 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6839 mData->mFirstSnapshot->uninit();
6840 mData->mFirstSnapshot.setNull();
6841 }
6842
6843 mData->mCurrentSnapshot.setNull();
6844 }
6845
6846 /* free data structures (the essential mData structure is not freed here
6847 * since it may be still in use) */
6848 mMediaData.free();
6849 mStorageControllers.free();
6850 mHWData.free();
6851 mUserData.free();
6852 mSSData.free();
6853}
6854
6855/**
6856 * Returns a pointer to the Machine object for this machine that acts like a
6857 * parent for complex machine data objects such as shared folders, etc.
6858 *
6859 * For primary Machine objects and for SnapshotMachine objects, returns this
6860 * object's pointer itself. For SessionMachine objects, returns the peer
6861 * (primary) machine pointer.
6862 */
6863Machine* Machine::getMachine()
6864{
6865 if (isSessionMachine())
6866 return (Machine*)mPeer;
6867 return this;
6868}
6869
6870/**
6871 * Makes sure that there are no machine state dependents. If necessary, waits
6872 * for the number of dependents to drop to zero.
6873 *
6874 * Make sure this method is called from under this object's write lock to
6875 * guarantee that no new dependents may be added when this method returns
6876 * control to the caller.
6877 *
6878 * @note Locks this object for writing. The lock will be released while waiting
6879 * (if necessary).
6880 *
6881 * @warning To be used only in methods that change the machine state!
6882 */
6883void Machine::ensureNoStateDependencies()
6884{
6885 AssertReturnVoid(isWriteLockOnCurrentThread());
6886
6887 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6888
6889 /* Wait for all state dependents if necessary */
6890 if (mData->mMachineStateDeps != 0)
6891 {
6892 /* lazy semaphore creation */
6893 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6894 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6895
6896 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6897 mData->mMachineStateDeps));
6898
6899 ++mData->mMachineStateChangePending;
6900
6901 /* reset the semaphore before waiting, the last dependent will signal
6902 * it */
6903 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6904
6905 alock.leave();
6906
6907 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6908
6909 alock.enter();
6910
6911 -- mData->mMachineStateChangePending;
6912 }
6913}
6914
6915/**
6916 * Changes the machine state and informs callbacks.
6917 *
6918 * This method is not intended to fail so it either returns S_OK or asserts (and
6919 * returns a failure).
6920 *
6921 * @note Locks this object for writing.
6922 */
6923HRESULT Machine::setMachineState(MachineState_T aMachineState)
6924{
6925 LogFlowThisFuncEnter();
6926 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6927
6928 AutoCaller autoCaller(this);
6929 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6930
6931 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6932
6933 /* wait for state dependents to drop to zero */
6934 ensureNoStateDependencies();
6935
6936 if (mData->mMachineState != aMachineState)
6937 {
6938 mData->mMachineState = aMachineState;
6939
6940 RTTimeNow(&mData->mLastStateChange);
6941
6942 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6943 }
6944
6945 LogFlowThisFuncLeave();
6946 return S_OK;
6947}
6948
6949/**
6950 * Searches for a shared folder with the given logical name
6951 * in the collection of shared folders.
6952 *
6953 * @param aName logical name of the shared folder
6954 * @param aSharedFolder where to return the found object
6955 * @param aSetError whether to set the error info if the folder is
6956 * not found
6957 * @return
6958 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6959 *
6960 * @note
6961 * must be called from under the object's lock!
6962 */
6963HRESULT Machine::findSharedFolder(CBSTR aName,
6964 ComObjPtr<SharedFolder> &aSharedFolder,
6965 bool aSetError /* = false */)
6966{
6967 bool found = false;
6968 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6969 !found && it != mHWData->mSharedFolders.end();
6970 ++it)
6971 {
6972 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6973 found = (*it)->getName() == aName;
6974 if (found)
6975 aSharedFolder = *it;
6976 }
6977
6978 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6979
6980 if (aSetError && !found)
6981 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6982
6983 return rc;
6984}
6985
6986/**
6987 * Initializes all machine instance data from the given settings structures
6988 * from XML. The exception is the machine UUID which needs special handling
6989 * depending on the caller's use case, so the caller needs to set that herself.
6990 *
6991 * This gets called in several contexts during machine initialization:
6992 *
6993 * -- When machine XML exists on disk already and needs to be loaded into memory,
6994 * for example, from registeredInit() to load all registered machines on
6995 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
6996 * attached to the machine should be part of some media registry already.
6997 *
6998 * -- During OVF import, when a machine config has been constructed from an
6999 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7000 * ensure that the media listed as attachments in the config (which have
7001 * been imported from the OVF) receive the correct registry ID.
7002 *
7003 * @param config Machine settings from XML.
7004 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7005 * @return
7006 */
7007HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7008 const Guid *puuidRegistry)
7009{
7010 // copy name, description, OS type, teleporter, UTC etc.
7011 mUserData->s = config.machineUserData;
7012
7013 // look up the object by Id to check it is valid
7014 ComPtr<IGuestOSType> guestOSType;
7015 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7016 guestOSType.asOutParam());
7017 if (FAILED(rc)) return rc;
7018
7019 // stateFile (optional)
7020 if (config.strStateFile.isEmpty())
7021 mSSData->mStateFilePath.setNull();
7022 else
7023 {
7024 Utf8Str stateFilePathFull(config.strStateFile);
7025 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7026 if (RT_FAILURE(vrc))
7027 return setError(E_FAIL,
7028 tr("Invalid saved state file path '%s' (%Rrc)"),
7029 config.strStateFile.c_str(),
7030 vrc);
7031 mSSData->mStateFilePath = stateFilePathFull;
7032 }
7033
7034 // snapshot folder needs special processing so set it again
7035 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7036 if (FAILED(rc)) return rc;
7037
7038 /* currentStateModified (optional, default is true) */
7039 mData->mCurrentStateModified = config.fCurrentStateModified;
7040
7041 mData->mLastStateChange = config.timeLastStateChange;
7042
7043 /*
7044 * note: all mUserData members must be assigned prior this point because
7045 * we need to commit changes in order to let mUserData be shared by all
7046 * snapshot machine instances.
7047 */
7048 mUserData.commitCopy();
7049
7050 // machine registry, if present (must be loaded before snapshots)
7051 if (config.canHaveOwnMediaRegistry())
7052 {
7053 // determine machine folder
7054 Utf8Str strMachineFolder = getSettingsFileFull();
7055 strMachineFolder.stripFilename();
7056 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7057 config.mediaRegistry,
7058 strMachineFolder);
7059 if (FAILED(rc)) return rc;
7060 }
7061
7062 /* Snapshot node (optional) */
7063 size_t cRootSnapshots;
7064 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7065 {
7066 // there must be only one root snapshot
7067 Assert(cRootSnapshots == 1);
7068
7069 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7070
7071 rc = loadSnapshot(snap,
7072 config.uuidCurrentSnapshot,
7073 NULL); // no parent == first snapshot
7074 if (FAILED(rc)) return rc;
7075 }
7076
7077 // hardware data
7078 rc = loadHardware(config.hardwareMachine);
7079 if (FAILED(rc)) return rc;
7080
7081 // load storage controllers
7082 rc = loadStorageControllers(config.storageMachine,
7083 puuidRegistry,
7084 NULL /* puuidSnapshot */);
7085 if (FAILED(rc)) return rc;
7086
7087 /*
7088 * NOTE: the assignment below must be the last thing to do,
7089 * otherwise it will be not possible to change the settings
7090 * somewhere in the code above because all setters will be
7091 * blocked by checkStateDependency(MutableStateDep).
7092 */
7093
7094 /* set the machine state to Aborted or Saved when appropriate */
7095 if (config.fAborted)
7096 {
7097 Assert(!mSSData->mStateFilePath.isEmpty());
7098 mSSData->mStateFilePath.setNull();
7099
7100 /* no need to use setMachineState() during init() */
7101 mData->mMachineState = MachineState_Aborted;
7102 }
7103 else if (!mSSData->mStateFilePath.isEmpty())
7104 {
7105 /* no need to use setMachineState() during init() */
7106 mData->mMachineState = MachineState_Saved;
7107 }
7108
7109 // after loading settings, we are no longer different from the XML on disk
7110 mData->flModifications = 0;
7111
7112 return S_OK;
7113}
7114
7115/**
7116 * Recursively loads all snapshots starting from the given.
7117 *
7118 * @param aNode <Snapshot> node.
7119 * @param aCurSnapshotId Current snapshot ID from the settings file.
7120 * @param aParentSnapshot Parent snapshot.
7121 */
7122HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7123 const Guid &aCurSnapshotId,
7124 Snapshot *aParentSnapshot)
7125{
7126 AssertReturn(!isSnapshotMachine(), E_FAIL);
7127 AssertReturn(!isSessionMachine(), E_FAIL);
7128
7129 HRESULT rc = S_OK;
7130
7131 Utf8Str strStateFile;
7132 if (!data.strStateFile.isEmpty())
7133 {
7134 /* optional */
7135 strStateFile = data.strStateFile;
7136 int vrc = calculateFullPath(strStateFile, strStateFile);
7137 if (RT_FAILURE(vrc))
7138 return setError(E_FAIL,
7139 tr("Invalid saved state file path '%s' (%Rrc)"),
7140 strStateFile.c_str(),
7141 vrc);
7142 }
7143
7144 /* create a snapshot machine object */
7145 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7146 pSnapshotMachine.createObject();
7147 rc = pSnapshotMachine->init(this,
7148 data.hardware,
7149 data.storage,
7150 data.uuid.ref(),
7151 strStateFile);
7152 if (FAILED(rc)) return rc;
7153
7154 /* create a snapshot object */
7155 ComObjPtr<Snapshot> pSnapshot;
7156 pSnapshot.createObject();
7157 /* initialize the snapshot */
7158 rc = pSnapshot->init(mParent, // VirtualBox object
7159 data.uuid,
7160 data.strName,
7161 data.strDescription,
7162 data.timestamp,
7163 pSnapshotMachine,
7164 aParentSnapshot);
7165 if (FAILED(rc)) return rc;
7166
7167 /* memorize the first snapshot if necessary */
7168 if (!mData->mFirstSnapshot)
7169 mData->mFirstSnapshot = pSnapshot;
7170
7171 /* memorize the current snapshot when appropriate */
7172 if ( !mData->mCurrentSnapshot
7173 && pSnapshot->getId() == aCurSnapshotId
7174 )
7175 mData->mCurrentSnapshot = pSnapshot;
7176
7177 // now create the children
7178 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7179 it != data.llChildSnapshots.end();
7180 ++it)
7181 {
7182 const settings::Snapshot &childData = *it;
7183 // recurse
7184 rc = loadSnapshot(childData,
7185 aCurSnapshotId,
7186 pSnapshot); // parent = the one we created above
7187 if (FAILED(rc)) return rc;
7188 }
7189
7190 return rc;
7191}
7192
7193/**
7194 * @param aNode <Hardware> node.
7195 */
7196HRESULT Machine::loadHardware(const settings::Hardware &data)
7197{
7198 AssertReturn(!isSessionMachine(), E_FAIL);
7199
7200 HRESULT rc = S_OK;
7201
7202 try
7203 {
7204 /* The hardware version attribute (optional). */
7205 mHWData->mHWVersion = data.strVersion;
7206 mHWData->mHardwareUUID = data.uuid;
7207
7208 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7209 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7210 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7211 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7212 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7213 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7214 mHWData->mPAEEnabled = data.fPAE;
7215 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7216
7217 mHWData->mCPUCount = data.cCPUs;
7218 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7219 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7220
7221 // cpu
7222 if (mHWData->mCPUHotPlugEnabled)
7223 {
7224 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7225 it != data.llCpus.end();
7226 ++it)
7227 {
7228 const settings::Cpu &cpu = *it;
7229
7230 mHWData->mCPUAttached[cpu.ulId] = true;
7231 }
7232 }
7233
7234 // cpuid leafs
7235 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7236 it != data.llCpuIdLeafs.end();
7237 ++it)
7238 {
7239 const settings::CpuIdLeaf &leaf = *it;
7240
7241 switch (leaf.ulId)
7242 {
7243 case 0x0:
7244 case 0x1:
7245 case 0x2:
7246 case 0x3:
7247 case 0x4:
7248 case 0x5:
7249 case 0x6:
7250 case 0x7:
7251 case 0x8:
7252 case 0x9:
7253 case 0xA:
7254 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7255 break;
7256
7257 case 0x80000000:
7258 case 0x80000001:
7259 case 0x80000002:
7260 case 0x80000003:
7261 case 0x80000004:
7262 case 0x80000005:
7263 case 0x80000006:
7264 case 0x80000007:
7265 case 0x80000008:
7266 case 0x80000009:
7267 case 0x8000000A:
7268 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7269 break;
7270
7271 default:
7272 /* just ignore */
7273 break;
7274 }
7275 }
7276
7277 mHWData->mMemorySize = data.ulMemorySizeMB;
7278 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7279
7280 // boot order
7281 for (size_t i = 0;
7282 i < RT_ELEMENTS(mHWData->mBootOrder);
7283 i++)
7284 {
7285 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7286 if (it == data.mapBootOrder.end())
7287 mHWData->mBootOrder[i] = DeviceType_Null;
7288 else
7289 mHWData->mBootOrder[i] = it->second;
7290 }
7291
7292 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7293 mHWData->mMonitorCount = data.cMonitors;
7294 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7295 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7296 mHWData->mFirmwareType = data.firmwareType;
7297 mHWData->mPointingHidType = data.pointingHidType;
7298 mHWData->mKeyboardHidType = data.keyboardHidType;
7299 mHWData->mChipsetType = data.chipsetType;
7300 mHWData->mHpetEnabled = data.fHpetEnabled;
7301
7302 /* VRDEServer */
7303 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7304 if (FAILED(rc)) return rc;
7305
7306 /* BIOS */
7307 rc = mBIOSSettings->loadSettings(data.biosSettings);
7308 if (FAILED(rc)) return rc;
7309
7310 /* USB Controller */
7311 rc = mUSBController->loadSettings(data.usbController);
7312 if (FAILED(rc)) return rc;
7313
7314 // network adapters
7315 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7316 it != data.llNetworkAdapters.end();
7317 ++it)
7318 {
7319 const settings::NetworkAdapter &nic = *it;
7320
7321 /* slot unicity is guaranteed by XML Schema */
7322 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7323 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7324 if (FAILED(rc)) return rc;
7325 }
7326
7327 // serial ports
7328 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7329 it != data.llSerialPorts.end();
7330 ++it)
7331 {
7332 const settings::SerialPort &s = *it;
7333
7334 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7335 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7336 if (FAILED(rc)) return rc;
7337 }
7338
7339 // parallel ports (optional)
7340 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7341 it != data.llParallelPorts.end();
7342 ++it)
7343 {
7344 const settings::ParallelPort &p = *it;
7345
7346 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7347 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7348 if (FAILED(rc)) return rc;
7349 }
7350
7351 /* AudioAdapter */
7352 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7353 if (FAILED(rc)) return rc;
7354
7355 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7356 it != data.llSharedFolders.end();
7357 ++it)
7358 {
7359 const settings::SharedFolder &sf = *it;
7360 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7361 Bstr(sf.strHostPath).raw(),
7362 sf.fWritable, sf.fAutoMount);
7363 if (FAILED(rc)) return rc;
7364 }
7365
7366 // Clipboard
7367 mHWData->mClipboardMode = data.clipboardMode;
7368
7369 // guest settings
7370 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7371
7372 // IO settings
7373 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7374 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7375
7376 // Bandwidth control
7377 rc = mBandwidthControl->loadSettings(data.ioSettings);
7378 if (FAILED(rc)) return rc;
7379
7380#ifdef VBOX_WITH_GUEST_PROPS
7381 /* Guest properties (optional) */
7382 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7383 it != data.llGuestProperties.end();
7384 ++it)
7385 {
7386 const settings::GuestProperty &prop = *it;
7387 uint32_t fFlags = guestProp::NILFLAG;
7388 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7389 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7390 mHWData->mGuestProperties.push_back(property);
7391 }
7392
7393 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7394#endif /* VBOX_WITH_GUEST_PROPS defined */
7395 }
7396 catch(std::bad_alloc &)
7397 {
7398 return E_OUTOFMEMORY;
7399 }
7400
7401 AssertComRC(rc);
7402 return rc;
7403}
7404
7405/**
7406 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7407 *
7408 * @param data
7409 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7410 * @param puuidSnapshot
7411 * @return
7412 */
7413HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7414 const Guid *puuidRegistry,
7415 const Guid *puuidSnapshot)
7416{
7417 AssertReturn(!isSessionMachine(), E_FAIL);
7418
7419 HRESULT rc = S_OK;
7420
7421 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7422 it != data.llStorageControllers.end();
7423 ++it)
7424 {
7425 const settings::StorageController &ctlData = *it;
7426
7427 ComObjPtr<StorageController> pCtl;
7428 /* Try to find one with the name first. */
7429 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7430 if (SUCCEEDED(rc))
7431 return setError(VBOX_E_OBJECT_IN_USE,
7432 tr("Storage controller named '%s' already exists"),
7433 ctlData.strName.c_str());
7434
7435 pCtl.createObject();
7436 rc = pCtl->init(this,
7437 ctlData.strName,
7438 ctlData.storageBus,
7439 ctlData.ulInstance,
7440 ctlData.fBootable);
7441 if (FAILED(rc)) return rc;
7442
7443 mStorageControllers->push_back(pCtl);
7444
7445 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7446 if (FAILED(rc)) return rc;
7447
7448 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7449 if (FAILED(rc)) return rc;
7450
7451 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7452 if (FAILED(rc)) return rc;
7453
7454 /* Set IDE emulation settings (only for AHCI controller). */
7455 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7456 {
7457 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7458 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7459 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7460 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7461 )
7462 return rc;
7463 }
7464
7465 /* Load the attached devices now. */
7466 rc = loadStorageDevices(pCtl,
7467 ctlData,
7468 puuidRegistry,
7469 puuidSnapshot);
7470 if (FAILED(rc)) return rc;
7471 }
7472
7473 return S_OK;
7474}
7475
7476/**
7477 * Called from loadStorageControllers for a controller's devices.
7478 *
7479 * @param aStorageController
7480 * @param data
7481 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7482 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7483 * @return
7484 */
7485HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7486 const settings::StorageController &data,
7487 const Guid *puuidRegistry,
7488 const Guid *puuidSnapshot)
7489{
7490 HRESULT rc = S_OK;
7491
7492 /* paranoia: detect duplicate attachments */
7493 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7494 it != data.llAttachedDevices.end();
7495 ++it)
7496 {
7497 const settings::AttachedDevice &ad = *it;
7498
7499 for (settings::AttachedDevicesList::const_iterator it2 = it;
7500 it2 != data.llAttachedDevices.end();
7501 ++it2)
7502 {
7503 if (it == it2)
7504 continue;
7505
7506 const settings::AttachedDevice &ad2 = *it2;
7507
7508 if ( ad.lPort == ad2.lPort
7509 && ad.lDevice == ad2.lDevice)
7510 {
7511 return setError(E_FAIL,
7512 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7513 aStorageController->getName().c_str(),
7514 ad.lPort,
7515 ad.lDevice,
7516 mUserData->s.strName.c_str());
7517 }
7518 }
7519 }
7520
7521 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7522 it != data.llAttachedDevices.end();
7523 ++it)
7524 {
7525 const settings::AttachedDevice &dev = *it;
7526 ComObjPtr<Medium> medium;
7527
7528 switch (dev.deviceType)
7529 {
7530 case DeviceType_Floppy:
7531 case DeviceType_DVD:
7532 if (dev.strHostDriveSrc.isNotEmpty())
7533 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
7534 else
7535 rc = mParent->findRemoveableMedium(dev.deviceType,
7536 dev.uuid,
7537 false /* fRefresh */,
7538 false /* aSetError */,
7539 medium);
7540 if (rc == VBOX_E_OBJECT_NOT_FOUND)
7541 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
7542 rc = S_OK;
7543 break;
7544
7545 case DeviceType_HardDisk:
7546 {
7547 /* find a hard disk by UUID */
7548 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7549 if (FAILED(rc))
7550 {
7551 if (isSnapshotMachine())
7552 {
7553 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7554 // so the user knows that the bad disk is in a snapshot somewhere
7555 com::ErrorInfo info;
7556 return setError(E_FAIL,
7557 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7558 puuidSnapshot->raw(),
7559 info.getText().raw());
7560 }
7561 else
7562 return rc;
7563 }
7564
7565 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7566
7567 if (medium->getType() == MediumType_Immutable)
7568 {
7569 if (isSnapshotMachine())
7570 return setError(E_FAIL,
7571 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7572 "of the virtual machine '%s' ('%s')"),
7573 medium->getLocationFull().c_str(),
7574 dev.uuid.raw(),
7575 puuidSnapshot->raw(),
7576 mUserData->s.strName.c_str(),
7577 mData->m_strConfigFileFull.c_str());
7578
7579 return setError(E_FAIL,
7580 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7581 medium->getLocationFull().c_str(),
7582 dev.uuid.raw(),
7583 mUserData->s.strName.c_str(),
7584 mData->m_strConfigFileFull.c_str());
7585 }
7586
7587 if (medium->getType() == MediumType_MultiAttach)
7588 {
7589 if (isSnapshotMachine())
7590 return setError(E_FAIL,
7591 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7592 "of the virtual machine '%s' ('%s')"),
7593 medium->getLocationFull().c_str(),
7594 dev.uuid.raw(),
7595 puuidSnapshot->raw(),
7596 mUserData->s.strName.c_str(),
7597 mData->m_strConfigFileFull.c_str());
7598
7599 return setError(E_FAIL,
7600 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7601 medium->getLocationFull().c_str(),
7602 dev.uuid.raw(),
7603 mUserData->s.strName.c_str(),
7604 mData->m_strConfigFileFull.c_str());
7605 }
7606
7607 if ( !isSnapshotMachine()
7608 && medium->getChildren().size() != 0
7609 )
7610 return setError(E_FAIL,
7611 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7612 "because it has %d differencing child hard disks"),
7613 medium->getLocationFull().c_str(),
7614 dev.uuid.raw(),
7615 mUserData->s.strName.c_str(),
7616 mData->m_strConfigFileFull.c_str(),
7617 medium->getChildren().size());
7618
7619 if (findAttachment(mMediaData->mAttachments,
7620 medium))
7621 return setError(E_FAIL,
7622 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7623 medium->getLocationFull().c_str(),
7624 dev.uuid.raw(),
7625 mUserData->s.strName.c_str(),
7626 mData->m_strConfigFileFull.c_str());
7627
7628 break;
7629 }
7630
7631 default:
7632 return setError(E_FAIL,
7633 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7634 medium->getLocationFull().c_str(),
7635 mUserData->s.strName.c_str(),
7636 mData->m_strConfigFileFull.c_str());
7637 }
7638
7639 if (FAILED(rc))
7640 break;
7641
7642 /* Bandwidth groups are loaded at this point. */
7643 ComObjPtr<BandwidthGroup> pBwGroup;
7644
7645 if (!dev.strBwGroup.isEmpty())
7646 {
7647 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
7648 if (FAILED(rc))
7649 return setError(E_FAIL,
7650 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
7651 medium->getLocationFull().c_str(),
7652 dev.strBwGroup.c_str(),
7653 mUserData->s.strName.c_str(),
7654 mData->m_strConfigFileFull.c_str());
7655 }
7656
7657 const Bstr controllerName = aStorageController->getName();
7658 ComObjPtr<MediumAttachment> pAttachment;
7659 pAttachment.createObject();
7660 rc = pAttachment->init(this,
7661 medium,
7662 controllerName,
7663 dev.lPort,
7664 dev.lDevice,
7665 dev.deviceType,
7666 dev.fPassThrough,
7667 pBwGroup);
7668 if (FAILED(rc)) break;
7669
7670 /* associate the medium with this machine and snapshot */
7671 if (!medium.isNull())
7672 {
7673 if (isSnapshotMachine())
7674 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7675 else
7676 rc = medium->addBackReference(mData->mUuid);
7677
7678 if (puuidRegistry)
7679 // caller wants registry ID to be set on all attached media (OVF import case)
7680 medium->addRegistry(*puuidRegistry);
7681 }
7682
7683 if (FAILED(rc))
7684 break;
7685
7686 /* back up mMediaData to let registeredInit() properly rollback on failure
7687 * (= limited accessibility) */
7688 setModified(IsModified_Storage);
7689 mMediaData.backup();
7690 mMediaData->mAttachments.push_back(pAttachment);
7691 }
7692
7693 return rc;
7694}
7695
7696/**
7697 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7698 *
7699 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7700 * @param aSnapshot where to return the found snapshot
7701 * @param aSetError true to set extended error info on failure
7702 */
7703HRESULT Machine::findSnapshotById(const Guid &aId,
7704 ComObjPtr<Snapshot> &aSnapshot,
7705 bool aSetError /* = false */)
7706{
7707 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7708
7709 if (!mData->mFirstSnapshot)
7710 {
7711 if (aSetError)
7712 return setError(E_FAIL, tr("This machine does not have any snapshots"));
7713 return E_FAIL;
7714 }
7715
7716 if (aId.isEmpty())
7717 aSnapshot = mData->mFirstSnapshot;
7718 else
7719 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
7720
7721 if (!aSnapshot)
7722 {
7723 if (aSetError)
7724 return setError(E_FAIL,
7725 tr("Could not find a snapshot with UUID {%s}"),
7726 aId.toString().c_str());
7727 return E_FAIL;
7728 }
7729
7730 return S_OK;
7731}
7732
7733/**
7734 * Returns the snapshot with the given name or fails of no such snapshot.
7735 *
7736 * @param aName snapshot name to find
7737 * @param aSnapshot where to return the found snapshot
7738 * @param aSetError true to set extended error info on failure
7739 */
7740HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
7741 ComObjPtr<Snapshot> &aSnapshot,
7742 bool aSetError /* = false */)
7743{
7744 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
7745
7746 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7747
7748 if (!mData->mFirstSnapshot)
7749 {
7750 if (aSetError)
7751 return setError(VBOX_E_OBJECT_NOT_FOUND,
7752 tr("This machine does not have any snapshots"));
7753 return VBOX_E_OBJECT_NOT_FOUND;
7754 }
7755
7756 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
7757
7758 if (!aSnapshot)
7759 {
7760 if (aSetError)
7761 return setError(VBOX_E_OBJECT_NOT_FOUND,
7762 tr("Could not find a snapshot named '%s'"), strName.c_str());
7763 return VBOX_E_OBJECT_NOT_FOUND;
7764 }
7765
7766 return S_OK;
7767}
7768
7769/**
7770 * Returns a storage controller object with the given name.
7771 *
7772 * @param aName storage controller name to find
7773 * @param aStorageController where to return the found storage controller
7774 * @param aSetError true to set extended error info on failure
7775 */
7776HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7777 ComObjPtr<StorageController> &aStorageController,
7778 bool aSetError /* = false */)
7779{
7780 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7781
7782 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7783 it != mStorageControllers->end();
7784 ++it)
7785 {
7786 if ((*it)->getName() == aName)
7787 {
7788 aStorageController = (*it);
7789 return S_OK;
7790 }
7791 }
7792
7793 if (aSetError)
7794 return setError(VBOX_E_OBJECT_NOT_FOUND,
7795 tr("Could not find a storage controller named '%s'"),
7796 aName.c_str());
7797 return VBOX_E_OBJECT_NOT_FOUND;
7798}
7799
7800HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7801 MediaData::AttachmentList &atts)
7802{
7803 AutoCaller autoCaller(this);
7804 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7805
7806 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7807
7808 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7809 it != mMediaData->mAttachments.end();
7810 ++it)
7811 {
7812 const ComObjPtr<MediumAttachment> &pAtt = *it;
7813
7814 // should never happen, but deal with NULL pointers in the list.
7815 AssertStmt(!pAtt.isNull(), continue);
7816
7817 // getControllerName() needs caller+read lock
7818 AutoCaller autoAttCaller(pAtt);
7819 if (FAILED(autoAttCaller.rc()))
7820 {
7821 atts.clear();
7822 return autoAttCaller.rc();
7823 }
7824 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7825
7826 if (pAtt->getControllerName() == aName)
7827 atts.push_back(pAtt);
7828 }
7829
7830 return S_OK;
7831}
7832
7833/**
7834 * Helper for #saveSettings. Cares about renaming the settings directory and
7835 * file if the machine name was changed and about creating a new settings file
7836 * if this is a new machine.
7837 *
7838 * @note Must be never called directly but only from #saveSettings().
7839 */
7840HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7841{
7842 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7843
7844 HRESULT rc = S_OK;
7845
7846 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7847
7848 /* attempt to rename the settings file if machine name is changed */
7849 if ( mUserData->s.fNameSync
7850 && mUserData.isBackedUp()
7851 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7852 )
7853 {
7854 bool dirRenamed = false;
7855 bool fileRenamed = false;
7856
7857 Utf8Str configFile, newConfigFile;
7858 Utf8Str configDir, newConfigDir;
7859
7860 do
7861 {
7862 int vrc = VINF_SUCCESS;
7863
7864 Utf8Str name = mUserData.backedUpData()->s.strName;
7865 Utf8Str newName = mUserData->s.strName;
7866
7867 configFile = mData->m_strConfigFileFull;
7868
7869 /* first, rename the directory if it matches the machine name */
7870 configDir = configFile;
7871 configDir.stripFilename();
7872 newConfigDir = configDir;
7873 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7874 {
7875 newConfigDir.stripFilename();
7876 newConfigDir.append(RTPATH_DELIMITER);
7877 newConfigDir.append(newName);
7878 /* new dir and old dir cannot be equal here because of 'if'
7879 * above and because name != newName */
7880 Assert(configDir != newConfigDir);
7881 if (!fSettingsFileIsNew)
7882 {
7883 /* perform real rename only if the machine is not new */
7884 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7885 if (RT_FAILURE(vrc))
7886 {
7887 rc = setError(E_FAIL,
7888 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7889 configDir.c_str(),
7890 newConfigDir.c_str(),
7891 vrc);
7892 break;
7893 }
7894 dirRenamed = true;
7895 }
7896 }
7897
7898 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
7899 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7900
7901 /* then try to rename the settings file itself */
7902 if (newConfigFile != configFile)
7903 {
7904 /* get the path to old settings file in renamed directory */
7905 configFile = Utf8StrFmt("%s%c%s",
7906 newConfigDir.c_str(),
7907 RTPATH_DELIMITER,
7908 RTPathFilename(configFile.c_str()));
7909 if (!fSettingsFileIsNew)
7910 {
7911 /* perform real rename only if the machine is not new */
7912 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7913 if (RT_FAILURE(vrc))
7914 {
7915 rc = setError(E_FAIL,
7916 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7917 configFile.c_str(),
7918 newConfigFile.c_str(),
7919 vrc);
7920 break;
7921 }
7922 fileRenamed = true;
7923 }
7924 }
7925
7926 // update m_strConfigFileFull amd mConfigFile
7927 mData->m_strConfigFileFull = newConfigFile;
7928 // compute the relative path too
7929 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7930
7931 // store the old and new so that VirtualBox::saveSettings() can update
7932 // the media registry
7933 if ( mData->mRegistered
7934 && configDir != newConfigDir)
7935 {
7936 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7937
7938 if (pfNeedsGlobalSaveSettings)
7939 *pfNeedsGlobalSaveSettings = true;
7940 }
7941
7942 /* update the saved state file path */
7943 Utf8Str path = mSSData->mStateFilePath;
7944 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7945 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
7946 newConfigDir.c_str(),
7947 path.c_str() + configDir.length());
7948
7949 /* Update saved state file paths of all online snapshots.
7950 * Note that saveSettings() will recognize name change
7951 * and will save all snapshots in this case. */
7952 if (mData->mFirstSnapshot)
7953 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7954 newConfigDir.c_str());
7955 }
7956 while (0);
7957
7958 if (FAILED(rc))
7959 {
7960 /* silently try to rename everything back */
7961 if (fileRenamed)
7962 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
7963 if (dirRenamed)
7964 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
7965 }
7966
7967 if (FAILED(rc)) return rc;
7968 }
7969
7970 if (fSettingsFileIsNew)
7971 {
7972 /* create a virgin config file */
7973 int vrc = VINF_SUCCESS;
7974
7975 /* ensure the settings directory exists */
7976 Utf8Str path(mData->m_strConfigFileFull);
7977 path.stripFilename();
7978 if (!RTDirExists(path.c_str()))
7979 {
7980 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7981 if (RT_FAILURE(vrc))
7982 {
7983 return setError(E_FAIL,
7984 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7985 path.c_str(),
7986 vrc);
7987 }
7988 }
7989
7990 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7991 path = Utf8Str(mData->m_strConfigFileFull);
7992 RTFILE f = NIL_RTFILE;
7993 vrc = RTFileOpen(&f, path.c_str(),
7994 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7995 if (RT_FAILURE(vrc))
7996 return setError(E_FAIL,
7997 tr("Could not create the settings file '%s' (%Rrc)"),
7998 path.c_str(),
7999 vrc);
8000 RTFileClose(f);
8001 }
8002
8003 return rc;
8004}
8005
8006/**
8007 * Saves and commits machine data, user data and hardware data.
8008 *
8009 * Note that on failure, the data remains uncommitted.
8010 *
8011 * @a aFlags may combine the following flags:
8012 *
8013 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8014 * Used when saving settings after an operation that makes them 100%
8015 * correspond to the settings from the current snapshot.
8016 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8017 * #isReallyModified() returns false. This is necessary for cases when we
8018 * change machine data directly, not through the backup()/commit() mechanism.
8019 * - SaveS_Force: settings will be saved without doing a deep compare of the
8020 * settings structures. This is used when this is called because snapshots
8021 * have changed to avoid the overhead of the deep compare.
8022 *
8023 * @note Must be called from under this object's write lock. Locks children for
8024 * writing.
8025 *
8026 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8027 * initialized to false and that will be set to true by this function if
8028 * the caller must invoke VirtualBox::saveSettings() because the global
8029 * settings have changed. This will happen if a machine rename has been
8030 * saved and the global machine and media registries will therefore need
8031 * updating.
8032 */
8033HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8034 int aFlags /*= 0*/)
8035{
8036 LogFlowThisFuncEnter();
8037
8038 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8039
8040 /* make sure child objects are unable to modify the settings while we are
8041 * saving them */
8042 ensureNoStateDependencies();
8043
8044 AssertReturn(!isSnapshotMachine(),
8045 E_FAIL);
8046
8047 HRESULT rc = S_OK;
8048 bool fNeedsWrite = false;
8049
8050 /* First, prepare to save settings. It will care about renaming the
8051 * settings directory and file if the machine name was changed and about
8052 * creating a new settings file if this is a new machine. */
8053 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8054 if (FAILED(rc)) return rc;
8055
8056 // keep a pointer to the current settings structures
8057 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8058 settings::MachineConfigFile *pNewConfig = NULL;
8059
8060 try
8061 {
8062 // make a fresh one to have everyone write stuff into
8063 pNewConfig = new settings::MachineConfigFile(NULL);
8064 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8065
8066 // now go and copy all the settings data from COM to the settings structures
8067 // (this calles saveSettings() on all the COM objects in the machine)
8068 copyMachineDataToSettings(*pNewConfig);
8069
8070 if (aFlags & SaveS_ResetCurStateModified)
8071 {
8072 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8073 mData->mCurrentStateModified = FALSE;
8074 fNeedsWrite = true; // always, no need to compare
8075 }
8076 else if (aFlags & SaveS_Force)
8077 {
8078 fNeedsWrite = true; // always, no need to compare
8079 }
8080 else
8081 {
8082 if (!mData->mCurrentStateModified)
8083 {
8084 // do a deep compare of the settings that we just saved with the settings
8085 // previously stored in the config file; this invokes MachineConfigFile::operator==
8086 // which does a deep compare of all the settings, which is expensive but less expensive
8087 // than writing out XML in vain
8088 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8089
8090 // could still be modified if any settings changed
8091 mData->mCurrentStateModified = fAnySettingsChanged;
8092
8093 fNeedsWrite = fAnySettingsChanged;
8094 }
8095 else
8096 fNeedsWrite = true;
8097 }
8098
8099 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8100
8101 if (fNeedsWrite)
8102 // now spit it all out!
8103 pNewConfig->write(mData->m_strConfigFileFull);
8104
8105 mData->pMachineConfigFile = pNewConfig;
8106 delete pOldConfig;
8107 commit();
8108
8109 // after saving settings, we are no longer different from the XML on disk
8110 mData->flModifications = 0;
8111 }
8112 catch (HRESULT err)
8113 {
8114 // we assume that error info is set by the thrower
8115 rc = err;
8116
8117 // restore old config
8118 delete pNewConfig;
8119 mData->pMachineConfigFile = pOldConfig;
8120 }
8121 catch (...)
8122 {
8123 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8124 }
8125
8126 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8127 {
8128 /* Fire the data change event, even on failure (since we've already
8129 * committed all data). This is done only for SessionMachines because
8130 * mutable Machine instances are always not registered (i.e. private
8131 * to the client process that creates them) and thus don't need to
8132 * inform callbacks. */
8133 if (isSessionMachine())
8134 mParent->onMachineDataChange(mData->mUuid);
8135 }
8136
8137 LogFlowThisFunc(("rc=%08X\n", rc));
8138 LogFlowThisFuncLeave();
8139 return rc;
8140}
8141
8142/**
8143 * Implementation for saving the machine settings into the given
8144 * settings::MachineConfigFile instance. This copies machine extradata
8145 * from the previous machine config file in the instance data, if any.
8146 *
8147 * This gets called from two locations:
8148 *
8149 * -- Machine::saveSettings(), during the regular XML writing;
8150 *
8151 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8152 * exported to OVF and we write the VirtualBox proprietary XML
8153 * into a <vbox:Machine> tag.
8154 *
8155 * This routine fills all the fields in there, including snapshots, *except*
8156 * for the following:
8157 *
8158 * -- fCurrentStateModified. There is some special logic associated with that.
8159 *
8160 * The caller can then call MachineConfigFile::write() or do something else
8161 * with it.
8162 *
8163 * Caller must hold the machine lock!
8164 *
8165 * This throws XML errors and HRESULT, so the caller must have a catch block!
8166 */
8167void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8168{
8169 // deep copy extradata
8170 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8171
8172 config.uuid = mData->mUuid;
8173
8174 // copy name, description, OS type, teleport, UTC etc.
8175 config.machineUserData = mUserData->s;
8176
8177 if ( mData->mMachineState == MachineState_Saved
8178 || mData->mMachineState == MachineState_Restoring
8179 // when deleting a snapshot we may or may not have a saved state in the current state,
8180 // so let's not assert here please
8181 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8182 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8183 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8184 && (!mSSData->mStateFilePath.isEmpty())
8185 )
8186 )
8187 {
8188 Assert(!mSSData->mStateFilePath.isEmpty());
8189 /* try to make the file name relative to the settings file dir */
8190 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
8191 }
8192 else
8193 {
8194 Assert(mSSData->mStateFilePath.isEmpty());
8195 config.strStateFile.setNull();
8196 }
8197
8198 if (mData->mCurrentSnapshot)
8199 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8200 else
8201 config.uuidCurrentSnapshot.clear();
8202
8203 config.timeLastStateChange = mData->mLastStateChange;
8204 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8205 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8206
8207 HRESULT rc = saveHardware(config.hardwareMachine);
8208 if (FAILED(rc)) throw rc;
8209
8210 rc = saveStorageControllers(config.storageMachine);
8211 if (FAILED(rc)) throw rc;
8212
8213 // save machine's media registry if this is VirtualBox 4.0 or later
8214 if (config.canHaveOwnMediaRegistry())
8215 {
8216 // determine machine folder
8217 Utf8Str strMachineFolder = getSettingsFileFull();
8218 strMachineFolder.stripFilename();
8219 mParent->saveMediaRegistry(config.mediaRegistry,
8220 getId(), // only media with registry ID == machine UUID
8221 strMachineFolder);
8222 // this throws HRESULT
8223 }
8224
8225 // save snapshots
8226 rc = saveAllSnapshots(config);
8227 if (FAILED(rc)) throw rc;
8228}
8229
8230/**
8231 * Saves all snapshots of the machine into the given machine config file. Called
8232 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8233 * @param config
8234 * @return
8235 */
8236HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8237{
8238 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8239
8240 HRESULT rc = S_OK;
8241
8242 try
8243 {
8244 config.llFirstSnapshot.clear();
8245
8246 if (mData->mFirstSnapshot)
8247 {
8248 settings::Snapshot snapNew;
8249 config.llFirstSnapshot.push_back(snapNew);
8250
8251 // get reference to the fresh copy of the snapshot on the list and
8252 // work on that copy directly to avoid excessive copying later
8253 settings::Snapshot &snap = config.llFirstSnapshot.front();
8254
8255 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8256 if (FAILED(rc)) throw rc;
8257 }
8258
8259// if (mType == IsSessionMachine)
8260// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8261
8262 }
8263 catch (HRESULT err)
8264 {
8265 /* we assume that error info is set by the thrower */
8266 rc = err;
8267 }
8268 catch (...)
8269 {
8270 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8271 }
8272
8273 return rc;
8274}
8275
8276/**
8277 * Saves the VM hardware configuration. It is assumed that the
8278 * given node is empty.
8279 *
8280 * @param aNode <Hardware> node to save the VM hardware configuration to.
8281 */
8282HRESULT Machine::saveHardware(settings::Hardware &data)
8283{
8284 HRESULT rc = S_OK;
8285
8286 try
8287 {
8288 /* The hardware version attribute (optional).
8289 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8290 if ( mHWData->mHWVersion == "1"
8291 && mSSData->mStateFilePath.isEmpty()
8292 )
8293 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. */
8294
8295 data.strVersion = mHWData->mHWVersion;
8296 data.uuid = mHWData->mHardwareUUID;
8297
8298 // CPU
8299 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8300 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8301 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8302 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8303 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8304 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8305 data.fPAE = !!mHWData->mPAEEnabled;
8306 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8307
8308 /* Standard and Extended CPUID leafs. */
8309 data.llCpuIdLeafs.clear();
8310 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8311 {
8312 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8313 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8314 }
8315 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8316 {
8317 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8318 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8319 }
8320
8321 data.cCPUs = mHWData->mCPUCount;
8322 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8323 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8324
8325 data.llCpus.clear();
8326 if (data.fCpuHotPlug)
8327 {
8328 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8329 {
8330 if (mHWData->mCPUAttached[idx])
8331 {
8332 settings::Cpu cpu;
8333 cpu.ulId = idx;
8334 data.llCpus.push_back(cpu);
8335 }
8336 }
8337 }
8338
8339 // memory
8340 data.ulMemorySizeMB = mHWData->mMemorySize;
8341 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8342
8343 // firmware
8344 data.firmwareType = mHWData->mFirmwareType;
8345
8346 // HID
8347 data.pointingHidType = mHWData->mPointingHidType;
8348 data.keyboardHidType = mHWData->mKeyboardHidType;
8349
8350 // chipset
8351 data.chipsetType = mHWData->mChipsetType;
8352
8353 // HPET
8354 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8355
8356 // boot order
8357 data.mapBootOrder.clear();
8358 for (size_t i = 0;
8359 i < RT_ELEMENTS(mHWData->mBootOrder);
8360 ++i)
8361 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8362
8363 // display
8364 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8365 data.cMonitors = mHWData->mMonitorCount;
8366 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8367 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8368
8369 /* VRDEServer settings (optional) */
8370 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8371 if (FAILED(rc)) throw rc;
8372
8373 /* BIOS (required) */
8374 rc = mBIOSSettings->saveSettings(data.biosSettings);
8375 if (FAILED(rc)) throw rc;
8376
8377 /* USB Controller (required) */
8378 rc = mUSBController->saveSettings(data.usbController);
8379 if (FAILED(rc)) throw rc;
8380
8381 /* Network adapters (required) */
8382 data.llNetworkAdapters.clear();
8383 for (ULONG slot = 0;
8384 slot < RT_ELEMENTS(mNetworkAdapters);
8385 ++slot)
8386 {
8387 settings::NetworkAdapter nic;
8388 nic.ulSlot = slot;
8389 rc = mNetworkAdapters[slot]->saveSettings(nic);
8390 if (FAILED(rc)) throw rc;
8391
8392 data.llNetworkAdapters.push_back(nic);
8393 }
8394
8395 /* Serial ports */
8396 data.llSerialPorts.clear();
8397 for (ULONG slot = 0;
8398 slot < RT_ELEMENTS(mSerialPorts);
8399 ++slot)
8400 {
8401 settings::SerialPort s;
8402 s.ulSlot = slot;
8403 rc = mSerialPorts[slot]->saveSettings(s);
8404 if (FAILED(rc)) return rc;
8405
8406 data.llSerialPorts.push_back(s);
8407 }
8408
8409 /* Parallel ports */
8410 data.llParallelPorts.clear();
8411 for (ULONG slot = 0;
8412 slot < RT_ELEMENTS(mParallelPorts);
8413 ++slot)
8414 {
8415 settings::ParallelPort p;
8416 p.ulSlot = slot;
8417 rc = mParallelPorts[slot]->saveSettings(p);
8418 if (FAILED(rc)) return rc;
8419
8420 data.llParallelPorts.push_back(p);
8421 }
8422
8423 /* Audio adapter */
8424 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8425 if (FAILED(rc)) return rc;
8426
8427 /* Shared folders */
8428 data.llSharedFolders.clear();
8429 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8430 it != mHWData->mSharedFolders.end();
8431 ++it)
8432 {
8433 ComObjPtr<SharedFolder> pFolder = *it;
8434 settings::SharedFolder sf;
8435 sf.strName = pFolder->getName();
8436 sf.strHostPath = pFolder->getHostPath();
8437 sf.fWritable = !!pFolder->isWritable();
8438 sf.fAutoMount = !!pFolder->isAutoMounted();
8439
8440 data.llSharedFolders.push_back(sf);
8441 }
8442
8443 // clipboard
8444 data.clipboardMode = mHWData->mClipboardMode;
8445
8446 /* Guest */
8447 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8448
8449 // IO settings
8450 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8451 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8452
8453 /* BandwidthControl (required) */
8454 rc = mBandwidthControl->saveSettings(data.ioSettings);
8455 if (FAILED(rc)) throw rc;
8456
8457 // guest properties
8458 data.llGuestProperties.clear();
8459#ifdef VBOX_WITH_GUEST_PROPS
8460 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8461 it != mHWData->mGuestProperties.end();
8462 ++it)
8463 {
8464 HWData::GuestProperty property = *it;
8465
8466 /* Remove transient guest properties at shutdown unless we
8467 * are saving state */
8468 if ( ( mData->mMachineState == MachineState_PoweredOff
8469 || mData->mMachineState == MachineState_Aborted
8470 || mData->mMachineState == MachineState_Teleported)
8471 && property.mFlags & guestProp::TRANSIENT)
8472 continue;
8473 settings::GuestProperty prop;
8474 prop.strName = property.strName;
8475 prop.strValue = property.strValue;
8476 prop.timestamp = property.mTimestamp;
8477 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8478 guestProp::writeFlags(property.mFlags, szFlags);
8479 prop.strFlags = szFlags;
8480
8481 data.llGuestProperties.push_back(prop);
8482 }
8483
8484 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8485 /* I presume this doesn't require a backup(). */
8486 mData->mGuestPropertiesModified = FALSE;
8487#endif /* VBOX_WITH_GUEST_PROPS defined */
8488 }
8489 catch(std::bad_alloc &)
8490 {
8491 return E_OUTOFMEMORY;
8492 }
8493
8494 AssertComRC(rc);
8495 return rc;
8496}
8497
8498/**
8499 * Saves the storage controller configuration.
8500 *
8501 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8502 */
8503HRESULT Machine::saveStorageControllers(settings::Storage &data)
8504{
8505 data.llStorageControllers.clear();
8506
8507 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8508 it != mStorageControllers->end();
8509 ++it)
8510 {
8511 HRESULT rc;
8512 ComObjPtr<StorageController> pCtl = *it;
8513
8514 settings::StorageController ctl;
8515 ctl.strName = pCtl->getName();
8516 ctl.controllerType = pCtl->getControllerType();
8517 ctl.storageBus = pCtl->getStorageBus();
8518 ctl.ulInstance = pCtl->getInstance();
8519 ctl.fBootable = pCtl->getBootable();
8520
8521 /* Save the port count. */
8522 ULONG portCount;
8523 rc = pCtl->COMGETTER(PortCount)(&portCount);
8524 ComAssertComRCRet(rc, rc);
8525 ctl.ulPortCount = portCount;
8526
8527 /* Save fUseHostIOCache */
8528 BOOL fUseHostIOCache;
8529 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8530 ComAssertComRCRet(rc, rc);
8531 ctl.fUseHostIOCache = !!fUseHostIOCache;
8532
8533 /* Save IDE emulation settings. */
8534 if (ctl.controllerType == StorageControllerType_IntelAhci)
8535 {
8536 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8537 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8538 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8539 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8540 )
8541 ComAssertComRCRet(rc, rc);
8542 }
8543
8544 /* save the devices now. */
8545 rc = saveStorageDevices(pCtl, ctl);
8546 ComAssertComRCRet(rc, rc);
8547
8548 data.llStorageControllers.push_back(ctl);
8549 }
8550
8551 return S_OK;
8552}
8553
8554/**
8555 * Saves the hard disk configuration.
8556 */
8557HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8558 settings::StorageController &data)
8559{
8560 MediaData::AttachmentList atts;
8561
8562 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8563 if (FAILED(rc)) return rc;
8564
8565 data.llAttachedDevices.clear();
8566 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8567 it != atts.end();
8568 ++it)
8569 {
8570 settings::AttachedDevice dev;
8571
8572 MediumAttachment *pAttach = *it;
8573 Medium *pMedium = pAttach->getMedium();
8574 BandwidthGroup *pBwGroup = pAttach->getBandwidthGroup();
8575
8576 dev.deviceType = pAttach->getType();
8577 dev.lPort = pAttach->getPort();
8578 dev.lDevice = pAttach->getDevice();
8579 if (pMedium)
8580 {
8581 if (pMedium->isHostDrive())
8582 dev.strHostDriveSrc = pMedium->getLocationFull();
8583 else
8584 dev.uuid = pMedium->getId();
8585 dev.fPassThrough = pAttach->getPassthrough();
8586 }
8587
8588 if (pBwGroup)
8589 {
8590 dev.strBwGroup = pBwGroup->getName();
8591 }
8592
8593 data.llAttachedDevices.push_back(dev);
8594 }
8595
8596 return S_OK;
8597}
8598
8599/**
8600 * Saves machine state settings as defined by aFlags
8601 * (SaveSTS_* values).
8602 *
8603 * @param aFlags Combination of SaveSTS_* flags.
8604 *
8605 * @note Locks objects for writing.
8606 */
8607HRESULT Machine::saveStateSettings(int aFlags)
8608{
8609 if (aFlags == 0)
8610 return S_OK;
8611
8612 AutoCaller autoCaller(this);
8613 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8614
8615 /* This object's write lock is also necessary to serialize file access
8616 * (prevent concurrent reads and writes) */
8617 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8618
8619 HRESULT rc = S_OK;
8620
8621 Assert(mData->pMachineConfigFile);
8622
8623 try
8624 {
8625 if (aFlags & SaveSTS_CurStateModified)
8626 mData->pMachineConfigFile->fCurrentStateModified = true;
8627
8628 if (aFlags & SaveSTS_StateFilePath)
8629 {
8630 if (!mSSData->mStateFilePath.isEmpty())
8631 /* try to make the file name relative to the settings file dir */
8632 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8633 else
8634 mData->pMachineConfigFile->strStateFile.setNull();
8635 }
8636
8637 if (aFlags & SaveSTS_StateTimeStamp)
8638 {
8639 Assert( mData->mMachineState != MachineState_Aborted
8640 || mSSData->mStateFilePath.isEmpty());
8641
8642 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8643
8644 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8645//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8646 }
8647
8648 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8649 }
8650 catch (...)
8651 {
8652 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8653 }
8654
8655 return rc;
8656}
8657
8658/**
8659 * Creates differencing hard disks for all normal hard disks attached to this
8660 * machine and a new set of attachments to refer to created disks.
8661 *
8662 * Used when taking a snapshot or when deleting the current state. Gets called
8663 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8664 *
8665 * This method assumes that mMediaData contains the original hard disk attachments
8666 * it needs to create diffs for. On success, these attachments will be replaced
8667 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8668 * called to delete created diffs which will also rollback mMediaData and restore
8669 * whatever was backed up before calling this method.
8670 *
8671 * Attachments with non-normal hard disks are left as is.
8672 *
8673 * If @a aOnline is @c false then the original hard disks that require implicit
8674 * diffs will be locked for reading. Otherwise it is assumed that they are
8675 * already locked for writing (when the VM was started). Note that in the latter
8676 * case it is responsibility of the caller to lock the newly created diffs for
8677 * writing if this method succeeds.
8678 *
8679 * @param aProgress Progress object to run (must contain at least as
8680 * many operations left as the number of hard disks
8681 * attached).
8682 * @param aOnline Whether the VM was online prior to this operation.
8683 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
8684 *
8685 * @note The progress object is not marked as completed, neither on success nor
8686 * on failure. This is a responsibility of the caller.
8687 *
8688 * @note Locks this object for writing.
8689 */
8690HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8691 ULONG aWeight,
8692 bool aOnline,
8693 GuidList *pllRegistriesThatNeedSaving)
8694{
8695 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8696
8697 AutoCaller autoCaller(this);
8698 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8699
8700 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8701
8702 /* must be in a protective state because we leave the lock below */
8703 AssertReturn( mData->mMachineState == MachineState_Saving
8704 || mData->mMachineState == MachineState_LiveSnapshotting
8705 || mData->mMachineState == MachineState_RestoringSnapshot
8706 || mData->mMachineState == MachineState_DeletingSnapshot
8707 , E_FAIL);
8708
8709 HRESULT rc = S_OK;
8710
8711 MediumLockListMap lockedMediaOffline;
8712 MediumLockListMap *lockedMediaMap;
8713 if (aOnline)
8714 lockedMediaMap = &mData->mSession.mLockedMedia;
8715 else
8716 lockedMediaMap = &lockedMediaOffline;
8717
8718 try
8719 {
8720 if (!aOnline)
8721 {
8722 /* lock all attached hard disks early to detect "in use"
8723 * situations before creating actual diffs */
8724 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8725 it != mMediaData->mAttachments.end();
8726 ++it)
8727 {
8728 MediumAttachment* pAtt = *it;
8729 if (pAtt->getType() == DeviceType_HardDisk)
8730 {
8731 Medium* pMedium = pAtt->getMedium();
8732 Assert(pMedium);
8733
8734 MediumLockList *pMediumLockList(new MediumLockList());
8735 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8736 false /* fMediumLockWrite */,
8737 NULL,
8738 *pMediumLockList);
8739 if (FAILED(rc))
8740 {
8741 delete pMediumLockList;
8742 throw rc;
8743 }
8744 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8745 if (FAILED(rc))
8746 {
8747 throw setError(rc,
8748 tr("Collecting locking information for all attached media failed"));
8749 }
8750 }
8751 }
8752
8753 /* Now lock all media. If this fails, nothing is locked. */
8754 rc = lockedMediaMap->Lock();
8755 if (FAILED(rc))
8756 {
8757 throw setError(rc,
8758 tr("Locking of attached media failed"));
8759 }
8760 }
8761
8762 /* remember the current list (note that we don't use backup() since
8763 * mMediaData may be already backed up) */
8764 MediaData::AttachmentList atts = mMediaData->mAttachments;
8765
8766 /* start from scratch */
8767 mMediaData->mAttachments.clear();
8768
8769 /* go through remembered attachments and create diffs for normal hard
8770 * disks and attach them */
8771 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8772 it != atts.end();
8773 ++it)
8774 {
8775 MediumAttachment* pAtt = *it;
8776
8777 DeviceType_T devType = pAtt->getType();
8778 Medium* pMedium = pAtt->getMedium();
8779
8780 if ( devType != DeviceType_HardDisk
8781 || pMedium == NULL
8782 || pMedium->getType() != MediumType_Normal)
8783 {
8784 /* copy the attachment as is */
8785
8786 /** @todo the progress object created in Console::TakeSnaphot
8787 * only expects operations for hard disks. Later other
8788 * device types need to show up in the progress as well. */
8789 if (devType == DeviceType_HardDisk)
8790 {
8791 if (pMedium == NULL)
8792 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
8793 aWeight); // weight
8794 else
8795 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8796 pMedium->getBase()->getName().c_str()).raw(),
8797 aWeight); // weight
8798 }
8799
8800 mMediaData->mAttachments.push_back(pAtt);
8801 continue;
8802 }
8803
8804 /* need a diff */
8805 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8806 pMedium->getBase()->getName().c_str()).raw(),
8807 aWeight); // weight
8808
8809 Utf8Str strFullSnapshotFolder;
8810 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
8811
8812 ComObjPtr<Medium> diff;
8813 diff.createObject();
8814 rc = diff->init(mParent,
8815 pMedium->getPreferredDiffFormat(),
8816 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
8817 pMedium->getFirstRegistryMachineId(), // store the diff in the same registry as the parent
8818 pllRegistriesThatNeedSaving);
8819 if (FAILED(rc)) throw rc;
8820
8821 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8822 * the push_back? Looks like we're going to leave medium with the
8823 * wrong kind of lock (general issue with if we fail anywhere at all)
8824 * and an orphaned VDI in the snapshots folder. */
8825
8826 /* update the appropriate lock list */
8827 MediumLockList *pMediumLockList;
8828 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8829 AssertComRCThrowRC(rc);
8830 if (aOnline)
8831 {
8832 rc = pMediumLockList->Update(pMedium, false);
8833 AssertComRCThrowRC(rc);
8834 }
8835
8836 /* leave the lock before the potentially lengthy operation */
8837 alock.leave();
8838 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8839 pMediumLockList,
8840 NULL /* aProgress */,
8841 true /* aWait */,
8842 pllRegistriesThatNeedSaving);
8843 alock.enter();
8844 if (FAILED(rc)) throw rc;
8845
8846 rc = lockedMediaMap->Unlock();
8847 AssertComRCThrowRC(rc);
8848 rc = pMediumLockList->Append(diff, true);
8849 AssertComRCThrowRC(rc);
8850 rc = lockedMediaMap->Lock();
8851 AssertComRCThrowRC(rc);
8852
8853 rc = diff->addBackReference(mData->mUuid);
8854 AssertComRCThrowRC(rc);
8855
8856 /* add a new attachment */
8857 ComObjPtr<MediumAttachment> attachment;
8858 attachment.createObject();
8859 rc = attachment->init(this,
8860 diff,
8861 pAtt->getControllerName(),
8862 pAtt->getPort(),
8863 pAtt->getDevice(),
8864 DeviceType_HardDisk,
8865 true /* aImplicit */,
8866 pAtt->getBandwidthGroup());
8867 if (FAILED(rc)) throw rc;
8868
8869 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8870 AssertComRCThrowRC(rc);
8871 mMediaData->mAttachments.push_back(attachment);
8872 }
8873 }
8874 catch (HRESULT aRC) { rc = aRC; }
8875
8876 /* unlock all hard disks we locked */
8877 if (!aOnline)
8878 {
8879 ErrorInfoKeeper eik;
8880
8881 rc = lockedMediaMap->Clear();
8882 AssertComRC(rc);
8883 }
8884
8885 if (FAILED(rc))
8886 {
8887 MultiResult mrc = rc;
8888
8889 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
8890 }
8891
8892 return rc;
8893}
8894
8895/**
8896 * Deletes implicit differencing hard disks created either by
8897 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8898 *
8899 * Note that to delete hard disks created by #AttachMedium() this method is
8900 * called from #fixupMedia() when the changes are rolled back.
8901 *
8902 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8903 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8904 *
8905 * @note Locks this object for writing.
8906 */
8907HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
8908{
8909 AutoCaller autoCaller(this);
8910 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8911
8912 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8913 LogFlowThisFuncEnter();
8914
8915 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8916
8917 HRESULT rc = S_OK;
8918
8919 MediaData::AttachmentList implicitAtts;
8920
8921 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8922
8923 /* enumerate new attachments */
8924 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8925 it != mMediaData->mAttachments.end();
8926 ++it)
8927 {
8928 ComObjPtr<Medium> hd = (*it)->getMedium();
8929 if (hd.isNull())
8930 continue;
8931
8932 if ((*it)->isImplicit())
8933 {
8934 /* deassociate and mark for deletion */
8935 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8936 rc = hd->removeBackReference(mData->mUuid);
8937 AssertComRC(rc);
8938 implicitAtts.push_back(*it);
8939 continue;
8940 }
8941
8942 /* was this hard disk attached before? */
8943 if (!findAttachment(oldAtts, hd))
8944 {
8945 /* no: de-associate */
8946 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8947 rc = hd->removeBackReference(mData->mUuid);
8948 AssertComRC(rc);
8949 continue;
8950 }
8951 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8952 }
8953
8954 /* rollback hard disk changes */
8955 mMediaData.rollback();
8956
8957 MultiResult mrc(S_OK);
8958
8959 /* delete unused implicit diffs */
8960 if (implicitAtts.size() != 0)
8961 {
8962 /* will leave the lock before the potentially lengthy
8963 * operation, so protect with the special state (unless already
8964 * protected) */
8965 MachineState_T oldState = mData->mMachineState;
8966 if ( oldState != MachineState_Saving
8967 && oldState != MachineState_LiveSnapshotting
8968 && oldState != MachineState_RestoringSnapshot
8969 && oldState != MachineState_DeletingSnapshot
8970 && oldState != MachineState_DeletingSnapshotOnline
8971 && oldState != MachineState_DeletingSnapshotPaused
8972 )
8973 setMachineState(MachineState_SettingUp);
8974
8975 alock.leave();
8976
8977 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8978 it != implicitAtts.end();
8979 ++it)
8980 {
8981 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8982 ComObjPtr<Medium> hd = (*it)->getMedium();
8983
8984 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8985 pllRegistriesThatNeedSaving);
8986 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8987 mrc = rc;
8988 }
8989
8990 alock.enter();
8991
8992 if (mData->mMachineState == MachineState_SettingUp)
8993 setMachineState(oldState);
8994 }
8995
8996 return mrc;
8997}
8998
8999/**
9000 * Looks through the given list of media attachments for one with the given parameters
9001 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9002 * can be searched as well if needed.
9003 *
9004 * @param list
9005 * @param aControllerName
9006 * @param aControllerPort
9007 * @param aDevice
9008 * @return
9009 */
9010MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9011 IN_BSTR aControllerName,
9012 LONG aControllerPort,
9013 LONG aDevice)
9014{
9015 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9016 it != ll.end();
9017 ++it)
9018 {
9019 MediumAttachment *pAttach = *it;
9020 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9021 return pAttach;
9022 }
9023
9024 return NULL;
9025}
9026
9027/**
9028 * Looks through the given list of media attachments for one with the given parameters
9029 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9030 * can be searched as well if needed.
9031 *
9032 * @param list
9033 * @param aControllerName
9034 * @param aControllerPort
9035 * @param aDevice
9036 * @return
9037 */
9038MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9039 ComObjPtr<Medium> pMedium)
9040{
9041 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9042 it != ll.end();
9043 ++it)
9044 {
9045 MediumAttachment *pAttach = *it;
9046 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9047 if (pMediumThis == pMedium)
9048 return pAttach;
9049 }
9050
9051 return NULL;
9052}
9053
9054/**
9055 * Looks through the given list of media attachments for one with the given parameters
9056 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9057 * can be searched as well if needed.
9058 *
9059 * @param list
9060 * @param aControllerName
9061 * @param aControllerPort
9062 * @param aDevice
9063 * @return
9064 */
9065MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9066 Guid &id)
9067{
9068 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9069 it != ll.end();
9070 ++it)
9071 {
9072 MediumAttachment *pAttach = *it;
9073 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9074 if (pMediumThis->getId() == id)
9075 return pAttach;
9076 }
9077
9078 return NULL;
9079}
9080
9081/**
9082 * Main implementation for Machine::DetachDevice. This also gets called
9083 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9084 *
9085 * @param pAttach Medium attachment to detach.
9086 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9087 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9088 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9089 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9090 * @return
9091 */
9092HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9093 AutoWriteLock &writeLock,
9094 Snapshot *pSnapshot,
9095 GuidList *pllRegistriesThatNeedSaving)
9096{
9097 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9098 DeviceType_T mediumType = pAttach->getType();
9099
9100 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9101
9102 if (pAttach->isImplicit())
9103 {
9104 /* attempt to implicitly delete the implicitly created diff */
9105
9106 /// @todo move the implicit flag from MediumAttachment to Medium
9107 /// and forbid any hard disk operation when it is implicit. Or maybe
9108 /// a special media state for it to make it even more simple.
9109
9110 Assert(mMediaData.isBackedUp());
9111
9112 /* will leave the lock before the potentially lengthy operation, so
9113 * protect with the special state */
9114 MachineState_T oldState = mData->mMachineState;
9115 setMachineState(MachineState_SettingUp);
9116
9117 writeLock.release();
9118
9119 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9120 pllRegistriesThatNeedSaving);
9121
9122 writeLock.acquire();
9123
9124 setMachineState(oldState);
9125
9126 if (FAILED(rc)) return rc;
9127 }
9128
9129 setModified(IsModified_Storage);
9130 mMediaData.backup();
9131
9132 // we cannot use erase (it) below because backup() above will create
9133 // a copy of the list and make this copy active, but the iterator
9134 // still refers to the original and is not valid for the copy
9135 mMediaData->mAttachments.remove(pAttach);
9136
9137 if (!oldmedium.isNull())
9138 {
9139 // if this is from a snapshot, do not defer detachment to commitMedia()
9140 if (pSnapshot)
9141 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9142 // else if non-hard disk media, do not defer detachment to commitMedia() either
9143 else if (mediumType != DeviceType_HardDisk)
9144 oldmedium->removeBackReference(mData->mUuid);
9145 }
9146
9147 return S_OK;
9148}
9149
9150/**
9151 * Goes thru all medium attachments of the list and calls detachDevice() on each
9152 * of them and attaches all Medium objects found in the process to the given list,
9153 * depending on cleanupMode.
9154 *
9155 * This gets called from Machine::Unregister, both for the actual Machine and
9156 * the SnapshotMachine objects that might be found in the snapshots.
9157 *
9158 * Requires caller and locking.
9159 *
9160 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9161 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9162 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9163 * otherwise no media get added.
9164 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9165 * @return
9166 */
9167HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9168 Snapshot *pSnapshot,
9169 CleanupMode_T cleanupMode,
9170 MediaList &llMedia)
9171{
9172 Assert(isWriteLockOnCurrentThread());
9173
9174 HRESULT rc;
9175
9176 // make a temporary list because detachDevice invalidates iterators into
9177 // mMediaData->mAttachments
9178 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9179
9180 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9181 it != llAttachments2.end();
9182 ++it)
9183 {
9184 ComObjPtr<MediumAttachment> pAttach = *it;
9185 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9186
9187 if (!pMedium.isNull())
9188 {
9189 DeviceType_T devType = pMedium->getDeviceType();
9190 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9191 && devType == DeviceType_HardDisk)
9192 || (cleanupMode == CleanupMode_Full)
9193 )
9194 llMedia.push_back(pMedium);
9195 }
9196
9197 // real machine: then we need to use the proper method
9198 rc = detachDevice(pAttach,
9199 writeLock,
9200 pSnapshot,
9201 NULL /* pfNeedsSaveSettings */);
9202
9203 if (FAILED(rc))
9204 return rc;
9205 }
9206
9207 return S_OK;
9208}
9209
9210/**
9211 * Perform deferred hard disk detachments.
9212 *
9213 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9214 * backed up).
9215 *
9216 * If @a aOnline is @c true then this method will also unlock the old hard disks
9217 * for which the new implicit diffs were created and will lock these new diffs for
9218 * writing.
9219 *
9220 * @param aOnline Whether the VM was online prior to this operation.
9221 *
9222 * @note Locks this object for writing!
9223 */
9224void Machine::commitMedia(bool aOnline /*= false*/)
9225{
9226 AutoCaller autoCaller(this);
9227 AssertComRCReturnVoid(autoCaller.rc());
9228
9229 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9230
9231 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9232
9233 HRESULT rc = S_OK;
9234
9235 /* no attach/detach operations -- nothing to do */
9236 if (!mMediaData.isBackedUp())
9237 return;
9238
9239 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9240 bool fMediaNeedsLocking = false;
9241
9242 /* enumerate new attachments */
9243 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9244 it != mMediaData->mAttachments.end();
9245 ++it)
9246 {
9247 MediumAttachment *pAttach = *it;
9248
9249 pAttach->commit();
9250
9251 Medium* pMedium = pAttach->getMedium();
9252 bool fImplicit = pAttach->isImplicit();
9253
9254 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9255 (pMedium) ? pMedium->getName().c_str() : "NULL",
9256 fImplicit));
9257
9258 /** @todo convert all this Machine-based voodoo to MediumAttachment
9259 * based commit logic. */
9260 if (fImplicit)
9261 {
9262 /* convert implicit attachment to normal */
9263 pAttach->setImplicit(false);
9264
9265 if ( aOnline
9266 && pMedium
9267 && pAttach->getType() == DeviceType_HardDisk
9268 )
9269 {
9270 ComObjPtr<Medium> parent = pMedium->getParent();
9271 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9272
9273 /* update the appropriate lock list */
9274 MediumLockList *pMediumLockList;
9275 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9276 AssertComRC(rc);
9277 if (pMediumLockList)
9278 {
9279 /* unlock if there's a need to change the locking */
9280 if (!fMediaNeedsLocking)
9281 {
9282 rc = mData->mSession.mLockedMedia.Unlock();
9283 AssertComRC(rc);
9284 fMediaNeedsLocking = true;
9285 }
9286 rc = pMediumLockList->Update(parent, false);
9287 AssertComRC(rc);
9288 rc = pMediumLockList->Append(pMedium, true);
9289 AssertComRC(rc);
9290 }
9291 }
9292
9293 continue;
9294 }
9295
9296 if (pMedium)
9297 {
9298 /* was this medium attached before? */
9299 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9300 oldIt != oldAtts.end();
9301 ++oldIt)
9302 {
9303 MediumAttachment *pOldAttach = *oldIt;
9304 if (pOldAttach->getMedium() == pMedium)
9305 {
9306 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9307
9308 /* yes: remove from old to avoid de-association */
9309 oldAtts.erase(oldIt);
9310 break;
9311 }
9312 }
9313 }
9314 }
9315
9316 /* enumerate remaining old attachments and de-associate from the
9317 * current machine state */
9318 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9319 it != oldAtts.end();
9320 ++it)
9321 {
9322 MediumAttachment *pAttach = *it;
9323 Medium* pMedium = pAttach->getMedium();
9324
9325 /* Detach only hard disks, since DVD/floppy media is detached
9326 * instantly in MountMedium. */
9327 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9328 {
9329 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9330
9331 /* now de-associate from the current machine state */
9332 rc = pMedium->removeBackReference(mData->mUuid);
9333 AssertComRC(rc);
9334
9335 if (aOnline)
9336 {
9337 /* unlock since medium is not used anymore */
9338 MediumLockList *pMediumLockList;
9339 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9340 AssertComRC(rc);
9341 if (pMediumLockList)
9342 {
9343 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9344 AssertComRC(rc);
9345 }
9346 }
9347 }
9348 }
9349
9350 /* take media locks again so that the locking state is consistent */
9351 if (fMediaNeedsLocking)
9352 {
9353 Assert(aOnline);
9354 rc = mData->mSession.mLockedMedia.Lock();
9355 AssertComRC(rc);
9356 }
9357
9358 /* commit the hard disk changes */
9359 mMediaData.commit();
9360
9361 if (isSessionMachine())
9362 {
9363 /* attach new data to the primary machine and reshare it */
9364 mPeer->mMediaData.attach(mMediaData);
9365 }
9366
9367 return;
9368}
9369
9370/**
9371 * Perform deferred deletion of implicitly created diffs.
9372 *
9373 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9374 * backed up).
9375 *
9376 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9377 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9378 *
9379 * @note Locks this object for writing!
9380 */
9381void Machine::rollbackMedia()
9382{
9383 AutoCaller autoCaller(this);
9384 AssertComRCReturnVoid (autoCaller.rc());
9385
9386 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9387
9388 LogFlowThisFunc(("Entering\n"));
9389
9390 HRESULT rc = S_OK;
9391
9392 /* no attach/detach operations -- nothing to do */
9393 if (!mMediaData.isBackedUp())
9394 return;
9395
9396 /* enumerate new attachments */
9397 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9398 it != mMediaData->mAttachments.end();
9399 ++it)
9400 {
9401 MediumAttachment *pAttach = *it;
9402 /* Fix up the backrefs for DVD/floppy media. */
9403 if (pAttach->getType() != DeviceType_HardDisk)
9404 {
9405 Medium* pMedium = pAttach->getMedium();
9406 if (pMedium)
9407 {
9408 rc = pMedium->removeBackReference(mData->mUuid);
9409 AssertComRC(rc);
9410 }
9411 }
9412
9413 (*it)->rollback();
9414
9415 pAttach = *it;
9416 /* Fix up the backrefs for DVD/floppy media. */
9417 if (pAttach->getType() != DeviceType_HardDisk)
9418 {
9419 Medium* pMedium = pAttach->getMedium();
9420 if (pMedium)
9421 {
9422 rc = pMedium->addBackReference(mData->mUuid);
9423 AssertComRC(rc);
9424 }
9425 }
9426 }
9427
9428 /** @todo convert all this Machine-based voodoo to MediumAttachment
9429 * based rollback logic. */
9430 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9431 // which gets called if Machine::registeredInit() fails...
9432 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9433
9434 return;
9435}
9436
9437/**
9438 * Returns true if the settings file is located in the directory named exactly
9439 * as the machine; this means, among other things, that the machine directory
9440 * should be auto-renamed.
9441 *
9442 * @param aSettingsDir if not NULL, the full machine settings file directory
9443 * name will be assigned there.
9444 *
9445 * @note Doesn't lock anything.
9446 * @note Not thread safe (must be called from this object's lock).
9447 */
9448bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9449{
9450 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9451 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9452 if (aSettingsDir)
9453 *aSettingsDir = strMachineDirName;
9454 strMachineDirName.stripPath(); // vmname
9455 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9456 strConfigFileOnly.stripPath() // vmname.vbox
9457 .stripExt(); // vmname
9458
9459 AssertReturn(!strMachineDirName.isEmpty(), false);
9460 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9461
9462 return strMachineDirName == strConfigFileOnly;
9463}
9464
9465/**
9466 * Discards all changes to machine settings.
9467 *
9468 * @param aNotify Whether to notify the direct session about changes or not.
9469 *
9470 * @note Locks objects for writing!
9471 */
9472void Machine::rollback(bool aNotify)
9473{
9474 AutoCaller autoCaller(this);
9475 AssertComRCReturn(autoCaller.rc(), (void)0);
9476
9477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9478
9479 if (!mStorageControllers.isNull())
9480 {
9481 if (mStorageControllers.isBackedUp())
9482 {
9483 /* unitialize all new devices (absent in the backed up list). */
9484 StorageControllerList::const_iterator it = mStorageControllers->begin();
9485 StorageControllerList *backedList = mStorageControllers.backedUpData();
9486 while (it != mStorageControllers->end())
9487 {
9488 if ( std::find(backedList->begin(), backedList->end(), *it)
9489 == backedList->end()
9490 )
9491 {
9492 (*it)->uninit();
9493 }
9494 ++it;
9495 }
9496
9497 /* restore the list */
9498 mStorageControllers.rollback();
9499 }
9500
9501 /* rollback any changes to devices after restoring the list */
9502 if (mData->flModifications & IsModified_Storage)
9503 {
9504 StorageControllerList::const_iterator it = mStorageControllers->begin();
9505 while (it != mStorageControllers->end())
9506 {
9507 (*it)->rollback();
9508 ++it;
9509 }
9510 }
9511 }
9512
9513 mUserData.rollback();
9514
9515 mHWData.rollback();
9516
9517 if (mData->flModifications & IsModified_Storage)
9518 rollbackMedia();
9519
9520 if (mBIOSSettings)
9521 mBIOSSettings->rollback();
9522
9523 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9524 mVRDEServer->rollback();
9525
9526 if (mAudioAdapter)
9527 mAudioAdapter->rollback();
9528
9529 if (mUSBController && (mData->flModifications & IsModified_USB))
9530 mUSBController->rollback();
9531
9532 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
9533 mBandwidthControl->rollback();
9534
9535 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9536 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9537 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9538
9539 if (mData->flModifications & IsModified_NetworkAdapters)
9540 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9541 if ( mNetworkAdapters[slot]
9542 && mNetworkAdapters[slot]->isModified())
9543 {
9544 mNetworkAdapters[slot]->rollback();
9545 networkAdapters[slot] = mNetworkAdapters[slot];
9546 }
9547
9548 if (mData->flModifications & IsModified_SerialPorts)
9549 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9550 if ( mSerialPorts[slot]
9551 && mSerialPorts[slot]->isModified())
9552 {
9553 mSerialPorts[slot]->rollback();
9554 serialPorts[slot] = mSerialPorts[slot];
9555 }
9556
9557 if (mData->flModifications & IsModified_ParallelPorts)
9558 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9559 if ( mParallelPorts[slot]
9560 && mParallelPorts[slot]->isModified())
9561 {
9562 mParallelPorts[slot]->rollback();
9563 parallelPorts[slot] = mParallelPorts[slot];
9564 }
9565
9566 if (aNotify)
9567 {
9568 /* inform the direct session about changes */
9569
9570 ComObjPtr<Machine> that = this;
9571 uint32_t flModifications = mData->flModifications;
9572 alock.leave();
9573
9574 if (flModifications & IsModified_SharedFolders)
9575 that->onSharedFolderChange();
9576
9577 if (flModifications & IsModified_VRDEServer)
9578 that->onVRDEServerChange(/* aRestart */ TRUE);
9579 if (flModifications & IsModified_USB)
9580 that->onUSBControllerChange();
9581
9582 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9583 if (networkAdapters[slot])
9584 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9585 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9586 if (serialPorts[slot])
9587 that->onSerialPortChange(serialPorts[slot]);
9588 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9589 if (parallelPorts[slot])
9590 that->onParallelPortChange(parallelPorts[slot]);
9591
9592 if (flModifications & IsModified_Storage)
9593 that->onStorageControllerChange();
9594
9595#if 0
9596 if (flModifications & IsModified_BandwidthControl)
9597 that->onBandwidthControlChange();
9598#endif
9599 }
9600}
9601
9602/**
9603 * Commits all the changes to machine settings.
9604 *
9605 * Note that this operation is supposed to never fail.
9606 *
9607 * @note Locks this object and children for writing.
9608 */
9609void Machine::commit()
9610{
9611 AutoCaller autoCaller(this);
9612 AssertComRCReturnVoid(autoCaller.rc());
9613
9614 AutoCaller peerCaller(mPeer);
9615 AssertComRCReturnVoid(peerCaller.rc());
9616
9617 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9618
9619 /*
9620 * use safe commit to ensure Snapshot machines (that share mUserData)
9621 * will still refer to a valid memory location
9622 */
9623 mUserData.commitCopy();
9624
9625 mHWData.commit();
9626
9627 if (mMediaData.isBackedUp())
9628 commitMedia();
9629
9630 mBIOSSettings->commit();
9631 mVRDEServer->commit();
9632 mAudioAdapter->commit();
9633 mUSBController->commit();
9634 mBandwidthControl->commit();
9635
9636 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9637 mNetworkAdapters[slot]->commit();
9638 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9639 mSerialPorts[slot]->commit();
9640 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9641 mParallelPorts[slot]->commit();
9642
9643 bool commitStorageControllers = false;
9644
9645 if (mStorageControllers.isBackedUp())
9646 {
9647 mStorageControllers.commit();
9648
9649 if (mPeer)
9650 {
9651 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9652
9653 /* Commit all changes to new controllers (this will reshare data with
9654 * peers for those who have peers) */
9655 StorageControllerList *newList = new StorageControllerList();
9656 StorageControllerList::const_iterator it = mStorageControllers->begin();
9657 while (it != mStorageControllers->end())
9658 {
9659 (*it)->commit();
9660
9661 /* look if this controller has a peer device */
9662 ComObjPtr<StorageController> peer = (*it)->getPeer();
9663 if (!peer)
9664 {
9665 /* no peer means the device is a newly created one;
9666 * create a peer owning data this device share it with */
9667 peer.createObject();
9668 peer->init(mPeer, *it, true /* aReshare */);
9669 }
9670 else
9671 {
9672 /* remove peer from the old list */
9673 mPeer->mStorageControllers->remove(peer);
9674 }
9675 /* and add it to the new list */
9676 newList->push_back(peer);
9677
9678 ++it;
9679 }
9680
9681 /* uninit old peer's controllers that are left */
9682 it = mPeer->mStorageControllers->begin();
9683 while (it != mPeer->mStorageControllers->end())
9684 {
9685 (*it)->uninit();
9686 ++it;
9687 }
9688
9689 /* attach new list of controllers to our peer */
9690 mPeer->mStorageControllers.attach(newList);
9691 }
9692 else
9693 {
9694 /* we have no peer (our parent is the newly created machine);
9695 * just commit changes to devices */
9696 commitStorageControllers = true;
9697 }
9698 }
9699 else
9700 {
9701 /* the list of controllers itself is not changed,
9702 * just commit changes to controllers themselves */
9703 commitStorageControllers = true;
9704 }
9705
9706 if (commitStorageControllers)
9707 {
9708 StorageControllerList::const_iterator it = mStorageControllers->begin();
9709 while (it != mStorageControllers->end())
9710 {
9711 (*it)->commit();
9712 ++it;
9713 }
9714 }
9715
9716 if (isSessionMachine())
9717 {
9718 /* attach new data to the primary machine and reshare it */
9719 mPeer->mUserData.attach(mUserData);
9720 mPeer->mHWData.attach(mHWData);
9721 /* mMediaData is reshared by fixupMedia */
9722 // mPeer->mMediaData.attach(mMediaData);
9723 Assert(mPeer->mMediaData.data() == mMediaData.data());
9724 }
9725}
9726
9727/**
9728 * Copies all the hardware data from the given machine.
9729 *
9730 * Currently, only called when the VM is being restored from a snapshot. In
9731 * particular, this implies that the VM is not running during this method's
9732 * call.
9733 *
9734 * @note This method must be called from under this object's lock.
9735 *
9736 * @note This method doesn't call #commit(), so all data remains backed up and
9737 * unsaved.
9738 */
9739void Machine::copyFrom(Machine *aThat)
9740{
9741 AssertReturnVoid(!isSnapshotMachine());
9742 AssertReturnVoid(aThat->isSnapshotMachine());
9743
9744 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9745
9746 mHWData.assignCopy(aThat->mHWData);
9747
9748 // create copies of all shared folders (mHWData after attaching a copy
9749 // contains just references to original objects)
9750 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9751 it != mHWData->mSharedFolders.end();
9752 ++it)
9753 {
9754 ComObjPtr<SharedFolder> folder;
9755 folder.createObject();
9756 HRESULT rc = folder->initCopy(getMachine(), *it);
9757 AssertComRC(rc);
9758 *it = folder;
9759 }
9760
9761 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9762 mVRDEServer->copyFrom(aThat->mVRDEServer);
9763 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9764 mUSBController->copyFrom(aThat->mUSBController);
9765 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
9766
9767 /* create private copies of all controllers */
9768 mStorageControllers.backup();
9769 mStorageControllers->clear();
9770 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9771 it != aThat->mStorageControllers->end();
9772 ++it)
9773 {
9774 ComObjPtr<StorageController> ctrl;
9775 ctrl.createObject();
9776 ctrl->initCopy(this, *it);
9777 mStorageControllers->push_back(ctrl);
9778 }
9779
9780 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9781 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9782 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9783 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9784 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9785 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9786}
9787
9788#ifdef VBOX_WITH_RESOURCE_USAGE_API
9789
9790void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9791{
9792 AssertReturnVoid(isWriteLockOnCurrentThread());
9793 AssertPtrReturnVoid(aCollector);
9794
9795 pm::CollectorHAL *hal = aCollector->getHAL();
9796 /* Create sub metrics */
9797 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9798 "Percentage of processor time spent in user mode by the VM process.");
9799 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9800 "Percentage of processor time spent in kernel mode by the VM process.");
9801 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9802 "Size of resident portion of VM process in memory.");
9803 /* Create and register base metrics */
9804 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9805 cpuLoadUser, cpuLoadKernel);
9806 aCollector->registerBaseMetric(cpuLoad);
9807 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9808 ramUsageUsed);
9809 aCollector->registerBaseMetric(ramUsage);
9810
9811 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9812 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9813 new pm::AggregateAvg()));
9814 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9815 new pm::AggregateMin()));
9816 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9817 new pm::AggregateMax()));
9818 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9819 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9820 new pm::AggregateAvg()));
9821 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9822 new pm::AggregateMin()));
9823 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9824 new pm::AggregateMax()));
9825
9826 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9827 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9828 new pm::AggregateAvg()));
9829 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9830 new pm::AggregateMin()));
9831 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9832 new pm::AggregateMax()));
9833
9834
9835 /* Guest metrics */
9836 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9837
9838 /* Create sub metrics */
9839 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9840 "Percentage of processor time spent in user mode as seen by the guest.");
9841 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9842 "Percentage of processor time spent in kernel mode as seen by the guest.");
9843 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9844 "Percentage of processor time spent idling as seen by the guest.");
9845
9846 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9847 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9848 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9849 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9850 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9851 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9852
9853 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9854
9855 /* Create and register base metrics */
9856 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9857 aCollector->registerBaseMetric(guestCpuLoad);
9858
9859 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9860 guestMemCache, guestPagedTotal);
9861 aCollector->registerBaseMetric(guestCpuMem);
9862
9863 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9864 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9865 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9866 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9867
9868 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9869 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9870 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9871 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9872
9873 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9874 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9875 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9876 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9877
9878 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9879 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9880 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9881 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9882
9883 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9884 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9885 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9886 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9887
9888 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9889 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9890 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9891 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9892
9893 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9894 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9895 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9896 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9897
9898 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9899 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9900 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9901 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9902
9903 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9904 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9905 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9906 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9907}
9908
9909void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9910{
9911 AssertReturnVoid(isWriteLockOnCurrentThread());
9912
9913 if (aCollector)
9914 {
9915 aCollector->unregisterMetricsFor(aMachine);
9916 aCollector->unregisterBaseMetricsFor(aMachine);
9917 }
9918
9919 if (mGuestHAL)
9920 {
9921 delete mGuestHAL;
9922 mGuestHAL = NULL;
9923 }
9924}
9925
9926#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9927
9928
9929////////////////////////////////////////////////////////////////////////////////
9930
9931DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9932
9933HRESULT SessionMachine::FinalConstruct()
9934{
9935 LogFlowThisFunc(("\n"));
9936
9937#if defined(RT_OS_WINDOWS)
9938 mIPCSem = NULL;
9939#elif defined(RT_OS_OS2)
9940 mIPCSem = NULLHANDLE;
9941#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9942 mIPCSem = -1;
9943#else
9944# error "Port me!"
9945#endif
9946
9947 return BaseFinalConstruct();
9948}
9949
9950void SessionMachine::FinalRelease()
9951{
9952 LogFlowThisFunc(("\n"));
9953
9954 uninit(Uninit::Unexpected);
9955
9956 BaseFinalRelease();
9957}
9958
9959/**
9960 * @note Must be called only by Machine::openSession() from its own write lock.
9961 */
9962HRESULT SessionMachine::init(Machine *aMachine)
9963{
9964 LogFlowThisFuncEnter();
9965 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9966
9967 AssertReturn(aMachine, E_INVALIDARG);
9968
9969 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9970
9971 /* Enclose the state transition NotReady->InInit->Ready */
9972 AutoInitSpan autoInitSpan(this);
9973 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9974
9975 /* create the interprocess semaphore */
9976#if defined(RT_OS_WINDOWS)
9977 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9978 for (size_t i = 0; i < mIPCSemName.length(); i++)
9979 if (mIPCSemName.raw()[i] == '\\')
9980 mIPCSemName.raw()[i] = '/';
9981 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
9982 ComAssertMsgRet(mIPCSem,
9983 ("Cannot create IPC mutex '%ls', err=%d",
9984 mIPCSemName.raw(), ::GetLastError()),
9985 E_FAIL);
9986#elif defined(RT_OS_OS2)
9987 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9988 aMachine->mData->mUuid.raw());
9989 mIPCSemName = ipcSem;
9990 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
9991 ComAssertMsgRet(arc == NO_ERROR,
9992 ("Cannot create IPC mutex '%s', arc=%ld",
9993 ipcSem.c_str(), arc),
9994 E_FAIL);
9995#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9996# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9997# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9998 /** @todo Check that this still works correctly. */
9999 AssertCompileSize(key_t, 8);
10000# else
10001 AssertCompileSize(key_t, 4);
10002# endif
10003 key_t key;
10004 mIPCSem = -1;
10005 mIPCKey = "0";
10006 for (uint32_t i = 0; i < 1 << 24; i++)
10007 {
10008 key = ((uint32_t)'V' << 24) | i;
10009 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10010 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10011 {
10012 mIPCSem = sem;
10013 if (sem >= 0)
10014 mIPCKey = BstrFmt("%u", key);
10015 break;
10016 }
10017 }
10018# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10019 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10020 char *pszSemName = NULL;
10021 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10022 key_t key = ::ftok(pszSemName, 'V');
10023 RTStrFree(pszSemName);
10024
10025 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10026# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10027
10028 int errnoSave = errno;
10029 if (mIPCSem < 0 && errnoSave == ENOSYS)
10030 {
10031 setError(E_FAIL,
10032 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10033 "support for SysV IPC. Check the host kernel configuration for "
10034 "CONFIG_SYSVIPC=y"));
10035 return E_FAIL;
10036 }
10037 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10038 * the IPC semaphores */
10039 if (mIPCSem < 0 && errnoSave == ENOSPC)
10040 {
10041#ifdef RT_OS_LINUX
10042 setError(E_FAIL,
10043 tr("Cannot create IPC semaphore because the system limit for the "
10044 "maximum number of semaphore sets (SEMMNI), or the system wide "
10045 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10046 "current set of SysV IPC semaphores can be determined from "
10047 "the file /proc/sysvipc/sem"));
10048#else
10049 setError(E_FAIL,
10050 tr("Cannot create IPC semaphore because the system-imposed limit "
10051 "on the maximum number of allowed semaphores or semaphore "
10052 "identifiers system-wide would be exceeded"));
10053#endif
10054 return E_FAIL;
10055 }
10056 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10057 E_FAIL);
10058 /* set the initial value to 1 */
10059 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10060 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10061 E_FAIL);
10062#else
10063# error "Port me!"
10064#endif
10065
10066 /* memorize the peer Machine */
10067 unconst(mPeer) = aMachine;
10068 /* share the parent pointer */
10069 unconst(mParent) = aMachine->mParent;
10070
10071 /* take the pointers to data to share */
10072 mData.share(aMachine->mData);
10073 mSSData.share(aMachine->mSSData);
10074
10075 mUserData.share(aMachine->mUserData);
10076 mHWData.share(aMachine->mHWData);
10077 mMediaData.share(aMachine->mMediaData);
10078
10079 mStorageControllers.allocate();
10080 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10081 it != aMachine->mStorageControllers->end();
10082 ++it)
10083 {
10084 ComObjPtr<StorageController> ctl;
10085 ctl.createObject();
10086 ctl->init(this, *it);
10087 mStorageControllers->push_back(ctl);
10088 }
10089
10090 unconst(mBIOSSettings).createObject();
10091 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10092 /* create another VRDEServer object that will be mutable */
10093 unconst(mVRDEServer).createObject();
10094 mVRDEServer->init(this, aMachine->mVRDEServer);
10095 /* create another audio adapter object that will be mutable */
10096 unconst(mAudioAdapter).createObject();
10097 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10098 /* create a list of serial ports that will be mutable */
10099 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10100 {
10101 unconst(mSerialPorts[slot]).createObject();
10102 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10103 }
10104 /* create a list of parallel ports that will be mutable */
10105 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10106 {
10107 unconst(mParallelPorts[slot]).createObject();
10108 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10109 }
10110 /* create another USB controller object that will be mutable */
10111 unconst(mUSBController).createObject();
10112 mUSBController->init(this, aMachine->mUSBController);
10113
10114 /* create a list of network adapters that will be mutable */
10115 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10116 {
10117 unconst(mNetworkAdapters[slot]).createObject();
10118 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10119 }
10120
10121 /* create another bandwidth control object that will be mutable */
10122 unconst(mBandwidthControl).createObject();
10123 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10124
10125 /* default is to delete saved state on Saved -> PoweredOff transition */
10126 mRemoveSavedState = true;
10127
10128 /* Confirm a successful initialization when it's the case */
10129 autoInitSpan.setSucceeded();
10130
10131 LogFlowThisFuncLeave();
10132 return S_OK;
10133}
10134
10135/**
10136 * Uninitializes this session object. If the reason is other than
10137 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10138 *
10139 * @param aReason uninitialization reason
10140 *
10141 * @note Locks mParent + this object for writing.
10142 */
10143void SessionMachine::uninit(Uninit::Reason aReason)
10144{
10145 LogFlowThisFuncEnter();
10146 LogFlowThisFunc(("reason=%d\n", aReason));
10147
10148 /*
10149 * Strongly reference ourselves to prevent this object deletion after
10150 * mData->mSession.mMachine.setNull() below (which can release the last
10151 * reference and call the destructor). Important: this must be done before
10152 * accessing any members (and before AutoUninitSpan that does it as well).
10153 * This self reference will be released as the very last step on return.
10154 */
10155 ComObjPtr<SessionMachine> selfRef = this;
10156
10157 /* Enclose the state transition Ready->InUninit->NotReady */
10158 AutoUninitSpan autoUninitSpan(this);
10159 if (autoUninitSpan.uninitDone())
10160 {
10161 LogFlowThisFunc(("Already uninitialized\n"));
10162 LogFlowThisFuncLeave();
10163 return;
10164 }
10165
10166 if (autoUninitSpan.initFailed())
10167 {
10168 /* We've been called by init() because it's failed. It's not really
10169 * necessary (nor it's safe) to perform the regular uninit sequence
10170 * below, the following is enough.
10171 */
10172 LogFlowThisFunc(("Initialization failed.\n"));
10173#if defined(RT_OS_WINDOWS)
10174 if (mIPCSem)
10175 ::CloseHandle(mIPCSem);
10176 mIPCSem = NULL;
10177#elif defined(RT_OS_OS2)
10178 if (mIPCSem != NULLHANDLE)
10179 ::DosCloseMutexSem(mIPCSem);
10180 mIPCSem = NULLHANDLE;
10181#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10182 if (mIPCSem >= 0)
10183 ::semctl(mIPCSem, 0, IPC_RMID);
10184 mIPCSem = -1;
10185# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10186 mIPCKey = "0";
10187# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10188#else
10189# error "Port me!"
10190#endif
10191 uninitDataAndChildObjects();
10192 mData.free();
10193 unconst(mParent) = NULL;
10194 unconst(mPeer) = NULL;
10195 LogFlowThisFuncLeave();
10196 return;
10197 }
10198
10199 MachineState_T lastState;
10200 {
10201 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10202 lastState = mData->mMachineState;
10203 }
10204 NOREF(lastState);
10205
10206#ifdef VBOX_WITH_USB
10207 // release all captured USB devices, but do this before requesting the locks below
10208 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10209 {
10210 /* Console::captureUSBDevices() is called in the VM process only after
10211 * setting the machine state to Starting or Restoring.
10212 * Console::detachAllUSBDevices() will be called upon successful
10213 * termination. So, we need to release USB devices only if there was
10214 * an abnormal termination of a running VM.
10215 *
10216 * This is identical to SessionMachine::DetachAllUSBDevices except
10217 * for the aAbnormal argument. */
10218 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10219 AssertComRC(rc);
10220 NOREF(rc);
10221
10222 USBProxyService *service = mParent->host()->usbProxyService();
10223 if (service)
10224 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10225 }
10226#endif /* VBOX_WITH_USB */
10227
10228 // we need to lock this object in uninit() because the lock is shared
10229 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10230 // and others need mParent lock, and USB needs host lock.
10231 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10232
10233 // Trigger async cleanup tasks, avoid doing things here which are not
10234 // vital to be done immediately and maybe need more locks. This calls
10235 // Machine::unregisterMetrics().
10236 mParent->onMachineUninit(mPeer);
10237
10238 if (aReason == Uninit::Abnormal)
10239 {
10240 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10241 Global::IsOnlineOrTransient(lastState)));
10242
10243 /* reset the state to Aborted */
10244 if (mData->mMachineState != MachineState_Aborted)
10245 setMachineState(MachineState_Aborted);
10246 }
10247
10248 // any machine settings modified?
10249 if (mData->flModifications)
10250 {
10251 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10252 rollback(false /* aNotify */);
10253 }
10254
10255 Assert(mConsoleTaskData.mStateFilePath.isEmpty() || !mConsoleTaskData.mSnapshot);
10256 if (!mConsoleTaskData.mStateFilePath.isEmpty())
10257 {
10258 LogWarningThisFunc(("canceling failed save state request!\n"));
10259 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10260 }
10261 else if (!mConsoleTaskData.mSnapshot.isNull())
10262 {
10263 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10264
10265 /* delete all differencing hard disks created (this will also attach
10266 * their parents back by rolling back mMediaData) */
10267 rollbackMedia();
10268 /* delete the saved state file (it might have been already created) */
10269 if (mConsoleTaskData.mSnapshot->stateFilePath().length())
10270 RTFileDelete(mConsoleTaskData.mSnapshot->stateFilePath().c_str());
10271
10272 mConsoleTaskData.mSnapshot->uninit();
10273 }
10274
10275 if (!mData->mSession.mType.isEmpty())
10276 {
10277 /* mType is not null when this machine's process has been started by
10278 * Machine::launchVMProcess(), therefore it is our child. We
10279 * need to queue the PID to reap the process (and avoid zombies on
10280 * Linux). */
10281 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10282 mParent->addProcessToReap(mData->mSession.mPid);
10283 }
10284
10285 mData->mSession.mPid = NIL_RTPROCESS;
10286
10287 if (aReason == Uninit::Unexpected)
10288 {
10289 /* Uninitialization didn't come from #checkForDeath(), so tell the
10290 * client watcher thread to update the set of machines that have open
10291 * sessions. */
10292 mParent->updateClientWatcher();
10293 }
10294
10295 /* uninitialize all remote controls */
10296 if (mData->mSession.mRemoteControls.size())
10297 {
10298 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10299 mData->mSession.mRemoteControls.size()));
10300
10301 Data::Session::RemoteControlList::iterator it =
10302 mData->mSession.mRemoteControls.begin();
10303 while (it != mData->mSession.mRemoteControls.end())
10304 {
10305 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10306 HRESULT rc = (*it)->Uninitialize();
10307 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10308 if (FAILED(rc))
10309 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10310 ++it;
10311 }
10312 mData->mSession.mRemoteControls.clear();
10313 }
10314
10315 /*
10316 * An expected uninitialization can come only from #checkForDeath().
10317 * Otherwise it means that something's gone really wrong (for example,
10318 * the Session implementation has released the VirtualBox reference
10319 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10320 * etc). However, it's also possible, that the client releases the IPC
10321 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10322 * but the VirtualBox release event comes first to the server process.
10323 * This case is practically possible, so we should not assert on an
10324 * unexpected uninit, just log a warning.
10325 */
10326
10327 if ((aReason == Uninit::Unexpected))
10328 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10329
10330 if (aReason != Uninit::Normal)
10331 {
10332 mData->mSession.mDirectControl.setNull();
10333 }
10334 else
10335 {
10336 /* this must be null here (see #OnSessionEnd()) */
10337 Assert(mData->mSession.mDirectControl.isNull());
10338 Assert(mData->mSession.mState == SessionState_Unlocking);
10339 Assert(!mData->mSession.mProgress.isNull());
10340 }
10341 if (mData->mSession.mProgress)
10342 {
10343 if (aReason == Uninit::Normal)
10344 mData->mSession.mProgress->notifyComplete(S_OK);
10345 else
10346 mData->mSession.mProgress->notifyComplete(E_FAIL,
10347 COM_IIDOF(ISession),
10348 getComponentName(),
10349 tr("The VM session was aborted"));
10350 mData->mSession.mProgress.setNull();
10351 }
10352
10353 /* remove the association between the peer machine and this session machine */
10354 Assert( (SessionMachine*)mData->mSession.mMachine == this
10355 || aReason == Uninit::Unexpected);
10356
10357 /* reset the rest of session data */
10358 mData->mSession.mMachine.setNull();
10359 mData->mSession.mState = SessionState_Unlocked;
10360 mData->mSession.mType.setNull();
10361
10362 /* close the interprocess semaphore before leaving the exclusive lock */
10363#if defined(RT_OS_WINDOWS)
10364 if (mIPCSem)
10365 ::CloseHandle(mIPCSem);
10366 mIPCSem = NULL;
10367#elif defined(RT_OS_OS2)
10368 if (mIPCSem != NULLHANDLE)
10369 ::DosCloseMutexSem(mIPCSem);
10370 mIPCSem = NULLHANDLE;
10371#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10372 if (mIPCSem >= 0)
10373 ::semctl(mIPCSem, 0, IPC_RMID);
10374 mIPCSem = -1;
10375# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10376 mIPCKey = "0";
10377# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10378#else
10379# error "Port me!"
10380#endif
10381
10382 /* fire an event */
10383 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10384
10385 uninitDataAndChildObjects();
10386
10387 /* free the essential data structure last */
10388 mData.free();
10389
10390#if 1 /** @todo Please review this change! (bird) */
10391 /* drop the exclusive lock before setting the below two to NULL */
10392 multilock.release();
10393#else
10394 /* leave the exclusive lock before setting the below two to NULL */
10395 multilock.leave();
10396#endif
10397
10398 unconst(mParent) = NULL;
10399 unconst(mPeer) = NULL;
10400
10401 LogFlowThisFuncLeave();
10402}
10403
10404// util::Lockable interface
10405////////////////////////////////////////////////////////////////////////////////
10406
10407/**
10408 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10409 * with the primary Machine instance (mPeer).
10410 */
10411RWLockHandle *SessionMachine::lockHandle() const
10412{
10413 AssertReturn(mPeer != NULL, NULL);
10414 return mPeer->lockHandle();
10415}
10416
10417// IInternalMachineControl methods
10418////////////////////////////////////////////////////////////////////////////////
10419
10420/**
10421 * @note Locks this object for writing.
10422 */
10423STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10424{
10425 AutoCaller autoCaller(this);
10426 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10427
10428 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10429
10430 mRemoveSavedState = aRemove;
10431
10432 return S_OK;
10433}
10434
10435/**
10436 * @note Locks the same as #setMachineState() does.
10437 */
10438STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10439{
10440 return setMachineState(aMachineState);
10441}
10442
10443/**
10444 * @note Locks this object for reading.
10445 */
10446STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10447{
10448 AutoCaller autoCaller(this);
10449 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10450
10451 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10452
10453#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10454 mIPCSemName.cloneTo(aId);
10455 return S_OK;
10456#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10457# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10458 mIPCKey.cloneTo(aId);
10459# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10460 mData->m_strConfigFileFull.cloneTo(aId);
10461# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10462 return S_OK;
10463#else
10464# error "Port me!"
10465#endif
10466}
10467
10468/**
10469 * @note Locks this object for writing.
10470 */
10471STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10472{
10473 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10474 AutoCaller autoCaller(this);
10475 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10476
10477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10478
10479 if (mData->mSession.mState != SessionState_Locked)
10480 return VBOX_E_INVALID_OBJECT_STATE;
10481
10482 if (!mData->mSession.mProgress.isNull())
10483 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10484
10485 LogFlowThisFunc(("returns S_OK.\n"));
10486 return S_OK;
10487}
10488
10489/**
10490 * @note Locks this object for writing.
10491 */
10492STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10493{
10494 AutoCaller autoCaller(this);
10495 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10496
10497 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10498
10499 if (mData->mSession.mState != SessionState_Locked)
10500 return VBOX_E_INVALID_OBJECT_STATE;
10501
10502 /* Finalize the openRemoteSession progress object. */
10503 if (mData->mSession.mProgress)
10504 {
10505 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10506 mData->mSession.mProgress.setNull();
10507 }
10508
10509 if (SUCCEEDED((HRESULT)iResult))
10510 {
10511#ifdef VBOX_WITH_RESOURCE_USAGE_API
10512 /* The VM has been powered up successfully, so it makes sense
10513 * now to offer the performance metrics for a running machine
10514 * object. Doing it earlier wouldn't be safe. */
10515 registerMetrics(mParent->performanceCollector(), mPeer,
10516 mData->mSession.mPid);
10517#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10518 }
10519
10520 return S_OK;
10521}
10522
10523/**
10524 * @note Locks this object for writing.
10525 */
10526STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
10527{
10528 LogFlowThisFuncEnter();
10529
10530 CheckComArgOutPointerValid(aProgress);
10531
10532 AutoCaller autoCaller(this);
10533 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10534
10535 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10536
10537 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
10538 E_FAIL);
10539
10540 /* create a progress object to track operation completion */
10541 ComObjPtr<Progress> pProgress;
10542 pProgress.createObject();
10543 pProgress->init(getVirtualBox(),
10544 static_cast<IMachine *>(this) /* aInitiator */,
10545 Bstr(tr("Stopping the virtual machine")).raw(),
10546 FALSE /* aCancelable */);
10547
10548 /* fill in the console task data */
10549 mConsoleTaskData.mLastState = mData->mMachineState;
10550 mConsoleTaskData.mProgress = pProgress;
10551
10552 /* set the state to Stopping (this is expected by Console::PowerDown()) */
10553 setMachineState(MachineState_Stopping);
10554
10555 pProgress.queryInterfaceTo(aProgress);
10556
10557 return S_OK;
10558}
10559
10560/**
10561 * @note Locks this object for writing.
10562 */
10563STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
10564{
10565 LogFlowThisFuncEnter();
10566
10567 AutoCaller autoCaller(this);
10568 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10569
10570 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10571
10572 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
10573 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
10574 && mConsoleTaskData.mLastState != MachineState_Null,
10575 E_FAIL);
10576
10577 /*
10578 * On failure, set the state to the state we had when BeginPoweringDown()
10579 * was called (this is expected by Console::PowerDown() and the associated
10580 * task). On success the VM process already changed the state to
10581 * MachineState_PoweredOff, so no need to do anything.
10582 */
10583 if (FAILED(iResult))
10584 setMachineState(mConsoleTaskData.mLastState);
10585
10586 /* notify the progress object about operation completion */
10587 Assert(mConsoleTaskData.mProgress);
10588 if (SUCCEEDED(iResult))
10589 mConsoleTaskData.mProgress->notifyComplete(S_OK);
10590 else
10591 {
10592 Utf8Str strErrMsg(aErrMsg);
10593 if (strErrMsg.length())
10594 mConsoleTaskData.mProgress->notifyComplete(iResult,
10595 COM_IIDOF(ISession),
10596 getComponentName(),
10597 strErrMsg.c_str());
10598 else
10599 mConsoleTaskData.mProgress->notifyComplete(iResult);
10600 }
10601
10602 /* clear out the temporary saved state data */
10603 mConsoleTaskData.mLastState = MachineState_Null;
10604 mConsoleTaskData.mProgress.setNull();
10605
10606 LogFlowThisFuncLeave();
10607 return S_OK;
10608}
10609
10610
10611/**
10612 * Goes through the USB filters of the given machine to see if the given
10613 * device matches any filter or not.
10614 *
10615 * @note Locks the same as USBController::hasMatchingFilter() does.
10616 */
10617STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10618 BOOL *aMatched,
10619 ULONG *aMaskedIfs)
10620{
10621 LogFlowThisFunc(("\n"));
10622
10623 CheckComArgNotNull(aUSBDevice);
10624 CheckComArgOutPointerValid(aMatched);
10625
10626 AutoCaller autoCaller(this);
10627 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10628
10629#ifdef VBOX_WITH_USB
10630 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10631#else
10632 NOREF(aUSBDevice);
10633 NOREF(aMaskedIfs);
10634 *aMatched = FALSE;
10635#endif
10636
10637 return S_OK;
10638}
10639
10640/**
10641 * @note Locks the same as Host::captureUSBDevice() does.
10642 */
10643STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10644{
10645 LogFlowThisFunc(("\n"));
10646
10647 AutoCaller autoCaller(this);
10648 AssertComRCReturnRC(autoCaller.rc());
10649
10650#ifdef VBOX_WITH_USB
10651 /* if captureDeviceForVM() fails, it must have set extended error info */
10652 MultiResult rc = mParent->host()->checkUSBProxyService();
10653 if (FAILED(rc)) return rc;
10654
10655 USBProxyService *service = mParent->host()->usbProxyService();
10656 AssertReturn(service, E_FAIL);
10657 return service->captureDeviceForVM(this, Guid(aId).ref());
10658#else
10659 NOREF(aId);
10660 return E_NOTIMPL;
10661#endif
10662}
10663
10664/**
10665 * @note Locks the same as Host::detachUSBDevice() does.
10666 */
10667STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10668{
10669 LogFlowThisFunc(("\n"));
10670
10671 AutoCaller autoCaller(this);
10672 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10673
10674#ifdef VBOX_WITH_USB
10675 USBProxyService *service = mParent->host()->usbProxyService();
10676 AssertReturn(service, E_FAIL);
10677 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10678#else
10679 NOREF(aId);
10680 NOREF(aDone);
10681 return E_NOTIMPL;
10682#endif
10683}
10684
10685/**
10686 * Inserts all machine filters to the USB proxy service and then calls
10687 * Host::autoCaptureUSBDevices().
10688 *
10689 * Called by Console from the VM process upon VM startup.
10690 *
10691 * @note Locks what called methods lock.
10692 */
10693STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10694{
10695 LogFlowThisFunc(("\n"));
10696
10697 AutoCaller autoCaller(this);
10698 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10699
10700#ifdef VBOX_WITH_USB
10701 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10702 AssertComRC(rc);
10703 NOREF(rc);
10704
10705 USBProxyService *service = mParent->host()->usbProxyService();
10706 AssertReturn(service, E_FAIL);
10707 return service->autoCaptureDevicesForVM(this);
10708#else
10709 return S_OK;
10710#endif
10711}
10712
10713/**
10714 * Removes all machine filters from the USB proxy service and then calls
10715 * Host::detachAllUSBDevices().
10716 *
10717 * Called by Console from the VM process upon normal VM termination or by
10718 * SessionMachine::uninit() upon abnormal VM termination (from under the
10719 * Machine/SessionMachine lock).
10720 *
10721 * @note Locks what called methods lock.
10722 */
10723STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10724{
10725 LogFlowThisFunc(("\n"));
10726
10727 AutoCaller autoCaller(this);
10728 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10729
10730#ifdef VBOX_WITH_USB
10731 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10732 AssertComRC(rc);
10733 NOREF(rc);
10734
10735 USBProxyService *service = mParent->host()->usbProxyService();
10736 AssertReturn(service, E_FAIL);
10737 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10738#else
10739 NOREF(aDone);
10740 return S_OK;
10741#endif
10742}
10743
10744/**
10745 * @note Locks this object for writing.
10746 */
10747STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10748 IProgress **aProgress)
10749{
10750 LogFlowThisFuncEnter();
10751
10752 AssertReturn(aSession, E_INVALIDARG);
10753 AssertReturn(aProgress, E_INVALIDARG);
10754
10755 AutoCaller autoCaller(this);
10756
10757 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10758 /*
10759 * We don't assert below because it might happen that a non-direct session
10760 * informs us it is closed right after we've been uninitialized -- it's ok.
10761 */
10762 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10763
10764 /* get IInternalSessionControl interface */
10765 ComPtr<IInternalSessionControl> control(aSession);
10766
10767 ComAssertRet(!control.isNull(), E_INVALIDARG);
10768
10769 /* Creating a Progress object requires the VirtualBox lock, and
10770 * thus locking it here is required by the lock order rules. */
10771 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10772
10773 if (control == mData->mSession.mDirectControl)
10774 {
10775 ComAssertRet(aProgress, E_POINTER);
10776
10777 /* The direct session is being normally closed by the client process
10778 * ----------------------------------------------------------------- */
10779
10780 /* go to the closing state (essential for all open*Session() calls and
10781 * for #checkForDeath()) */
10782 Assert(mData->mSession.mState == SessionState_Locked);
10783 mData->mSession.mState = SessionState_Unlocking;
10784
10785 /* set direct control to NULL to release the remote instance */
10786 mData->mSession.mDirectControl.setNull();
10787 LogFlowThisFunc(("Direct control is set to NULL\n"));
10788
10789 if (mData->mSession.mProgress)
10790 {
10791 /* finalize the progress, someone might wait if a frontend
10792 * closes the session before powering on the VM. */
10793 mData->mSession.mProgress->notifyComplete(E_FAIL,
10794 COM_IIDOF(ISession),
10795 getComponentName(),
10796 tr("The VM session was closed before any attempt to power it on"));
10797 mData->mSession.mProgress.setNull();
10798 }
10799
10800 /* Create the progress object the client will use to wait until
10801 * #checkForDeath() is called to uninitialize this session object after
10802 * it releases the IPC semaphore.
10803 * Note! Because we're "reusing" mProgress here, this must be a proxy
10804 * object just like for openRemoteSession. */
10805 Assert(mData->mSession.mProgress.isNull());
10806 ComObjPtr<ProgressProxy> progress;
10807 progress.createObject();
10808 ComPtr<IUnknown> pPeer(mPeer);
10809 progress->init(mParent, pPeer,
10810 Bstr(tr("Closing session")).raw(),
10811 FALSE /* aCancelable */);
10812 progress.queryInterfaceTo(aProgress);
10813 mData->mSession.mProgress = progress;
10814 }
10815 else
10816 {
10817 /* the remote session is being normally closed */
10818 Data::Session::RemoteControlList::iterator it =
10819 mData->mSession.mRemoteControls.begin();
10820 while (it != mData->mSession.mRemoteControls.end())
10821 {
10822 if (control == *it)
10823 break;
10824 ++it;
10825 }
10826 BOOL found = it != mData->mSession.mRemoteControls.end();
10827 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10828 E_INVALIDARG);
10829 mData->mSession.mRemoteControls.remove(*it);
10830 }
10831
10832 LogFlowThisFuncLeave();
10833 return S_OK;
10834}
10835
10836/**
10837 * @note Locks this object for writing.
10838 */
10839STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
10840{
10841 LogFlowThisFuncEnter();
10842
10843 CheckComArgOutPointerValid(aProgress);
10844 CheckComArgOutPointerValid(aStateFilePath);
10845
10846 AutoCaller autoCaller(this);
10847 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10848
10849 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10850
10851 AssertReturn( mData->mMachineState == MachineState_Paused
10852 && mConsoleTaskData.mLastState == MachineState_Null
10853 && mConsoleTaskData.mStateFilePath.isEmpty(),
10854 E_FAIL);
10855
10856 /* create a progress object to track operation completion */
10857 ComObjPtr<Progress> pProgress;
10858 pProgress.createObject();
10859 pProgress->init(getVirtualBox(),
10860 static_cast<IMachine *>(this) /* aInitiator */,
10861 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
10862 FALSE /* aCancelable */);
10863
10864 Bstr stateFilePath;
10865 /* stateFilePath is null when the machine is not running */
10866 if (mData->mMachineState == MachineState_Paused)
10867 {
10868 Utf8Str strFullSnapshotFolder;
10869 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10870 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10871 strFullSnapshotFolder.c_str(),
10872 RTPATH_DELIMITER,
10873 mData->mUuid.raw());
10874 }
10875
10876 /* fill in the console task data */
10877 mConsoleTaskData.mLastState = mData->mMachineState;
10878 mConsoleTaskData.mStateFilePath = stateFilePath;
10879 mConsoleTaskData.mProgress = pProgress;
10880
10881 /* set the state to Saving (this is expected by Console::SaveState()) */
10882 setMachineState(MachineState_Saving);
10883
10884 stateFilePath.cloneTo(aStateFilePath);
10885 pProgress.queryInterfaceTo(aProgress);
10886
10887 return S_OK;
10888}
10889
10890/**
10891 * @note Locks mParent + this object for writing.
10892 */
10893STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
10894{
10895 LogFlowThisFunc(("\n"));
10896
10897 AutoCaller autoCaller(this);
10898 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10899
10900 /* endSavingState() need mParent lock */
10901 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10902
10903 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
10904 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
10905 && mConsoleTaskData.mLastState != MachineState_Null
10906 && !mConsoleTaskData.mStateFilePath.isEmpty(),
10907 E_FAIL);
10908
10909 /*
10910 * On failure, set the state to the state we had when BeginSavingState()
10911 * was called (this is expected by Console::SaveState() and the associated
10912 * task). On success the VM process already changed the state to
10913 * MachineState_Saved, so no need to do anything.
10914 */
10915 if (FAILED(iResult))
10916 setMachineState(mConsoleTaskData.mLastState);
10917
10918 return endSavingState(iResult, aErrMsg);
10919}
10920
10921/**
10922 * @note Locks this object for writing.
10923 */
10924STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10925{
10926 LogFlowThisFunc(("\n"));
10927
10928 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10929
10930 AutoCaller autoCaller(this);
10931 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10932
10933 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10934
10935 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10936 || mData->mMachineState == MachineState_Teleported
10937 || mData->mMachineState == MachineState_Aborted
10938 , E_FAIL); /** @todo setError. */
10939
10940 Utf8Str stateFilePathFull = aSavedStateFile;
10941 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10942 if (RT_FAILURE(vrc))
10943 return setError(VBOX_E_FILE_ERROR,
10944 tr("Invalid saved state file path '%ls' (%Rrc)"),
10945 aSavedStateFile,
10946 vrc);
10947
10948 mSSData->mStateFilePath = stateFilePathFull;
10949
10950 /* The below setMachineState() will detect the state transition and will
10951 * update the settings file */
10952
10953 return setMachineState(MachineState_Saved);
10954}
10955
10956STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10957 ComSafeArrayOut(BSTR, aValues),
10958 ComSafeArrayOut(LONG64, aTimestamps),
10959 ComSafeArrayOut(BSTR, aFlags))
10960{
10961 LogFlowThisFunc(("\n"));
10962
10963#ifdef VBOX_WITH_GUEST_PROPS
10964 using namespace guestProp;
10965
10966 AutoCaller autoCaller(this);
10967 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10968
10969 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10970
10971 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10972 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10973 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10974 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10975
10976 size_t cEntries = mHWData->mGuestProperties.size();
10977 com::SafeArray<BSTR> names(cEntries);
10978 com::SafeArray<BSTR> values(cEntries);
10979 com::SafeArray<LONG64> timestamps(cEntries);
10980 com::SafeArray<BSTR> flags(cEntries);
10981 unsigned i = 0;
10982 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10983 it != mHWData->mGuestProperties.end();
10984 ++it)
10985 {
10986 char szFlags[MAX_FLAGS_LEN + 1];
10987 it->strName.cloneTo(&names[i]);
10988 it->strValue.cloneTo(&values[i]);
10989 timestamps[i] = it->mTimestamp;
10990 /* If it is NULL, keep it NULL. */
10991 if (it->mFlags)
10992 {
10993 writeFlags(it->mFlags, szFlags);
10994 Bstr(szFlags).cloneTo(&flags[i]);
10995 }
10996 else
10997 flags[i] = NULL;
10998 ++i;
10999 }
11000 names.detachTo(ComSafeArrayOutArg(aNames));
11001 values.detachTo(ComSafeArrayOutArg(aValues));
11002 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11003 flags.detachTo(ComSafeArrayOutArg(aFlags));
11004 return S_OK;
11005#else
11006 ReturnComNotImplemented();
11007#endif
11008}
11009
11010STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11011 IN_BSTR aValue,
11012 LONG64 aTimestamp,
11013 IN_BSTR aFlags)
11014{
11015 LogFlowThisFunc(("\n"));
11016
11017#ifdef VBOX_WITH_GUEST_PROPS
11018 using namespace guestProp;
11019
11020 CheckComArgStrNotEmptyOrNull(aName);
11021 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
11022 return E_POINTER; /* aValue can be NULL to indicate deletion */
11023
11024 try
11025 {
11026 /*
11027 * Convert input up front.
11028 */
11029 Utf8Str utf8Name(aName);
11030 uint32_t fFlags = NILFLAG;
11031 if (aFlags)
11032 {
11033 Utf8Str utf8Flags(aFlags);
11034 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11035 AssertRCReturn(vrc, E_INVALIDARG);
11036 }
11037
11038 /*
11039 * Now grab the object lock, validate the state and do the update.
11040 */
11041 AutoCaller autoCaller(this);
11042 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11043
11044 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11045
11046 switch (mData->mMachineState)
11047 {
11048 case MachineState_Paused:
11049 case MachineState_Running:
11050 case MachineState_Teleporting:
11051 case MachineState_TeleportingPausedVM:
11052 case MachineState_LiveSnapshotting:
11053 case MachineState_DeletingSnapshotOnline:
11054 case MachineState_DeletingSnapshotPaused:
11055 case MachineState_Saving:
11056 break;
11057
11058 default:
11059#ifndef DEBUG_sunlover
11060 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11061 VBOX_E_INVALID_VM_STATE);
11062#else
11063 return VBOX_E_INVALID_VM_STATE;
11064#endif
11065 }
11066
11067 setModified(IsModified_MachineData);
11068 mHWData.backup();
11069
11070 /** @todo r=bird: The careful memory handling doesn't work out here because
11071 * the catch block won't undo any damage we've done. So, if push_back throws
11072 * bad_alloc then you've lost the value.
11073 *
11074 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11075 * since values that changes actually bubbles to the end of the list. Using
11076 * something that has an efficient lookup and can tolerate a bit of updates
11077 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11078 * combination of RTStrCache (for sharing names and getting uniqueness into
11079 * the bargain) and hash/tree is another. */
11080 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11081 iter != mHWData->mGuestProperties.end();
11082 ++iter)
11083 if (utf8Name == iter->strName)
11084 {
11085 mHWData->mGuestProperties.erase(iter);
11086 mData->mGuestPropertiesModified = TRUE;
11087 break;
11088 }
11089 if (aValue != NULL)
11090 {
11091 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11092 mHWData->mGuestProperties.push_back(property);
11093 mData->mGuestPropertiesModified = TRUE;
11094 }
11095
11096 /*
11097 * Send a callback notification if appropriate
11098 */
11099 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11100 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11101 RTSTR_MAX,
11102 utf8Name.c_str(),
11103 RTSTR_MAX, NULL)
11104 )
11105 {
11106 alock.leave();
11107
11108 mParent->onGuestPropertyChange(mData->mUuid,
11109 aName,
11110 aValue,
11111 aFlags);
11112 }
11113 }
11114 catch (...)
11115 {
11116 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11117 }
11118 return S_OK;
11119#else
11120 ReturnComNotImplemented();
11121#endif
11122}
11123
11124// public methods only for internal purposes
11125/////////////////////////////////////////////////////////////////////////////
11126
11127/**
11128 * Called from the client watcher thread to check for expected or unexpected
11129 * death of the client process that has a direct session to this machine.
11130 *
11131 * On Win32 and on OS/2, this method is called only when we've got the
11132 * mutex (i.e. the client has either died or terminated normally) so it always
11133 * returns @c true (the client is terminated, the session machine is
11134 * uninitialized).
11135 *
11136 * On other platforms, the method returns @c true if the client process has
11137 * terminated normally or abnormally and the session machine was uninitialized,
11138 * and @c false if the client process is still alive.
11139 *
11140 * @note Locks this object for writing.
11141 */
11142bool SessionMachine::checkForDeath()
11143{
11144 Uninit::Reason reason;
11145 bool terminated = false;
11146
11147 /* Enclose autoCaller with a block because calling uninit() from under it
11148 * will deadlock. */
11149 {
11150 AutoCaller autoCaller(this);
11151 if (!autoCaller.isOk())
11152 {
11153 /* return true if not ready, to cause the client watcher to exclude
11154 * the corresponding session from watching */
11155 LogFlowThisFunc(("Already uninitialized!\n"));
11156 return true;
11157 }
11158
11159 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11160
11161 /* Determine the reason of death: if the session state is Closing here,
11162 * everything is fine. Otherwise it means that the client did not call
11163 * OnSessionEnd() before it released the IPC semaphore. This may happen
11164 * either because the client process has abnormally terminated, or
11165 * because it simply forgot to call ISession::Close() before exiting. We
11166 * threat the latter also as an abnormal termination (see
11167 * Session::uninit() for details). */
11168 reason = mData->mSession.mState == SessionState_Unlocking ?
11169 Uninit::Normal :
11170 Uninit::Abnormal;
11171
11172#if defined(RT_OS_WINDOWS)
11173
11174 AssertMsg(mIPCSem, ("semaphore must be created"));
11175
11176 /* release the IPC mutex */
11177 ::ReleaseMutex(mIPCSem);
11178
11179 terminated = true;
11180
11181#elif defined(RT_OS_OS2)
11182
11183 AssertMsg(mIPCSem, ("semaphore must be created"));
11184
11185 /* release the IPC mutex */
11186 ::DosReleaseMutexSem(mIPCSem);
11187
11188 terminated = true;
11189
11190#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11191
11192 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11193
11194 int val = ::semctl(mIPCSem, 0, GETVAL);
11195 if (val > 0)
11196 {
11197 /* the semaphore is signaled, meaning the session is terminated */
11198 terminated = true;
11199 }
11200
11201#else
11202# error "Port me!"
11203#endif
11204
11205 } /* AutoCaller block */
11206
11207 if (terminated)
11208 uninit(reason);
11209
11210 return terminated;
11211}
11212
11213/**
11214 * @note Locks this object for reading.
11215 */
11216HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11217{
11218 LogFlowThisFunc(("\n"));
11219
11220 AutoCaller autoCaller(this);
11221 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11222
11223 ComPtr<IInternalSessionControl> directControl;
11224 {
11225 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11226 directControl = mData->mSession.mDirectControl;
11227 }
11228
11229 /* ignore notifications sent after #OnSessionEnd() is called */
11230 if (!directControl)
11231 return S_OK;
11232
11233 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11234}
11235
11236/**
11237 * @note Locks this object for reading.
11238 */
11239HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11240 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
11241{
11242 LogFlowThisFunc(("\n"));
11243
11244 AutoCaller autoCaller(this);
11245 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11246
11247 ComPtr<IInternalSessionControl> directControl;
11248 {
11249 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11250 directControl = mData->mSession.mDirectControl;
11251 }
11252
11253 /* ignore notifications sent after #OnSessionEnd() is called */
11254 if (!directControl)
11255 return S_OK;
11256 /*
11257 * instead acting like callback we ask IVirtualBox deliver corresponding event
11258 */
11259
11260 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
11261 return S_OK;
11262}
11263
11264/**
11265 * @note Locks this object for reading.
11266 */
11267HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
11268{
11269 LogFlowThisFunc(("\n"));
11270
11271 AutoCaller autoCaller(this);
11272 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11273
11274 ComPtr<IInternalSessionControl> directControl;
11275 {
11276 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11277 directControl = mData->mSession.mDirectControl;
11278 }
11279
11280 /* ignore notifications sent after #OnSessionEnd() is called */
11281 if (!directControl)
11282 return S_OK;
11283
11284 return directControl->OnSerialPortChange(serialPort);
11285}
11286
11287/**
11288 * @note Locks this object for reading.
11289 */
11290HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
11291{
11292 LogFlowThisFunc(("\n"));
11293
11294 AutoCaller autoCaller(this);
11295 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11296
11297 ComPtr<IInternalSessionControl> directControl;
11298 {
11299 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11300 directControl = mData->mSession.mDirectControl;
11301 }
11302
11303 /* ignore notifications sent after #OnSessionEnd() is called */
11304 if (!directControl)
11305 return S_OK;
11306
11307 return directControl->OnParallelPortChange(parallelPort);
11308}
11309
11310/**
11311 * @note Locks this object for reading.
11312 */
11313HRESULT SessionMachine::onStorageControllerChange()
11314{
11315 LogFlowThisFunc(("\n"));
11316
11317 AutoCaller autoCaller(this);
11318 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11319
11320 ComPtr<IInternalSessionControl> directControl;
11321 {
11322 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11323 directControl = mData->mSession.mDirectControl;
11324 }
11325
11326 /* ignore notifications sent after #OnSessionEnd() is called */
11327 if (!directControl)
11328 return S_OK;
11329
11330 return directControl->OnStorageControllerChange();
11331}
11332
11333/**
11334 * @note Locks this object for reading.
11335 */
11336HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11337{
11338 LogFlowThisFunc(("\n"));
11339
11340 AutoCaller autoCaller(this);
11341 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11342
11343 ComPtr<IInternalSessionControl> directControl;
11344 {
11345 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11346 directControl = mData->mSession.mDirectControl;
11347 }
11348
11349 /* ignore notifications sent after #OnSessionEnd() is called */
11350 if (!directControl)
11351 return S_OK;
11352
11353 return directControl->OnMediumChange(aAttachment, aForce);
11354}
11355
11356/**
11357 * @note Locks this object for reading.
11358 */
11359HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11360{
11361 LogFlowThisFunc(("\n"));
11362
11363 AutoCaller autoCaller(this);
11364 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11365
11366 ComPtr<IInternalSessionControl> directControl;
11367 {
11368 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11369 directControl = mData->mSession.mDirectControl;
11370 }
11371
11372 /* ignore notifications sent after #OnSessionEnd() is called */
11373 if (!directControl)
11374 return S_OK;
11375
11376 return directControl->OnCPUChange(aCPU, aRemove);
11377}
11378
11379HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11380{
11381 LogFlowThisFunc(("\n"));
11382
11383 AutoCaller autoCaller(this);
11384 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11385
11386 ComPtr<IInternalSessionControl> directControl;
11387 {
11388 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11389 directControl = mData->mSession.mDirectControl;
11390 }
11391
11392 /* ignore notifications sent after #OnSessionEnd() is called */
11393 if (!directControl)
11394 return S_OK;
11395
11396 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11397}
11398
11399/**
11400 * @note Locks this object for reading.
11401 */
11402HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11403{
11404 LogFlowThisFunc(("\n"));
11405
11406 AutoCaller autoCaller(this);
11407 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11408
11409 ComPtr<IInternalSessionControl> directControl;
11410 {
11411 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11412 directControl = mData->mSession.mDirectControl;
11413 }
11414
11415 /* ignore notifications sent after #OnSessionEnd() is called */
11416 if (!directControl)
11417 return S_OK;
11418
11419 return directControl->OnVRDEServerChange(aRestart);
11420}
11421
11422/**
11423 * @note Locks this object for reading.
11424 */
11425HRESULT SessionMachine::onUSBControllerChange()
11426{
11427 LogFlowThisFunc(("\n"));
11428
11429 AutoCaller autoCaller(this);
11430 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11431
11432 ComPtr<IInternalSessionControl> directControl;
11433 {
11434 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11435 directControl = mData->mSession.mDirectControl;
11436 }
11437
11438 /* ignore notifications sent after #OnSessionEnd() is called */
11439 if (!directControl)
11440 return S_OK;
11441
11442 return directControl->OnUSBControllerChange();
11443}
11444
11445/**
11446 * @note Locks this object for reading.
11447 */
11448HRESULT SessionMachine::onSharedFolderChange()
11449{
11450 LogFlowThisFunc(("\n"));
11451
11452 AutoCaller autoCaller(this);
11453 AssertComRCReturnRC(autoCaller.rc());
11454
11455 ComPtr<IInternalSessionControl> directControl;
11456 {
11457 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11458 directControl = mData->mSession.mDirectControl;
11459 }
11460
11461 /* ignore notifications sent after #OnSessionEnd() is called */
11462 if (!directControl)
11463 return S_OK;
11464
11465 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11466}
11467
11468/**
11469 * @note Locks this object for reading.
11470 */
11471HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
11472{
11473 LogFlowThisFunc(("\n"));
11474
11475 AutoCaller autoCaller(this);
11476 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11477
11478 ComPtr<IInternalSessionControl> directControl;
11479 {
11480 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11481 directControl = mData->mSession.mDirectControl;
11482 }
11483
11484 /* ignore notifications sent after #OnSessionEnd() is called */
11485 if (!directControl)
11486 return S_OK;
11487
11488 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
11489}
11490
11491/**
11492 * Returns @c true if this machine's USB controller reports it has a matching
11493 * filter for the given USB device and @c false otherwise.
11494 *
11495 * @note Caller must have requested machine read lock.
11496 */
11497bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11498{
11499 AutoCaller autoCaller(this);
11500 /* silently return if not ready -- this method may be called after the
11501 * direct machine session has been called */
11502 if (!autoCaller.isOk())
11503 return false;
11504
11505
11506#ifdef VBOX_WITH_USB
11507 switch (mData->mMachineState)
11508 {
11509 case MachineState_Starting:
11510 case MachineState_Restoring:
11511 case MachineState_TeleportingIn:
11512 case MachineState_Paused:
11513 case MachineState_Running:
11514 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11515 * elsewhere... */
11516 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11517 default: break;
11518 }
11519#else
11520 NOREF(aDevice);
11521 NOREF(aMaskedIfs);
11522#endif
11523 return false;
11524}
11525
11526/**
11527 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11528 */
11529HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11530 IVirtualBoxErrorInfo *aError,
11531 ULONG aMaskedIfs)
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->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11557}
11558
11559/**
11560 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11561 */
11562HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11563 IVirtualBoxErrorInfo *aError)
11564{
11565 LogFlowThisFunc(("\n"));
11566
11567 AutoCaller autoCaller(this);
11568
11569 /* This notification may happen after the machine object has been
11570 * uninitialized (the session was closed), so don't assert. */
11571 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11572
11573 ComPtr<IInternalSessionControl> directControl;
11574 {
11575 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11576 directControl = mData->mSession.mDirectControl;
11577 }
11578
11579 /* fail on notifications sent after #OnSessionEnd() is called, it is
11580 * expected by the caller */
11581 if (!directControl)
11582 return E_FAIL;
11583
11584 /* No locks should be held at this point. */
11585 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11586 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11587
11588 return directControl->OnUSBDeviceDetach(aId, aError);
11589}
11590
11591// protected methods
11592/////////////////////////////////////////////////////////////////////////////
11593
11594/**
11595 * Helper method to finalize saving the state.
11596 *
11597 * @note Must be called from under this object's lock.
11598 *
11599 * @param aRc S_OK if the snapshot has been taken successfully
11600 * @param aErrMsg human readable error message for failure
11601 *
11602 * @note Locks mParent + this objects for writing.
11603 */
11604HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
11605{
11606 LogFlowThisFuncEnter();
11607
11608 AutoCaller autoCaller(this);
11609 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11610
11611 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11612
11613 HRESULT rc = S_OK;
11614
11615 if (SUCCEEDED(aRc))
11616 {
11617 mSSData->mStateFilePath = mConsoleTaskData.mStateFilePath;
11618
11619 /* save all VM settings */
11620 rc = saveSettings(NULL);
11621 // no need to check whether VirtualBox.xml needs saving also since
11622 // we can't have a name change pending at this point
11623 }
11624 else
11625 {
11626 /* delete the saved state file (it might have been already created) */
11627 RTFileDelete(mConsoleTaskData.mStateFilePath.c_str());
11628 }
11629
11630 /* notify the progress object about operation completion */
11631 Assert(mConsoleTaskData.mProgress);
11632 if (SUCCEEDED(aRc))
11633 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11634 else
11635 {
11636 if (aErrMsg.length())
11637 mConsoleTaskData.mProgress->notifyComplete(aRc,
11638 COM_IIDOF(ISession),
11639 getComponentName(),
11640 aErrMsg.c_str());
11641 else
11642 mConsoleTaskData.mProgress->notifyComplete(aRc);
11643 }
11644
11645 /* clear out the temporary saved state data */
11646 mConsoleTaskData.mLastState = MachineState_Null;
11647 mConsoleTaskData.mStateFilePath.setNull();
11648 mConsoleTaskData.mProgress.setNull();
11649
11650 LogFlowThisFuncLeave();
11651 return rc;
11652}
11653
11654/**
11655 * Locks the attached media.
11656 *
11657 * All attached hard disks are locked for writing and DVD/floppy are locked for
11658 * reading. Parents of attached hard disks (if any) are locked for reading.
11659 *
11660 * This method also performs accessibility check of all media it locks: if some
11661 * media is inaccessible, the method will return a failure and a bunch of
11662 * extended error info objects per each inaccessible medium.
11663 *
11664 * Note that this method is atomic: if it returns a success, all media are
11665 * locked as described above; on failure no media is locked at all (all
11666 * succeeded individual locks will be undone).
11667 *
11668 * This method is intended to be called when the machine is in Starting or
11669 * Restoring state and asserts otherwise.
11670 *
11671 * The locks made by this method must be undone by calling #unlockMedia() when
11672 * no more needed.
11673 */
11674HRESULT SessionMachine::lockMedia()
11675{
11676 AutoCaller autoCaller(this);
11677 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11678
11679 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11680
11681 AssertReturn( mData->mMachineState == MachineState_Starting
11682 || mData->mMachineState == MachineState_Restoring
11683 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11684 /* bail out if trying to lock things with already set up locking */
11685 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11686
11687 MultiResult mrc(S_OK);
11688
11689 /* Collect locking information for all medium objects attached to the VM. */
11690 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11691 it != mMediaData->mAttachments.end();
11692 ++it)
11693 {
11694 MediumAttachment* pAtt = *it;
11695 DeviceType_T devType = pAtt->getType();
11696 Medium *pMedium = pAtt->getMedium();
11697
11698 MediumLockList *pMediumLockList(new MediumLockList());
11699 // There can be attachments without a medium (floppy/dvd), and thus
11700 // it's impossible to create a medium lock list. It still makes sense
11701 // to have the empty medium lock list in the map in case a medium is
11702 // attached later.
11703 if (pMedium != NULL)
11704 {
11705 MediumType_T mediumType = pMedium->getType();
11706 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
11707 || mediumType == MediumType_Shareable;
11708 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11709
11710 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11711 !fIsReadOnlyLock /* fMediumLockWrite */,
11712 NULL,
11713 *pMediumLockList);
11714 if (FAILED(mrc))
11715 {
11716 delete pMediumLockList;
11717 mData->mSession.mLockedMedia.Clear();
11718 break;
11719 }
11720 }
11721
11722 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11723 if (FAILED(rc))
11724 {
11725 mData->mSession.mLockedMedia.Clear();
11726 mrc = setError(rc,
11727 tr("Collecting locking information for all attached media failed"));
11728 break;
11729 }
11730 }
11731
11732 if (SUCCEEDED(mrc))
11733 {
11734 /* Now lock all media. If this fails, nothing is locked. */
11735 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11736 if (FAILED(rc))
11737 {
11738 mrc = setError(rc,
11739 tr("Locking of attached media failed"));
11740 }
11741 }
11742
11743 return mrc;
11744}
11745
11746/**
11747 * Undoes the locks made by by #lockMedia().
11748 */
11749void SessionMachine::unlockMedia()
11750{
11751 AutoCaller autoCaller(this);
11752 AssertComRCReturnVoid(autoCaller.rc());
11753
11754 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11755
11756 /* we may be holding important error info on the current thread;
11757 * preserve it */
11758 ErrorInfoKeeper eik;
11759
11760 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11761 AssertComRC(rc);
11762}
11763
11764/**
11765 * Helper to change the machine state (reimplementation).
11766 *
11767 * @note Locks this object for writing.
11768 */
11769HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11770{
11771 LogFlowThisFuncEnter();
11772 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11773
11774 AutoCaller autoCaller(this);
11775 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11776
11777 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11778
11779 MachineState_T oldMachineState = mData->mMachineState;
11780
11781 AssertMsgReturn(oldMachineState != aMachineState,
11782 ("oldMachineState=%s, aMachineState=%s\n",
11783 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11784 E_FAIL);
11785
11786 HRESULT rc = S_OK;
11787
11788 int stsFlags = 0;
11789 bool deleteSavedState = false;
11790
11791 /* detect some state transitions */
11792
11793 if ( ( oldMachineState == MachineState_Saved
11794 && aMachineState == MachineState_Restoring)
11795 || ( ( oldMachineState == MachineState_PoweredOff
11796 || oldMachineState == MachineState_Teleported
11797 || oldMachineState == MachineState_Aborted
11798 )
11799 && ( aMachineState == MachineState_TeleportingIn
11800 || aMachineState == MachineState_Starting
11801 )
11802 )
11803 )
11804 {
11805 /* The EMT thread is about to start */
11806
11807 /* Nothing to do here for now... */
11808
11809 /// @todo NEWMEDIA don't let mDVDDrive and other children
11810 /// change anything when in the Starting/Restoring state
11811 }
11812 else if ( ( oldMachineState == MachineState_Running
11813 || oldMachineState == MachineState_Paused
11814 || oldMachineState == MachineState_Teleporting
11815 || oldMachineState == MachineState_LiveSnapshotting
11816 || oldMachineState == MachineState_Stuck
11817 || oldMachineState == MachineState_Starting
11818 || oldMachineState == MachineState_Stopping
11819 || oldMachineState == MachineState_Saving
11820 || oldMachineState == MachineState_Restoring
11821 || oldMachineState == MachineState_TeleportingPausedVM
11822 || oldMachineState == MachineState_TeleportingIn
11823 )
11824 && ( aMachineState == MachineState_PoweredOff
11825 || aMachineState == MachineState_Saved
11826 || aMachineState == MachineState_Teleported
11827 || aMachineState == MachineState_Aborted
11828 )
11829 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11830 * snapshot */
11831 && ( mConsoleTaskData.mSnapshot.isNull()
11832 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11833 )
11834 )
11835 {
11836 /* The EMT thread has just stopped, unlock attached media. Note that as
11837 * opposed to locking that is done from Console, we do unlocking here
11838 * because the VM process may have aborted before having a chance to
11839 * properly unlock all media it locked. */
11840
11841 unlockMedia();
11842 }
11843
11844 if (oldMachineState == MachineState_Restoring)
11845 {
11846 if (aMachineState != MachineState_Saved)
11847 {
11848 /*
11849 * delete the saved state file once the machine has finished
11850 * restoring from it (note that Console sets the state from
11851 * Restoring to Saved if the VM couldn't restore successfully,
11852 * to give the user an ability to fix an error and retry --
11853 * we keep the saved state file in this case)
11854 */
11855 deleteSavedState = true;
11856 }
11857 }
11858 else if ( oldMachineState == MachineState_Saved
11859 && ( aMachineState == MachineState_PoweredOff
11860 || aMachineState == MachineState_Aborted
11861 || aMachineState == MachineState_Teleported
11862 )
11863 )
11864 {
11865 /*
11866 * delete the saved state after Console::ForgetSavedState() is called
11867 * or if the VM process (owning a direct VM session) crashed while the
11868 * VM was Saved
11869 */
11870
11871 /// @todo (dmik)
11872 // Not sure that deleting the saved state file just because of the
11873 // client death before it attempted to restore the VM is a good
11874 // thing. But when it crashes we need to go to the Aborted state
11875 // which cannot have the saved state file associated... The only
11876 // way to fix this is to make the Aborted condition not a VM state
11877 // but a bool flag: i.e., when a crash occurs, set it to true and
11878 // change the state to PoweredOff or Saved depending on the
11879 // saved state presence.
11880
11881 deleteSavedState = true;
11882 mData->mCurrentStateModified = TRUE;
11883 stsFlags |= SaveSTS_CurStateModified;
11884 }
11885
11886 if ( aMachineState == MachineState_Starting
11887 || aMachineState == MachineState_Restoring
11888 || aMachineState == MachineState_TeleportingIn
11889 )
11890 {
11891 /* set the current state modified flag to indicate that the current
11892 * state is no more identical to the state in the
11893 * current snapshot */
11894 if (!mData->mCurrentSnapshot.isNull())
11895 {
11896 mData->mCurrentStateModified = TRUE;
11897 stsFlags |= SaveSTS_CurStateModified;
11898 }
11899 }
11900
11901 if (deleteSavedState)
11902 {
11903 if (mRemoveSavedState)
11904 {
11905 Assert(!mSSData->mStateFilePath.isEmpty());
11906 RTFileDelete(mSSData->mStateFilePath.c_str());
11907 }
11908 mSSData->mStateFilePath.setNull();
11909 stsFlags |= SaveSTS_StateFilePath;
11910 }
11911
11912 /* redirect to the underlying peer machine */
11913 mPeer->setMachineState(aMachineState);
11914
11915 if ( aMachineState == MachineState_PoweredOff
11916 || aMachineState == MachineState_Teleported
11917 || aMachineState == MachineState_Aborted
11918 || aMachineState == MachineState_Saved)
11919 {
11920 /* the machine has stopped execution
11921 * (or the saved state file was adopted) */
11922 stsFlags |= SaveSTS_StateTimeStamp;
11923 }
11924
11925 if ( ( oldMachineState == MachineState_PoweredOff
11926 || oldMachineState == MachineState_Aborted
11927 || oldMachineState == MachineState_Teleported
11928 )
11929 && aMachineState == MachineState_Saved)
11930 {
11931 /* the saved state file was adopted */
11932 Assert(!mSSData->mStateFilePath.isEmpty());
11933 stsFlags |= SaveSTS_StateFilePath;
11934 }
11935
11936#ifdef VBOX_WITH_GUEST_PROPS
11937 if ( aMachineState == MachineState_PoweredOff
11938 || aMachineState == MachineState_Aborted
11939 || aMachineState == MachineState_Teleported)
11940 {
11941 /* Make sure any transient guest properties get removed from the
11942 * property store on shutdown. */
11943
11944 HWData::GuestPropertyList::iterator it;
11945 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11946 if (!fNeedsSaving)
11947 for (it = mHWData->mGuestProperties.begin();
11948 it != mHWData->mGuestProperties.end(); ++it)
11949 if (it->mFlags & guestProp::TRANSIENT)
11950 {
11951 fNeedsSaving = true;
11952 break;
11953 }
11954 if (fNeedsSaving)
11955 {
11956 mData->mCurrentStateModified = TRUE;
11957 stsFlags |= SaveSTS_CurStateModified;
11958 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11959 }
11960 }
11961#endif
11962
11963 rc = saveStateSettings(stsFlags);
11964
11965 if ( ( oldMachineState != MachineState_PoweredOff
11966 && oldMachineState != MachineState_Aborted
11967 && oldMachineState != MachineState_Teleported
11968 )
11969 && ( aMachineState == MachineState_PoweredOff
11970 || aMachineState == MachineState_Aborted
11971 || aMachineState == MachineState_Teleported
11972 )
11973 )
11974 {
11975 /* we've been shut down for any reason */
11976 /* no special action so far */
11977 }
11978
11979 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11980 LogFlowThisFuncLeave();
11981 return rc;
11982}
11983
11984/**
11985 * Sends the current machine state value to the VM process.
11986 *
11987 * @note Locks this object for reading, then calls a client process.
11988 */
11989HRESULT SessionMachine::updateMachineStateOnClient()
11990{
11991 AutoCaller autoCaller(this);
11992 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11993
11994 ComPtr<IInternalSessionControl> directControl;
11995 {
11996 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11997 AssertReturn(!!mData, E_FAIL);
11998 directControl = mData->mSession.mDirectControl;
11999
12000 /* directControl may be already set to NULL here in #OnSessionEnd()
12001 * called too early by the direct session process while there is still
12002 * some operation (like deleting the snapshot) in progress. The client
12003 * process in this case is waiting inside Session::close() for the
12004 * "end session" process object to complete, while #uninit() called by
12005 * #checkForDeath() on the Watcher thread is waiting for the pending
12006 * operation to complete. For now, we accept this inconsistent behavior
12007 * and simply do nothing here. */
12008
12009 if (mData->mSession.mState == SessionState_Unlocking)
12010 return S_OK;
12011
12012 AssertReturn(!directControl.isNull(), E_FAIL);
12013 }
12014
12015 return directControl->UpdateMachineState(mData->mMachineState);
12016}
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