VirtualBox

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

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

build fix

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