VirtualBox

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

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

Main: make SerialPort instance data private and make it use the XML settings struct for simplicity

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

© 2023 Oracle
ContactPrivacy policyTerms of Use