VirtualBox

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

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

Main: make saved state paths relative to machines again (trunk regression)

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

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