VirtualBox

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

Last change on this file since 31296 was 31296, checked in by vboxsync, 15 years ago

Main: cleanup host drives management: do not return different IMedium objects every time Host::GetDVDDrives() or HOst::GetFloppyDrives() are called; refresh the internal list only when a public API is called, but not for every single internal use such as loading machine settings file; fix code duplication

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