VirtualBox

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

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

VRDE: removed VBOX_WITH_VRDP from source code, also some obsolete code removed.

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