VirtualBox

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

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

Machine::QueryLogFilename: Must set aName in the case where the file does not exist.

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

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