VirtualBox

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

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

Main: change VirtualBox::createMachine() to accept arbitrary paths for the XML settings file; remove the override parameter

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

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