VirtualBox

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

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

Statistics for shared pages

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