VirtualBox

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

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

Main: prevent attaching MultiAttach/Readonly media to pre-4.0 machines for backwards settings compatibility

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

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