VirtualBox

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

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

Always enable large page support on 64-bit hosts

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