VirtualBox

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

最後變更 在這個檔案從33078是 33078,由 vboxsync 提交於 14 年 前

Main: change per-machine media registries so that removeable media files (ISO, RAW) can appear in more than one registry; fix saving registry with removeable media (mount at runtime), hopefully

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

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