VirtualBox

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

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

Main: Unset the bootable flag on other controllers automatically instead of throwing an error

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 384.5 KB
Line 
1/* $Id: MachineImpl.cpp 34057 2010-11-13 18:41:49Z 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 bool fBootable = true;
5139 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5140 it != mStorageControllers->end();
5141 ++it)
5142 {
5143 if ((*it)->getStorageBus() == aConnectionType)
5144 {
5145 ULONG ulCurInst = (*it)->getInstance();
5146
5147 if (ulCurInst >= ulInstance)
5148 ulInstance = ulCurInst + 1;
5149
5150 /* Only one controller of each type can be marked as bootable. */
5151 if ((*it)->getBootable())
5152 fBootable = false;
5153 }
5154 }
5155
5156 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
5157 if (FAILED(rc)) return rc;
5158
5159 setModified(IsModified_Storage);
5160 mStorageControllers.backup();
5161 mStorageControllers->push_back(ctrl);
5162
5163 ctrl.queryInterfaceTo(controller);
5164
5165 /* inform the direct session if any */
5166 alock.leave();
5167 onStorageControllerChange();
5168
5169 return S_OK;
5170}
5171
5172STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
5173 IStorageController **aStorageController)
5174{
5175 CheckComArgStrNotEmptyOrNull(aName);
5176
5177 AutoCaller autoCaller(this);
5178 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5179
5180 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5181
5182 ComObjPtr<StorageController> ctrl;
5183
5184 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5185 if (SUCCEEDED(rc))
5186 ctrl.queryInterfaceTo(aStorageController);
5187
5188 return rc;
5189}
5190
5191STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
5192 IStorageController **aStorageController)
5193{
5194 AutoCaller autoCaller(this);
5195 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5196
5197 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5198
5199 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5200 it != mStorageControllers->end();
5201 ++it)
5202 {
5203 if ((*it)->getInstance() == aInstance)
5204 {
5205 (*it).queryInterfaceTo(aStorageController);
5206 return S_OK;
5207 }
5208 }
5209
5210 return setError(VBOX_E_OBJECT_NOT_FOUND,
5211 tr("Could not find a storage controller with instance number '%lu'"),
5212 aInstance);
5213}
5214
5215STDMETHODIMP Machine::SetStorageControllerBootable(IN_BSTR aName, BOOL fBootable)
5216{
5217 AutoCaller autoCaller(this);
5218 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5219
5220 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5221
5222 HRESULT rc = checkStateDependency(MutableStateDep);
5223 if (FAILED(rc)) return rc;
5224
5225 ComObjPtr<StorageController> ctrl;
5226
5227 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5228 if (SUCCEEDED(rc))
5229 {
5230 /* Ensure that only one controller of each type is marked as bootable. */
5231 if (fBootable == TRUE)
5232 {
5233 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5234 it != mStorageControllers->end();
5235 ++it)
5236 {
5237 ComObjPtr<StorageController> aCtrl = (*it);
5238
5239 if ( (aCtrl->getName() != Utf8Str(aName))
5240 && aCtrl->getBootable() == TRUE
5241 && aCtrl->getStorageBus() == ctrl->getStorageBus()
5242 && aCtrl->getControllerType() == ctrl->getControllerType())
5243 {
5244 aCtrl->setBootable(FALSE);
5245 break;
5246 }
5247 }
5248 }
5249
5250 if (SUCCEEDED(rc))
5251 {
5252 ctrl->setBootable(fBootable);
5253 setModified(IsModified_Storage);
5254 }
5255 }
5256
5257 if (SUCCEEDED(rc))
5258 {
5259 /* inform the direct session if any */
5260 alock.leave();
5261 onStorageControllerChange();
5262 }
5263
5264 return rc;
5265}
5266
5267STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5268{
5269 CheckComArgStrNotEmptyOrNull(aName);
5270
5271 AutoCaller autoCaller(this);
5272 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5273
5274 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5275
5276 HRESULT rc = checkStateDependency(MutableStateDep);
5277 if (FAILED(rc)) return rc;
5278
5279 ComObjPtr<StorageController> ctrl;
5280 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5281 if (FAILED(rc)) return rc;
5282
5283 /* We can remove the controller only if there is no device attached. */
5284 /* check if the device slot is already busy */
5285 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5286 it != mMediaData->mAttachments.end();
5287 ++it)
5288 {
5289 if ((*it)->getControllerName() == aName)
5290 return setError(VBOX_E_OBJECT_IN_USE,
5291 tr("Storage controller named '%ls' has still devices attached"),
5292 aName);
5293 }
5294
5295 /* We can remove it now. */
5296 setModified(IsModified_Storage);
5297 mStorageControllers.backup();
5298
5299 ctrl->unshare();
5300
5301 mStorageControllers->remove(ctrl);
5302
5303 /* inform the direct session if any */
5304 alock.leave();
5305 onStorageControllerChange();
5306
5307 return S_OK;
5308}
5309
5310STDMETHODIMP Machine::QuerySavedGuestSize(ULONG uScreenId, ULONG *puWidth, ULONG *puHeight)
5311{
5312 LogFlowThisFunc(("\n"));
5313
5314 CheckComArgNotNull(puWidth);
5315 CheckComArgNotNull(puHeight);
5316
5317 uint32_t u32Width = 0;
5318 uint32_t u32Height = 0;
5319
5320 int vrc = readSavedGuestSize(mSSData->mStateFilePath, uScreenId, &u32Width, &u32Height);
5321 if (RT_FAILURE(vrc))
5322 return setError(VBOX_E_IPRT_ERROR,
5323 tr("Saved guest size is not available (%Rrc)"),
5324 vrc);
5325
5326 *puWidth = u32Width;
5327 *puHeight = u32Height;
5328
5329 return S_OK;
5330}
5331
5332STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5333{
5334 LogFlowThisFunc(("\n"));
5335
5336 CheckComArgNotNull(aSize);
5337 CheckComArgNotNull(aWidth);
5338 CheckComArgNotNull(aHeight);
5339
5340 if (aScreenId != 0)
5341 return E_NOTIMPL;
5342
5343 AutoCaller autoCaller(this);
5344 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5345
5346 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5347
5348 uint8_t *pu8Data = NULL;
5349 uint32_t cbData = 0;
5350 uint32_t u32Width = 0;
5351 uint32_t u32Height = 0;
5352
5353 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5354
5355 if (RT_FAILURE(vrc))
5356 return setError(VBOX_E_IPRT_ERROR,
5357 tr("Saved screenshot data is not available (%Rrc)"),
5358 vrc);
5359
5360 *aSize = cbData;
5361 *aWidth = u32Width;
5362 *aHeight = u32Height;
5363
5364 freeSavedDisplayScreenshot(pu8Data);
5365
5366 return S_OK;
5367}
5368
5369STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5370{
5371 LogFlowThisFunc(("\n"));
5372
5373 CheckComArgNotNull(aWidth);
5374 CheckComArgNotNull(aHeight);
5375 CheckComArgOutSafeArrayPointerValid(aData);
5376
5377 if (aScreenId != 0)
5378 return E_NOTIMPL;
5379
5380 AutoCaller autoCaller(this);
5381 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5382
5383 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5384
5385 uint8_t *pu8Data = NULL;
5386 uint32_t cbData = 0;
5387 uint32_t u32Width = 0;
5388 uint32_t u32Height = 0;
5389
5390 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5391
5392 if (RT_FAILURE(vrc))
5393 return setError(VBOX_E_IPRT_ERROR,
5394 tr("Saved screenshot data is not available (%Rrc)"),
5395 vrc);
5396
5397 *aWidth = u32Width;
5398 *aHeight = u32Height;
5399
5400 com::SafeArray<BYTE> bitmap(cbData);
5401 /* Convert pixels to format expected by the API caller. */
5402 if (aBGR)
5403 {
5404 /* [0] B, [1] G, [2] R, [3] A. */
5405 for (unsigned i = 0; i < cbData; i += 4)
5406 {
5407 bitmap[i] = pu8Data[i];
5408 bitmap[i + 1] = pu8Data[i + 1];
5409 bitmap[i + 2] = pu8Data[i + 2];
5410 bitmap[i + 3] = 0xff;
5411 }
5412 }
5413 else
5414 {
5415 /* [0] R, [1] G, [2] B, [3] A. */
5416 for (unsigned i = 0; i < cbData; i += 4)
5417 {
5418 bitmap[i] = pu8Data[i + 2];
5419 bitmap[i + 1] = pu8Data[i + 1];
5420 bitmap[i + 2] = pu8Data[i];
5421 bitmap[i + 3] = 0xff;
5422 }
5423 }
5424 bitmap.detachTo(ComSafeArrayOutArg(aData));
5425
5426 freeSavedDisplayScreenshot(pu8Data);
5427
5428 return S_OK;
5429}
5430
5431
5432STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5433{
5434 LogFlowThisFunc(("\n"));
5435
5436 CheckComArgNotNull(aWidth);
5437 CheckComArgNotNull(aHeight);
5438 CheckComArgOutSafeArrayPointerValid(aData);
5439
5440 if (aScreenId != 0)
5441 return E_NOTIMPL;
5442
5443 AutoCaller autoCaller(this);
5444 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5445
5446 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5447
5448 uint8_t *pu8Data = NULL;
5449 uint32_t cbData = 0;
5450 uint32_t u32Width = 0;
5451 uint32_t u32Height = 0;
5452
5453 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5454
5455 if (RT_FAILURE(vrc))
5456 return setError(VBOX_E_IPRT_ERROR,
5457 tr("Saved screenshot data is not available (%Rrc)"),
5458 vrc);
5459
5460 *aWidth = u32Width;
5461 *aHeight = u32Height;
5462
5463 uint8_t *pu8PNG = NULL;
5464 uint32_t cbPNG = 0;
5465 uint32_t cxPNG = 0;
5466 uint32_t cyPNG = 0;
5467
5468 DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
5469
5470 com::SafeArray<BYTE> screenData(cbPNG);
5471 screenData.initFrom(pu8PNG, cbPNG);
5472 RTMemFree(pu8PNG);
5473
5474 screenData.detachTo(ComSafeArrayOutArg(aData));
5475
5476 freeSavedDisplayScreenshot(pu8Data);
5477
5478 return S_OK;
5479}
5480
5481STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5482{
5483 LogFlowThisFunc(("\n"));
5484
5485 CheckComArgNotNull(aSize);
5486 CheckComArgNotNull(aWidth);
5487 CheckComArgNotNull(aHeight);
5488
5489 if (aScreenId != 0)
5490 return E_NOTIMPL;
5491
5492 AutoCaller autoCaller(this);
5493 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5494
5495 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5496
5497 uint8_t *pu8Data = NULL;
5498 uint32_t cbData = 0;
5499 uint32_t u32Width = 0;
5500 uint32_t u32Height = 0;
5501
5502 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5503
5504 if (RT_FAILURE(vrc))
5505 return setError(VBOX_E_IPRT_ERROR,
5506 tr("Saved screenshot data is not available (%Rrc)"),
5507 vrc);
5508
5509 *aSize = cbData;
5510 *aWidth = u32Width;
5511 *aHeight = u32Height;
5512
5513 freeSavedDisplayScreenshot(pu8Data);
5514
5515 return S_OK;
5516}
5517
5518STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5519{
5520 LogFlowThisFunc(("\n"));
5521
5522 CheckComArgNotNull(aWidth);
5523 CheckComArgNotNull(aHeight);
5524 CheckComArgOutSafeArrayPointerValid(aData);
5525
5526 if (aScreenId != 0)
5527 return E_NOTIMPL;
5528
5529 AutoCaller autoCaller(this);
5530 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5531
5532 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5533
5534 uint8_t *pu8Data = NULL;
5535 uint32_t cbData = 0;
5536 uint32_t u32Width = 0;
5537 uint32_t u32Height = 0;
5538
5539 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5540
5541 if (RT_FAILURE(vrc))
5542 return setError(VBOX_E_IPRT_ERROR,
5543 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
5544 vrc);
5545
5546 *aWidth = u32Width;
5547 *aHeight = u32Height;
5548
5549 com::SafeArray<BYTE> png(cbData);
5550 png.initFrom(pu8Data, cbData);
5551 png.detachTo(ComSafeArrayOutArg(aData));
5552
5553 freeSavedDisplayScreenshot(pu8Data);
5554
5555 return S_OK;
5556}
5557
5558STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5559{
5560 HRESULT rc = S_OK;
5561 LogFlowThisFunc(("\n"));
5562
5563 AutoCaller autoCaller(this);
5564 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5565
5566 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5567
5568 if (!mHWData->mCPUHotPlugEnabled)
5569 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5570
5571 if (aCpu >= mHWData->mCPUCount)
5572 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5573
5574 if (mHWData->mCPUAttached[aCpu])
5575 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5576
5577 alock.release();
5578 rc = onCPUChange(aCpu, false);
5579 alock.acquire();
5580 if (FAILED(rc)) return rc;
5581
5582 setModified(IsModified_MachineData);
5583 mHWData.backup();
5584 mHWData->mCPUAttached[aCpu] = true;
5585
5586 /* Save settings if online */
5587 if (Global::IsOnline(mData->mMachineState))
5588 saveSettings(NULL);
5589
5590 return S_OK;
5591}
5592
5593STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5594{
5595 HRESULT rc = S_OK;
5596 LogFlowThisFunc(("\n"));
5597
5598 AutoCaller autoCaller(this);
5599 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5600
5601 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5602
5603 if (!mHWData->mCPUHotPlugEnabled)
5604 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5605
5606 if (aCpu >= SchemaDefs::MaxCPUCount)
5607 return setError(E_INVALIDARG,
5608 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5609 SchemaDefs::MaxCPUCount);
5610
5611 if (!mHWData->mCPUAttached[aCpu])
5612 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5613
5614 /* CPU 0 can't be detached */
5615 if (aCpu == 0)
5616 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5617
5618 alock.release();
5619 rc = onCPUChange(aCpu, true);
5620 alock.acquire();
5621 if (FAILED(rc)) return rc;
5622
5623 setModified(IsModified_MachineData);
5624 mHWData.backup();
5625 mHWData->mCPUAttached[aCpu] = false;
5626
5627 /* Save settings if online */
5628 if (Global::IsOnline(mData->mMachineState))
5629 saveSettings(NULL);
5630
5631 return S_OK;
5632}
5633
5634STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5635{
5636 LogFlowThisFunc(("\n"));
5637
5638 CheckComArgNotNull(aCpuAttached);
5639
5640 *aCpuAttached = false;
5641
5642 AutoCaller autoCaller(this);
5643 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5644
5645 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5646
5647 /* If hotplug is enabled the CPU is always enabled. */
5648 if (!mHWData->mCPUHotPlugEnabled)
5649 {
5650 if (aCpu < mHWData->mCPUCount)
5651 *aCpuAttached = true;
5652 }
5653 else
5654 {
5655 if (aCpu < SchemaDefs::MaxCPUCount)
5656 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5657 }
5658
5659 return S_OK;
5660}
5661
5662STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5663{
5664 CheckComArgOutPointerValid(aName);
5665
5666 AutoCaller autoCaller(this);
5667 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5668
5669 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5670
5671 Utf8Str log = queryLogFilename(aIdx);
5672 if (!RTFileExists(log.c_str()))
5673 log.setNull();
5674 log.cloneTo(aName);
5675
5676 return S_OK;
5677}
5678
5679STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
5680{
5681 LogFlowThisFunc(("\n"));
5682 CheckComArgOutSafeArrayPointerValid(aData);
5683 if (aSize < 0)
5684 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
5685
5686 AutoCaller autoCaller(this);
5687 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5688
5689 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5690
5691 HRESULT rc = S_OK;
5692 Utf8Str log = queryLogFilename(aIdx);
5693
5694 /* do not unnecessarily hold the lock while doing something which does
5695 * not need the lock and potentially takes a long time. */
5696 alock.release();
5697
5698 /* Limit the chunk size to 32K for now, as that gives better performance
5699 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5700 * One byte expands to approx. 25 bytes of breathtaking XML. */
5701 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5702 com::SafeArray<BYTE> logData(cbData);
5703
5704 RTFILE LogFile;
5705 int vrc = RTFileOpen(&LogFile, log.c_str(),
5706 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5707 if (RT_SUCCESS(vrc))
5708 {
5709 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5710 if (RT_SUCCESS(vrc))
5711 logData.resize(cbData);
5712 else
5713 rc = setError(VBOX_E_IPRT_ERROR,
5714 tr("Could not read log file '%s' (%Rrc)"),
5715 log.c_str(), vrc);
5716 RTFileClose(LogFile);
5717 }
5718 else
5719 rc = setError(VBOX_E_IPRT_ERROR,
5720 tr("Could not open log file '%s' (%Rrc)"),
5721 log.c_str(), vrc);
5722
5723 if (FAILED(rc))
5724 logData.resize(0);
5725 logData.detachTo(ComSafeArrayOutArg(aData));
5726
5727 return rc;
5728}
5729
5730
5731// public methods for internal purposes
5732/////////////////////////////////////////////////////////////////////////////
5733
5734/**
5735 * Adds the given IsModified_* flag to the dirty flags of the machine.
5736 * This must be called either during loadSettings or under the machine write lock.
5737 * @param fl
5738 */
5739void Machine::setModified(uint32_t fl)
5740{
5741 mData->flModifications |= fl;
5742}
5743
5744/**
5745 * Saves the registry entry of this machine to the given configuration node.
5746 *
5747 * @param aEntryNode Node to save the registry entry to.
5748 *
5749 * @note locks this object for reading.
5750 */
5751HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5752{
5753 AutoLimitedCaller autoCaller(this);
5754 AssertComRCReturnRC(autoCaller.rc());
5755
5756 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5757
5758 data.uuid = mData->mUuid;
5759 data.strSettingsFile = mData->m_strConfigFile;
5760
5761 return S_OK;
5762}
5763
5764/**
5765 * Calculates the absolute path of the given path taking the directory of the
5766 * machine settings file as the current directory.
5767 *
5768 * @param aPath Path to calculate the absolute path for.
5769 * @param aResult Where to put the result (used only on success, can be the
5770 * same Utf8Str instance as passed in @a aPath).
5771 * @return IPRT result.
5772 *
5773 * @note Locks this object for reading.
5774 */
5775int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5776{
5777 AutoCaller autoCaller(this);
5778 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5779
5780 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5781
5782 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5783
5784 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5785
5786 strSettingsDir.stripFilename();
5787 char folder[RTPATH_MAX];
5788 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5789 if (RT_SUCCESS(vrc))
5790 aResult = folder;
5791
5792 return vrc;
5793}
5794
5795/**
5796 * Copies strSource to strTarget, making it relative to the machine folder
5797 * if it is a subdirectory thereof, or simply copying it otherwise.
5798 *
5799 * @param strSource Path to evaluate and copy.
5800 * @param strTarget Buffer to receive target path.
5801 *
5802 * @note Locks this object for reading.
5803 */
5804void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5805 Utf8Str &strTarget)
5806{
5807 AutoCaller autoCaller(this);
5808 AssertComRCReturn(autoCaller.rc(), (void)0);
5809
5810 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5811
5812 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5813 // use strTarget as a temporary buffer to hold the machine settings dir
5814 strTarget = mData->m_strConfigFileFull;
5815 strTarget.stripFilename();
5816 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5817 // is relative: then append what's left
5818 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
5819 else
5820 // is not relative: then overwrite
5821 strTarget = strSource;
5822}
5823
5824/**
5825 * Returns the full path to the machine's log folder in the
5826 * \a aLogFolder argument.
5827 */
5828void Machine::getLogFolder(Utf8Str &aLogFolder)
5829{
5830 AutoCaller autoCaller(this);
5831 AssertComRCReturnVoid(autoCaller.rc());
5832
5833 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5834
5835 Utf8Str settingsDir;
5836 if (isInOwnDir(&settingsDir))
5837 /* Log folder is <Machines>/<VM_Name>/Logs */
5838 aLogFolder = settingsDir;
5839 else
5840 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5841 calculateFullPath(mUserData->s.strSnapshotFolder, aLogFolder);
5842
5843 aLogFolder.append(RTPATH_DELIMITER);
5844 aLogFolder.append("Logs");
5845}
5846
5847/**
5848 * Returns the full path to the machine's log file for an given index.
5849 */
5850Utf8Str Machine::queryLogFilename(ULONG idx)
5851{
5852 Utf8Str logFolder;
5853 getLogFolder(logFolder);
5854 Assert(logFolder.length());
5855 Utf8Str log;
5856 if (idx == 0)
5857 log = Utf8StrFmt("%s%cVBox.log",
5858 logFolder.c_str(), RTPATH_DELIMITER);
5859 else
5860 log = Utf8StrFmt("%s%cVBox.log.%d",
5861 logFolder.c_str(), RTPATH_DELIMITER, idx);
5862 return log;
5863}
5864
5865/**
5866 * @note Locks this object for writing, calls the client process
5867 * (inside the lock).
5868 */
5869HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5870 IN_BSTR aType,
5871 IN_BSTR aEnvironment,
5872 ProgressProxy *aProgress)
5873{
5874 LogFlowThisFuncEnter();
5875
5876 AssertReturn(aControl, E_FAIL);
5877 AssertReturn(aProgress, E_FAIL);
5878
5879 AutoCaller autoCaller(this);
5880 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5881
5882 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5883
5884 if (!mData->mRegistered)
5885 return setError(E_UNEXPECTED,
5886 tr("The machine '%s' is not registered"),
5887 mUserData->s.strName.c_str());
5888
5889 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5890
5891 if ( mData->mSession.mState == SessionState_Locked
5892 || mData->mSession.mState == SessionState_Spawning
5893 || mData->mSession.mState == SessionState_Unlocking)
5894 return setError(VBOX_E_INVALID_OBJECT_STATE,
5895 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
5896 mUserData->s.strName.c_str());
5897
5898 /* may not be busy */
5899 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5900
5901 /* get the path to the executable */
5902 char szPath[RTPATH_MAX];
5903 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5904 size_t sz = strlen(szPath);
5905 szPath[sz++] = RTPATH_DELIMITER;
5906 szPath[sz] = 0;
5907 char *cmd = szPath + sz;
5908 sz = RTPATH_MAX - sz;
5909
5910 int vrc = VINF_SUCCESS;
5911 RTPROCESS pid = NIL_RTPROCESS;
5912
5913 RTENV env = RTENV_DEFAULT;
5914
5915 if (aEnvironment != NULL && *aEnvironment)
5916 {
5917 char *newEnvStr = NULL;
5918
5919 do
5920 {
5921 /* clone the current environment */
5922 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5923 AssertRCBreakStmt(vrc2, vrc = vrc2);
5924
5925 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5926 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5927
5928 /* put new variables to the environment
5929 * (ignore empty variable names here since RTEnv API
5930 * intentionally doesn't do that) */
5931 char *var = newEnvStr;
5932 for (char *p = newEnvStr; *p; ++p)
5933 {
5934 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5935 {
5936 *p = '\0';
5937 if (*var)
5938 {
5939 char *val = strchr(var, '=');
5940 if (val)
5941 {
5942 *val++ = '\0';
5943 vrc2 = RTEnvSetEx(env, var, val);
5944 }
5945 else
5946 vrc2 = RTEnvUnsetEx(env, var);
5947 if (RT_FAILURE(vrc2))
5948 break;
5949 }
5950 var = p + 1;
5951 }
5952 }
5953 if (RT_SUCCESS(vrc2) && *var)
5954 vrc2 = RTEnvPutEx(env, var);
5955
5956 AssertRCBreakStmt(vrc2, vrc = vrc2);
5957 }
5958 while (0);
5959
5960 if (newEnvStr != NULL)
5961 RTStrFree(newEnvStr);
5962 }
5963
5964 Utf8Str strType(aType);
5965
5966 /* Qt is default */
5967#ifdef VBOX_WITH_QTGUI
5968 if (strType == "gui" || strType == "GUI/Qt")
5969 {
5970# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5971 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5972# else
5973 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5974# endif
5975 Assert(sz >= sizeof(VirtualBox_exe));
5976 strcpy(cmd, VirtualBox_exe);
5977
5978 Utf8Str idStr = mData->mUuid.toString();
5979 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5980 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5981 }
5982#else /* !VBOX_WITH_QTGUI */
5983 if (0)
5984 ;
5985#endif /* VBOX_WITH_QTGUI */
5986
5987 else
5988
5989#ifdef VBOX_WITH_VBOXSDL
5990 if (strType == "sdl" || strType == "GUI/SDL")
5991 {
5992 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5993 Assert(sz >= sizeof(VBoxSDL_exe));
5994 strcpy(cmd, VBoxSDL_exe);
5995
5996 Utf8Str idStr = mData->mUuid.toString();
5997 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
5998 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5999 }
6000#else /* !VBOX_WITH_VBOXSDL */
6001 if (0)
6002 ;
6003#endif /* !VBOX_WITH_VBOXSDL */
6004
6005 else
6006
6007#ifdef VBOX_WITH_HEADLESS
6008 if ( strType == "headless"
6009 || strType == "capture"
6010 || strType == "vrdp" /* Deprecated. Same as headless. */
6011 )
6012 {
6013 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6014 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6015 * and a VM works even if the server has not been installed.
6016 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6017 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6018 * differently in 4.0 and 3.x.
6019 */
6020 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6021 Assert(sz >= sizeof(VBoxHeadless_exe));
6022 strcpy(cmd, VBoxHeadless_exe);
6023
6024 Utf8Str idStr = mData->mUuid.toString();
6025 /* Leave space for "--capture" arg. */
6026 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0, 0 };
6027 if (strType == "capture")
6028 {
6029 unsigned pos = RT_ELEMENTS(args) - 2;
6030 args[pos] = "--capture";
6031 }
6032 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6033 }
6034#else /* !VBOX_WITH_HEADLESS */
6035 if (0)
6036 ;
6037#endif /* !VBOX_WITH_HEADLESS */
6038 else
6039 {
6040 RTEnvDestroy(env);
6041 return setError(E_INVALIDARG,
6042 tr("Invalid session type: '%s'"),
6043 strType.c_str());
6044 }
6045
6046 RTEnvDestroy(env);
6047
6048 if (RT_FAILURE(vrc))
6049 return setError(VBOX_E_IPRT_ERROR,
6050 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6051 mUserData->s.strName.c_str(), vrc);
6052
6053 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6054
6055 /*
6056 * Note that we don't leave the lock here before calling the client,
6057 * because it doesn't need to call us back if called with a NULL argument.
6058 * Leaving the lock here is dangerous because we didn't prepare the
6059 * launch data yet, but the client we've just started may happen to be
6060 * too fast and call openSession() that will fail (because of PID, etc.),
6061 * so that the Machine will never get out of the Spawning session state.
6062 */
6063
6064 /* inform the session that it will be a remote one */
6065 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6066 HRESULT rc = aControl->AssignMachine(NULL);
6067 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6068
6069 if (FAILED(rc))
6070 {
6071 /* restore the session state */
6072 mData->mSession.mState = SessionState_Unlocked;
6073 /* The failure may occur w/o any error info (from RPC), so provide one */
6074 return setError(VBOX_E_VM_ERROR,
6075 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6076 }
6077
6078 /* attach launch data to the machine */
6079 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6080 mData->mSession.mRemoteControls.push_back (aControl);
6081 mData->mSession.mProgress = aProgress;
6082 mData->mSession.mPid = pid;
6083 mData->mSession.mState = SessionState_Spawning;
6084 mData->mSession.mType = strType;
6085
6086 LogFlowThisFuncLeave();
6087 return S_OK;
6088}
6089
6090/**
6091 * Returns @c true if the given machine has an open direct session and returns
6092 * the session machine instance and additional session data (on some platforms)
6093 * if so.
6094 *
6095 * Note that when the method returns @c false, the arguments remain unchanged.
6096 *
6097 * @param aMachine Session machine object.
6098 * @param aControl Direct session control object (optional).
6099 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6100 *
6101 * @note locks this object for reading.
6102 */
6103#if defined(RT_OS_WINDOWS)
6104bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6105 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6106 HANDLE *aIPCSem /*= NULL*/,
6107 bool aAllowClosing /*= false*/)
6108#elif defined(RT_OS_OS2)
6109bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6110 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6111 HMTX *aIPCSem /*= NULL*/,
6112 bool aAllowClosing /*= false*/)
6113#else
6114bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6115 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6116 bool aAllowClosing /*= false*/)
6117#endif
6118{
6119 AutoLimitedCaller autoCaller(this);
6120 AssertComRCReturn(autoCaller.rc(), false);
6121
6122 /* just return false for inaccessible machines */
6123 if (autoCaller.state() != Ready)
6124 return false;
6125
6126 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6127
6128 if ( mData->mSession.mState == SessionState_Locked
6129 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6130 )
6131 {
6132 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6133
6134 aMachine = mData->mSession.mMachine;
6135
6136 if (aControl != NULL)
6137 *aControl = mData->mSession.mDirectControl;
6138
6139#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6140 /* Additional session data */
6141 if (aIPCSem != NULL)
6142 *aIPCSem = aMachine->mIPCSem;
6143#endif
6144 return true;
6145 }
6146
6147 return false;
6148}
6149
6150/**
6151 * Returns @c true if the given machine has an spawning direct session and
6152 * returns and additional session data (on some platforms) if so.
6153 *
6154 * Note that when the method returns @c false, the arguments remain unchanged.
6155 *
6156 * @param aPID PID of the spawned direct session process.
6157 *
6158 * @note locks this object for reading.
6159 */
6160#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6161bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6162#else
6163bool Machine::isSessionSpawning()
6164#endif
6165{
6166 AutoLimitedCaller autoCaller(this);
6167 AssertComRCReturn(autoCaller.rc(), false);
6168
6169 /* just return false for inaccessible machines */
6170 if (autoCaller.state() != Ready)
6171 return false;
6172
6173 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6174
6175 if (mData->mSession.mState == SessionState_Spawning)
6176 {
6177#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6178 /* Additional session data */
6179 if (aPID != NULL)
6180 {
6181 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6182 *aPID = mData->mSession.mPid;
6183 }
6184#endif
6185 return true;
6186 }
6187
6188 return false;
6189}
6190
6191/**
6192 * Called from the client watcher thread to check for unexpected client process
6193 * death during Session_Spawning state (e.g. before it successfully opened a
6194 * direct session).
6195 *
6196 * On Win32 and on OS/2, this method is called only when we've got the
6197 * direct client's process termination notification, so it always returns @c
6198 * true.
6199 *
6200 * On other platforms, this method returns @c true if the client process is
6201 * terminated and @c false if it's still alive.
6202 *
6203 * @note Locks this object for writing.
6204 */
6205bool Machine::checkForSpawnFailure()
6206{
6207 AutoCaller autoCaller(this);
6208 if (!autoCaller.isOk())
6209 {
6210 /* nothing to do */
6211 LogFlowThisFunc(("Already uninitialized!\n"));
6212 return true;
6213 }
6214
6215 /* VirtualBox::addProcessToReap() needs a write lock */
6216 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6217
6218 if (mData->mSession.mState != SessionState_Spawning)
6219 {
6220 /* nothing to do */
6221 LogFlowThisFunc(("Not spawning any more!\n"));
6222 return true;
6223 }
6224
6225 HRESULT rc = S_OK;
6226
6227#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6228
6229 /* the process was already unexpectedly terminated, we just need to set an
6230 * error and finalize session spawning */
6231 rc = setError(E_FAIL,
6232 tr("The virtual machine '%ls' has terminated unexpectedly during startup"),
6233 getName().c_str());
6234#else
6235
6236 /* PID not yet initialized, skip check. */
6237 if (mData->mSession.mPid == NIL_RTPROCESS)
6238 return false;
6239
6240 RTPROCSTATUS status;
6241 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6242 &status);
6243
6244 if (vrc != VERR_PROCESS_RUNNING)
6245 {
6246 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6247 rc = setError(E_FAIL,
6248 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6249 getName().c_str(), status.iStatus);
6250 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6251 rc = setError(E_FAIL,
6252 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6253 getName().c_str(), status.iStatus);
6254 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6255 rc = setError(E_FAIL,
6256 tr("The virtual machine '%s' has terminated abnormally"),
6257 getName().c_str(), status.iStatus);
6258 else
6259 rc = setError(E_FAIL,
6260 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6261 getName().c_str(), rc);
6262 }
6263
6264#endif
6265
6266 if (FAILED(rc))
6267 {
6268 /* Close the remote session, remove the remote control from the list
6269 * and reset session state to Closed (@note keep the code in sync with
6270 * the relevant part in checkForSpawnFailure()). */
6271
6272 Assert(mData->mSession.mRemoteControls.size() == 1);
6273 if (mData->mSession.mRemoteControls.size() == 1)
6274 {
6275 ErrorInfoKeeper eik;
6276 mData->mSession.mRemoteControls.front()->Uninitialize();
6277 }
6278
6279 mData->mSession.mRemoteControls.clear();
6280 mData->mSession.mState = SessionState_Unlocked;
6281
6282 /* finalize the progress after setting the state */
6283 if (!mData->mSession.mProgress.isNull())
6284 {
6285 mData->mSession.mProgress->notifyComplete(rc);
6286 mData->mSession.mProgress.setNull();
6287 }
6288
6289 mParent->addProcessToReap(mData->mSession.mPid);
6290 mData->mSession.mPid = NIL_RTPROCESS;
6291
6292 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6293 return true;
6294 }
6295
6296 return false;
6297}
6298
6299/**
6300 * Checks whether the machine can be registered. If so, commits and saves
6301 * all settings.
6302 *
6303 * @note Must be called from mParent's write lock. Locks this object and
6304 * children for writing.
6305 */
6306HRESULT Machine::prepareRegister()
6307{
6308 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6309
6310 AutoLimitedCaller autoCaller(this);
6311 AssertComRCReturnRC(autoCaller.rc());
6312
6313 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6314
6315 /* wait for state dependents to drop to zero */
6316 ensureNoStateDependencies();
6317
6318 if (!mData->mAccessible)
6319 return setError(VBOX_E_INVALID_OBJECT_STATE,
6320 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6321 mUserData->s.strName.c_str(),
6322 mData->mUuid.toString().c_str());
6323
6324 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6325
6326 if (mData->mRegistered)
6327 return setError(VBOX_E_INVALID_OBJECT_STATE,
6328 tr("The machine '%s' with UUID {%s} is already registered"),
6329 mUserData->s.strName.c_str(),
6330 mData->mUuid.toString().c_str());
6331
6332 HRESULT rc = S_OK;
6333
6334 // Ensure the settings are saved. If we are going to be registered and
6335 // no config file exists yet, create it by calling saveSettings() too.
6336 if ( (mData->flModifications)
6337 || (!mData->pMachineConfigFile->fileExists())
6338 )
6339 {
6340 rc = saveSettings(NULL);
6341 // no need to check whether VirtualBox.xml needs saving too since
6342 // we can't have a machine XML file rename pending
6343 if (FAILED(rc)) return rc;
6344 }
6345
6346 /* more config checking goes here */
6347
6348 if (SUCCEEDED(rc))
6349 {
6350 /* we may have had implicit modifications we want to fix on success */
6351 commit();
6352
6353 mData->mRegistered = true;
6354 }
6355 else
6356 {
6357 /* we may have had implicit modifications we want to cancel on failure*/
6358 rollback(false /* aNotify */);
6359 }
6360
6361 return rc;
6362}
6363
6364/**
6365 * Increases the number of objects dependent on the machine state or on the
6366 * registered state. Guarantees that these two states will not change at least
6367 * until #releaseStateDependency() is called.
6368 *
6369 * Depending on the @a aDepType value, additional state checks may be made.
6370 * These checks will set extended error info on failure. See
6371 * #checkStateDependency() for more info.
6372 *
6373 * If this method returns a failure, the dependency is not added and the caller
6374 * is not allowed to rely on any particular machine state or registration state
6375 * value and may return the failed result code to the upper level.
6376 *
6377 * @param aDepType Dependency type to add.
6378 * @param aState Current machine state (NULL if not interested).
6379 * @param aRegistered Current registered state (NULL if not interested).
6380 *
6381 * @note Locks this object for writing.
6382 */
6383HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6384 MachineState_T *aState /* = NULL */,
6385 BOOL *aRegistered /* = NULL */)
6386{
6387 AutoCaller autoCaller(this);
6388 AssertComRCReturnRC(autoCaller.rc());
6389
6390 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6391
6392 HRESULT rc = checkStateDependency(aDepType);
6393 if (FAILED(rc)) return rc;
6394
6395 {
6396 if (mData->mMachineStateChangePending != 0)
6397 {
6398 /* ensureNoStateDependencies() is waiting for state dependencies to
6399 * drop to zero so don't add more. It may make sense to wait a bit
6400 * and retry before reporting an error (since the pending state
6401 * transition should be really quick) but let's just assert for
6402 * now to see if it ever happens on practice. */
6403
6404 AssertFailed();
6405
6406 return setError(E_ACCESSDENIED,
6407 tr("Machine state change is in progress. Please retry the operation later."));
6408 }
6409
6410 ++mData->mMachineStateDeps;
6411 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6412 }
6413
6414 if (aState)
6415 *aState = mData->mMachineState;
6416 if (aRegistered)
6417 *aRegistered = mData->mRegistered;
6418
6419 return S_OK;
6420}
6421
6422/**
6423 * Decreases the number of objects dependent on the machine state.
6424 * Must always complete the #addStateDependency() call after the state
6425 * dependency is no more necessary.
6426 */
6427void Machine::releaseStateDependency()
6428{
6429 AutoCaller autoCaller(this);
6430 AssertComRCReturnVoid(autoCaller.rc());
6431
6432 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6433
6434 /* releaseStateDependency() w/o addStateDependency()? */
6435 AssertReturnVoid(mData->mMachineStateDeps != 0);
6436 -- mData->mMachineStateDeps;
6437
6438 if (mData->mMachineStateDeps == 0)
6439 {
6440 /* inform ensureNoStateDependencies() that there are no more deps */
6441 if (mData->mMachineStateChangePending != 0)
6442 {
6443 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6444 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6445 }
6446 }
6447}
6448
6449// protected methods
6450/////////////////////////////////////////////////////////////////////////////
6451
6452/**
6453 * Performs machine state checks based on the @a aDepType value. If a check
6454 * fails, this method will set extended error info, otherwise it will return
6455 * S_OK. It is supposed, that on failure, the caller will immediately return
6456 * the return value of this method to the upper level.
6457 *
6458 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6459 *
6460 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6461 * current state of this machine object allows to change settings of the
6462 * machine (i.e. the machine is not registered, or registered but not running
6463 * and not saved). It is useful to call this method from Machine setters
6464 * before performing any change.
6465 *
6466 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6467 * as for MutableStateDep except that if the machine is saved, S_OK is also
6468 * returned. This is useful in setters which allow changing machine
6469 * properties when it is in the saved state.
6470 *
6471 * @param aDepType Dependency type to check.
6472 *
6473 * @note Non Machine based classes should use #addStateDependency() and
6474 * #releaseStateDependency() methods or the smart AutoStateDependency
6475 * template.
6476 *
6477 * @note This method must be called from under this object's read or write
6478 * lock.
6479 */
6480HRESULT Machine::checkStateDependency(StateDependency aDepType)
6481{
6482 switch (aDepType)
6483 {
6484 case AnyStateDep:
6485 {
6486 break;
6487 }
6488 case MutableStateDep:
6489 {
6490 if ( mData->mRegistered
6491 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6492 || ( mData->mMachineState != MachineState_Paused
6493 && mData->mMachineState != MachineState_Running
6494 && mData->mMachineState != MachineState_Aborted
6495 && mData->mMachineState != MachineState_Teleported
6496 && mData->mMachineState != MachineState_PoweredOff
6497 )
6498 )
6499 )
6500 return setError(VBOX_E_INVALID_VM_STATE,
6501 tr("The machine is not mutable (state is %s)"),
6502 Global::stringifyMachineState(mData->mMachineState));
6503 break;
6504 }
6505 case MutableOrSavedStateDep:
6506 {
6507 if ( mData->mRegistered
6508 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6509 || ( mData->mMachineState != MachineState_Paused
6510 && mData->mMachineState != MachineState_Running
6511 && mData->mMachineState != MachineState_Aborted
6512 && mData->mMachineState != MachineState_Teleported
6513 && mData->mMachineState != MachineState_Saved
6514 && mData->mMachineState != MachineState_PoweredOff
6515 )
6516 )
6517 )
6518 return setError(VBOX_E_INVALID_VM_STATE,
6519 tr("The machine is not mutable (state is %s)"),
6520 Global::stringifyMachineState(mData->mMachineState));
6521 break;
6522 }
6523 }
6524
6525 return S_OK;
6526}
6527
6528/**
6529 * Helper to initialize all associated child objects and allocate data
6530 * structures.
6531 *
6532 * This method must be called as a part of the object's initialization procedure
6533 * (usually done in the #init() method).
6534 *
6535 * @note Must be called only from #init() or from #registeredInit().
6536 */
6537HRESULT Machine::initDataAndChildObjects()
6538{
6539 AutoCaller autoCaller(this);
6540 AssertComRCReturnRC(autoCaller.rc());
6541 AssertComRCReturn(autoCaller.state() == InInit ||
6542 autoCaller.state() == Limited, E_FAIL);
6543
6544 AssertReturn(!mData->mAccessible, E_FAIL);
6545
6546 /* allocate data structures */
6547 mSSData.allocate();
6548 mUserData.allocate();
6549 mHWData.allocate();
6550 mMediaData.allocate();
6551 mStorageControllers.allocate();
6552
6553 /* initialize mOSTypeId */
6554 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6555
6556 /* create associated BIOS settings object */
6557 unconst(mBIOSSettings).createObject();
6558 mBIOSSettings->init(this);
6559
6560 /* create an associated VRDE object (default is disabled) */
6561 unconst(mVRDEServer).createObject();
6562 mVRDEServer->init(this);
6563
6564 /* create associated serial port objects */
6565 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6566 {
6567 unconst(mSerialPorts[slot]).createObject();
6568 mSerialPorts[slot]->init(this, slot);
6569 }
6570
6571 /* create associated parallel port objects */
6572 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6573 {
6574 unconst(mParallelPorts[slot]).createObject();
6575 mParallelPorts[slot]->init(this, slot);
6576 }
6577
6578 /* create the audio adapter object (always present, default is disabled) */
6579 unconst(mAudioAdapter).createObject();
6580 mAudioAdapter->init(this);
6581
6582 /* create the USB controller object (always present, default is disabled) */
6583 unconst(mUSBController).createObject();
6584 mUSBController->init(this);
6585
6586 /* create associated network adapter objects */
6587 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6588 {
6589 unconst(mNetworkAdapters[slot]).createObject();
6590 mNetworkAdapters[slot]->init(this, slot);
6591 }
6592
6593 return S_OK;
6594}
6595
6596/**
6597 * Helper to uninitialize all associated child objects and to free all data
6598 * structures.
6599 *
6600 * This method must be called as a part of the object's uninitialization
6601 * procedure (usually done in the #uninit() method).
6602 *
6603 * @note Must be called only from #uninit() or from #registeredInit().
6604 */
6605void Machine::uninitDataAndChildObjects()
6606{
6607 AutoCaller autoCaller(this);
6608 AssertComRCReturnVoid(autoCaller.rc());
6609 AssertComRCReturnVoid( autoCaller.state() == InUninit
6610 || autoCaller.state() == Limited);
6611
6612 /* tell all our other child objects we've been uninitialized */
6613
6614 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6615 {
6616 if (mNetworkAdapters[slot])
6617 {
6618 mNetworkAdapters[slot]->uninit();
6619 unconst(mNetworkAdapters[slot]).setNull();
6620 }
6621 }
6622
6623 if (mUSBController)
6624 {
6625 mUSBController->uninit();
6626 unconst(mUSBController).setNull();
6627 }
6628
6629 if (mAudioAdapter)
6630 {
6631 mAudioAdapter->uninit();
6632 unconst(mAudioAdapter).setNull();
6633 }
6634
6635 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6636 {
6637 if (mParallelPorts[slot])
6638 {
6639 mParallelPorts[slot]->uninit();
6640 unconst(mParallelPorts[slot]).setNull();
6641 }
6642 }
6643
6644 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6645 {
6646 if (mSerialPorts[slot])
6647 {
6648 mSerialPorts[slot]->uninit();
6649 unconst(mSerialPorts[slot]).setNull();
6650 }
6651 }
6652
6653 if (mVRDEServer)
6654 {
6655 mVRDEServer->uninit();
6656 unconst(mVRDEServer).setNull();
6657 }
6658
6659 if (mBIOSSettings)
6660 {
6661 mBIOSSettings->uninit();
6662 unconst(mBIOSSettings).setNull();
6663 }
6664
6665 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6666 * instance is uninitialized; SessionMachine instances refer to real
6667 * Machine hard disks). This is necessary for a clean re-initialization of
6668 * the VM after successfully re-checking the accessibility state. Note
6669 * that in case of normal Machine or SnapshotMachine uninitialization (as
6670 * a result of unregistering or deleting the snapshot), outdated hard
6671 * disk attachments will already be uninitialized and deleted, so this
6672 * code will not affect them. */
6673 if ( !!mMediaData
6674 && (!isSessionMachine())
6675 )
6676 {
6677 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6678 it != mMediaData->mAttachments.end();
6679 ++it)
6680 {
6681 ComObjPtr<Medium> hd = (*it)->getMedium();
6682 if (hd.isNull())
6683 continue;
6684 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6685 AssertComRC(rc);
6686 }
6687 }
6688
6689 if (!isSessionMachine() && !isSnapshotMachine())
6690 {
6691 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6692 if (mData->mFirstSnapshot)
6693 {
6694 // snapshots tree is protected by media write lock; strictly
6695 // this isn't necessary here since we're deleting the entire
6696 // machine, but otherwise we assert in Snapshot::uninit()
6697 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6698 mData->mFirstSnapshot->uninit();
6699 mData->mFirstSnapshot.setNull();
6700 }
6701
6702 mData->mCurrentSnapshot.setNull();
6703 }
6704
6705 /* free data structures (the essential mData structure is not freed here
6706 * since it may be still in use) */
6707 mMediaData.free();
6708 mStorageControllers.free();
6709 mHWData.free();
6710 mUserData.free();
6711 mSSData.free();
6712}
6713
6714/**
6715 * Returns a pointer to the Machine object for this machine that acts like a
6716 * parent for complex machine data objects such as shared folders, etc.
6717 *
6718 * For primary Machine objects and for SnapshotMachine objects, returns this
6719 * object's pointer itself. For SessionMachine objects, returns the peer
6720 * (primary) machine pointer.
6721 */
6722Machine* Machine::getMachine()
6723{
6724 if (isSessionMachine())
6725 return (Machine*)mPeer;
6726 return this;
6727}
6728
6729/**
6730 * Makes sure that there are no machine state dependents. If necessary, waits
6731 * for the number of dependents to drop to zero.
6732 *
6733 * Make sure this method is called from under this object's write lock to
6734 * guarantee that no new dependents may be added when this method returns
6735 * control to the caller.
6736 *
6737 * @note Locks this object for writing. The lock will be released while waiting
6738 * (if necessary).
6739 *
6740 * @warning To be used only in methods that change the machine state!
6741 */
6742void Machine::ensureNoStateDependencies()
6743{
6744 AssertReturnVoid(isWriteLockOnCurrentThread());
6745
6746 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6747
6748 /* Wait for all state dependents if necessary */
6749 if (mData->mMachineStateDeps != 0)
6750 {
6751 /* lazy semaphore creation */
6752 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6753 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6754
6755 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6756 mData->mMachineStateDeps));
6757
6758 ++mData->mMachineStateChangePending;
6759
6760 /* reset the semaphore before waiting, the last dependent will signal
6761 * it */
6762 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6763
6764 alock.leave();
6765
6766 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6767
6768 alock.enter();
6769
6770 -- mData->mMachineStateChangePending;
6771 }
6772}
6773
6774/**
6775 * Changes the machine state and informs callbacks.
6776 *
6777 * This method is not intended to fail so it either returns S_OK or asserts (and
6778 * returns a failure).
6779 *
6780 * @note Locks this object for writing.
6781 */
6782HRESULT Machine::setMachineState(MachineState_T aMachineState)
6783{
6784 LogFlowThisFuncEnter();
6785 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6786
6787 AutoCaller autoCaller(this);
6788 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6789
6790 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6791
6792 /* wait for state dependents to drop to zero */
6793 ensureNoStateDependencies();
6794
6795 if (mData->mMachineState != aMachineState)
6796 {
6797 mData->mMachineState = aMachineState;
6798
6799 RTTimeNow(&mData->mLastStateChange);
6800
6801 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6802 }
6803
6804 LogFlowThisFuncLeave();
6805 return S_OK;
6806}
6807
6808/**
6809 * Searches for a shared folder with the given logical name
6810 * in the collection of shared folders.
6811 *
6812 * @param aName logical name of the shared folder
6813 * @param aSharedFolder where to return the found object
6814 * @param aSetError whether to set the error info if the folder is
6815 * not found
6816 * @return
6817 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6818 *
6819 * @note
6820 * must be called from under the object's lock!
6821 */
6822HRESULT Machine::findSharedFolder(CBSTR aName,
6823 ComObjPtr<SharedFolder> &aSharedFolder,
6824 bool aSetError /* = false */)
6825{
6826 bool found = false;
6827 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6828 !found && it != mHWData->mSharedFolders.end();
6829 ++it)
6830 {
6831 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6832 found = (*it)->getName() == aName;
6833 if (found)
6834 aSharedFolder = *it;
6835 }
6836
6837 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6838
6839 if (aSetError && !found)
6840 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6841
6842 return rc;
6843}
6844
6845/**
6846 * Initializes all machine instance data from the given settings structures
6847 * from XML. The exception is the machine UUID which needs special handling
6848 * depending on the caller's use case, so the caller needs to set that herself.
6849 *
6850 * This gets called in several contexts during machine initialization:
6851 *
6852 * -- When machine XML exists on disk already and needs to be loaded into memory,
6853 * for example, from registeredInit() to load all registered machines on
6854 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
6855 * attached to the machine should be part of some media registry already.
6856 *
6857 * -- During OVF import, when a machine config has been constructed from an
6858 * OVF file. In this case, puuidRegistry is set to the machine UUID to
6859 * ensure that the media listed as attachments in the config (which have
6860 * been imported from the OVF) receive the correct registry ID.
6861 *
6862 * @param config Machine settings from XML.
6863 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
6864 * @return
6865 */
6866HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
6867 const Guid *puuidRegistry)
6868{
6869 // copy name, description, OS type, teleporter, UTC etc.
6870 mUserData->s = config.machineUserData;
6871
6872 // look up the object by Id to check it is valid
6873 ComPtr<IGuestOSType> guestOSType;
6874 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
6875 guestOSType.asOutParam());
6876 if (FAILED(rc)) return rc;
6877
6878 // stateFile (optional)
6879 if (config.strStateFile.isEmpty())
6880 mSSData->mStateFilePath.setNull();
6881 else
6882 {
6883 Utf8Str stateFilePathFull(config.strStateFile);
6884 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6885 if (RT_FAILURE(vrc))
6886 return setError(E_FAIL,
6887 tr("Invalid saved state file path '%s' (%Rrc)"),
6888 config.strStateFile.c_str(),
6889 vrc);
6890 mSSData->mStateFilePath = stateFilePathFull;
6891 }
6892
6893 // snapshot folder needs special processing so set it again
6894 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
6895 if (FAILED(rc)) return rc;
6896
6897 /* currentStateModified (optional, default is true) */
6898 mData->mCurrentStateModified = config.fCurrentStateModified;
6899
6900 mData->mLastStateChange = config.timeLastStateChange;
6901
6902 /*
6903 * note: all mUserData members must be assigned prior this point because
6904 * we need to commit changes in order to let mUserData be shared by all
6905 * snapshot machine instances.
6906 */
6907 mUserData.commitCopy();
6908
6909 // machine registry, if present (must be loaded before snapshots)
6910 if (config.canHaveOwnMediaRegistry())
6911 {
6912 // determine machine folder
6913 Utf8Str strMachineFolder = getSettingsFileFull();
6914 strMachineFolder.stripFilename();
6915 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
6916 config.mediaRegistry,
6917 strMachineFolder);
6918 if (FAILED(rc)) return rc;
6919 }
6920
6921 /* Snapshot node (optional) */
6922 size_t cRootSnapshots;
6923 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6924 {
6925 // there must be only one root snapshot
6926 Assert(cRootSnapshots == 1);
6927
6928 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6929
6930 rc = loadSnapshot(snap,
6931 config.uuidCurrentSnapshot,
6932 NULL); // no parent == first snapshot
6933 if (FAILED(rc)) return rc;
6934 }
6935
6936 // hardware data
6937 rc = loadHardware(config.hardwareMachine);
6938 if (FAILED(rc)) return rc;
6939
6940 // load storage controllers
6941 rc = loadStorageControllers(config.storageMachine,
6942 puuidRegistry,
6943 NULL /* puuidSnapshot */);
6944 if (FAILED(rc)) return rc;
6945
6946 /*
6947 * NOTE: the assignment below must be the last thing to do,
6948 * otherwise it will be not possible to change the settings
6949 * somewhere in the code above because all setters will be
6950 * blocked by checkStateDependency(MutableStateDep).
6951 */
6952
6953 /* set the machine state to Aborted or Saved when appropriate */
6954 if (config.fAborted)
6955 {
6956 Assert(!mSSData->mStateFilePath.isEmpty());
6957 mSSData->mStateFilePath.setNull();
6958
6959 /* no need to use setMachineState() during init() */
6960 mData->mMachineState = MachineState_Aborted;
6961 }
6962 else if (!mSSData->mStateFilePath.isEmpty())
6963 {
6964 /* no need to use setMachineState() during init() */
6965 mData->mMachineState = MachineState_Saved;
6966 }
6967
6968 // after loading settings, we are no longer different from the XML on disk
6969 mData->flModifications = 0;
6970
6971 return S_OK;
6972}
6973
6974/**
6975 * Recursively loads all snapshots starting from the given.
6976 *
6977 * @param aNode <Snapshot> node.
6978 * @param aCurSnapshotId Current snapshot ID from the settings file.
6979 * @param aParentSnapshot Parent snapshot.
6980 */
6981HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6982 const Guid &aCurSnapshotId,
6983 Snapshot *aParentSnapshot)
6984{
6985 AssertReturn(!isSnapshotMachine(), E_FAIL);
6986 AssertReturn(!isSessionMachine(), E_FAIL);
6987
6988 HRESULT rc = S_OK;
6989
6990 Utf8Str strStateFile;
6991 if (!data.strStateFile.isEmpty())
6992 {
6993 /* optional */
6994 strStateFile = data.strStateFile;
6995 int vrc = calculateFullPath(strStateFile, strStateFile);
6996 if (RT_FAILURE(vrc))
6997 return setError(E_FAIL,
6998 tr("Invalid saved state file path '%s' (%Rrc)"),
6999 strStateFile.c_str(),
7000 vrc);
7001 }
7002
7003 /* create a snapshot machine object */
7004 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7005 pSnapshotMachine.createObject();
7006 rc = pSnapshotMachine->init(this,
7007 data.hardware,
7008 data.storage,
7009 data.uuid.ref(),
7010 strStateFile);
7011 if (FAILED(rc)) return rc;
7012
7013 /* create a snapshot object */
7014 ComObjPtr<Snapshot> pSnapshot;
7015 pSnapshot.createObject();
7016 /* initialize the snapshot */
7017 rc = pSnapshot->init(mParent, // VirtualBox object
7018 data.uuid,
7019 data.strName,
7020 data.strDescription,
7021 data.timestamp,
7022 pSnapshotMachine,
7023 aParentSnapshot);
7024 if (FAILED(rc)) return rc;
7025
7026 /* memorize the first snapshot if necessary */
7027 if (!mData->mFirstSnapshot)
7028 mData->mFirstSnapshot = pSnapshot;
7029
7030 /* memorize the current snapshot when appropriate */
7031 if ( !mData->mCurrentSnapshot
7032 && pSnapshot->getId() == aCurSnapshotId
7033 )
7034 mData->mCurrentSnapshot = pSnapshot;
7035
7036 // now create the children
7037 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7038 it != data.llChildSnapshots.end();
7039 ++it)
7040 {
7041 const settings::Snapshot &childData = *it;
7042 // recurse
7043 rc = loadSnapshot(childData,
7044 aCurSnapshotId,
7045 pSnapshot); // parent = the one we created above
7046 if (FAILED(rc)) return rc;
7047 }
7048
7049 return rc;
7050}
7051
7052/**
7053 * @param aNode <Hardware> node.
7054 */
7055HRESULT Machine::loadHardware(const settings::Hardware &data)
7056{
7057 AssertReturn(!isSessionMachine(), E_FAIL);
7058
7059 HRESULT rc = S_OK;
7060
7061 try
7062 {
7063 /* The hardware version attribute (optional). */
7064 mHWData->mHWVersion = data.strVersion;
7065 mHWData->mHardwareUUID = data.uuid;
7066
7067 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7068 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7069 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7070 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7071 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7072 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7073 mHWData->mPAEEnabled = data.fPAE;
7074 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7075
7076 mHWData->mCPUCount = data.cCPUs;
7077 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7078 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7079
7080 // cpu
7081 if (mHWData->mCPUHotPlugEnabled)
7082 {
7083 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7084 it != data.llCpus.end();
7085 ++it)
7086 {
7087 const settings::Cpu &cpu = *it;
7088
7089 mHWData->mCPUAttached[cpu.ulId] = true;
7090 }
7091 }
7092
7093 // cpuid leafs
7094 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7095 it != data.llCpuIdLeafs.end();
7096 ++it)
7097 {
7098 const settings::CpuIdLeaf &leaf = *it;
7099
7100 switch (leaf.ulId)
7101 {
7102 case 0x0:
7103 case 0x1:
7104 case 0x2:
7105 case 0x3:
7106 case 0x4:
7107 case 0x5:
7108 case 0x6:
7109 case 0x7:
7110 case 0x8:
7111 case 0x9:
7112 case 0xA:
7113 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7114 break;
7115
7116 case 0x80000000:
7117 case 0x80000001:
7118 case 0x80000002:
7119 case 0x80000003:
7120 case 0x80000004:
7121 case 0x80000005:
7122 case 0x80000006:
7123 case 0x80000007:
7124 case 0x80000008:
7125 case 0x80000009:
7126 case 0x8000000A:
7127 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7128 break;
7129
7130 default:
7131 /* just ignore */
7132 break;
7133 }
7134 }
7135
7136 mHWData->mMemorySize = data.ulMemorySizeMB;
7137 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7138
7139 // boot order
7140 for (size_t i = 0;
7141 i < RT_ELEMENTS(mHWData->mBootOrder);
7142 i++)
7143 {
7144 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7145 if (it == data.mapBootOrder.end())
7146 mHWData->mBootOrder[i] = DeviceType_Null;
7147 else
7148 mHWData->mBootOrder[i] = it->second;
7149 }
7150
7151 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7152 mHWData->mMonitorCount = data.cMonitors;
7153 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7154 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7155 mHWData->mFirmwareType = data.firmwareType;
7156 mHWData->mPointingHidType = data.pointingHidType;
7157 mHWData->mKeyboardHidType = data.keyboardHidType;
7158 mHWData->mChipsetType = data.chipsetType;
7159 mHWData->mHpetEnabled = data.fHpetEnabled;
7160
7161 /* VRDEServer */
7162 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7163 if (FAILED(rc)) return rc;
7164
7165 /* BIOS */
7166 rc = mBIOSSettings->loadSettings(data.biosSettings);
7167 if (FAILED(rc)) return rc;
7168
7169 /* USB Controller */
7170 rc = mUSBController->loadSettings(data.usbController);
7171 if (FAILED(rc)) return rc;
7172
7173 // network adapters
7174 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7175 it != data.llNetworkAdapters.end();
7176 ++it)
7177 {
7178 const settings::NetworkAdapter &nic = *it;
7179
7180 /* slot unicity is guaranteed by XML Schema */
7181 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7182 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7183 if (FAILED(rc)) return rc;
7184 }
7185
7186 // serial ports
7187 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7188 it != data.llSerialPorts.end();
7189 ++it)
7190 {
7191 const settings::SerialPort &s = *it;
7192
7193 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7194 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7195 if (FAILED(rc)) return rc;
7196 }
7197
7198 // parallel ports (optional)
7199 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7200 it != data.llParallelPorts.end();
7201 ++it)
7202 {
7203 const settings::ParallelPort &p = *it;
7204
7205 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7206 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7207 if (FAILED(rc)) return rc;
7208 }
7209
7210 /* AudioAdapter */
7211 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7212 if (FAILED(rc)) return rc;
7213
7214 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7215 it != data.llSharedFolders.end();
7216 ++it)
7217 {
7218 const settings::SharedFolder &sf = *it;
7219 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7220 Bstr(sf.strHostPath).raw(),
7221 sf.fWritable, sf.fAutoMount);
7222 if (FAILED(rc)) return rc;
7223 }
7224
7225 // Clipboard
7226 mHWData->mClipboardMode = data.clipboardMode;
7227
7228 // guest settings
7229 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7230
7231 // IO settings
7232 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7233 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7234
7235#ifdef VBOX_WITH_GUEST_PROPS
7236 /* Guest properties (optional) */
7237 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7238 it != data.llGuestProperties.end();
7239 ++it)
7240 {
7241 const settings::GuestProperty &prop = *it;
7242 uint32_t fFlags = guestProp::NILFLAG;
7243 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7244 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7245 mHWData->mGuestProperties.push_back(property);
7246 }
7247
7248 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7249#endif /* VBOX_WITH_GUEST_PROPS defined */
7250 }
7251 catch(std::bad_alloc &)
7252 {
7253 return E_OUTOFMEMORY;
7254 }
7255
7256 AssertComRC(rc);
7257 return rc;
7258}
7259
7260/**
7261 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7262 *
7263 * @param data
7264 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7265 * @param puuidSnapshot
7266 * @return
7267 */
7268HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7269 const Guid *puuidRegistry,
7270 const Guid *puuidSnapshot)
7271{
7272 AssertReturn(!isSessionMachine(), E_FAIL);
7273
7274 HRESULT rc = S_OK;
7275
7276 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7277 it != data.llStorageControllers.end();
7278 ++it)
7279 {
7280 const settings::StorageController &ctlData = *it;
7281
7282 ComObjPtr<StorageController> pCtl;
7283 /* Try to find one with the name first. */
7284 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7285 if (SUCCEEDED(rc))
7286 return setError(VBOX_E_OBJECT_IN_USE,
7287 tr("Storage controller named '%s' already exists"),
7288 ctlData.strName.c_str());
7289
7290 pCtl.createObject();
7291 rc = pCtl->init(this,
7292 ctlData.strName,
7293 ctlData.storageBus,
7294 ctlData.ulInstance,
7295 ctlData.fBootable);
7296 if (FAILED(rc)) return rc;
7297
7298 mStorageControllers->push_back(pCtl);
7299
7300 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7301 if (FAILED(rc)) return rc;
7302
7303 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7304 if (FAILED(rc)) return rc;
7305
7306 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7307 if (FAILED(rc)) return rc;
7308
7309 /* Set IDE emulation settings (only for AHCI controller). */
7310 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7311 {
7312 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7313 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7314 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7315 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7316 )
7317 return rc;
7318 }
7319
7320 /* Load the attached devices now. */
7321 rc = loadStorageDevices(pCtl,
7322 ctlData,
7323 puuidRegistry,
7324 puuidSnapshot);
7325 if (FAILED(rc)) return rc;
7326 }
7327
7328 return S_OK;
7329}
7330
7331/**
7332 * Called from loadStorageControllers for a controller's devices.
7333 *
7334 * @param aStorageController
7335 * @param data
7336 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7337 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7338 * @return
7339 */
7340HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7341 const settings::StorageController &data,
7342 const Guid *puuidRegistry,
7343 const Guid *puuidSnapshot)
7344{
7345 HRESULT rc = S_OK;
7346
7347 /* paranoia: detect duplicate attachments */
7348 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7349 it != data.llAttachedDevices.end();
7350 ++it)
7351 {
7352 const settings::AttachedDevice &ad = *it;
7353
7354 for (settings::AttachedDevicesList::const_iterator it2 = it;
7355 it2 != data.llAttachedDevices.end();
7356 ++it2)
7357 {
7358 if (it == it2)
7359 continue;
7360
7361 const settings::AttachedDevice &ad2 = *it2;
7362
7363 if ( ad.lPort == ad2.lPort
7364 && ad.lDevice == ad2.lDevice)
7365 {
7366 return setError(E_FAIL,
7367 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7368 aStorageController->getName().c_str(),
7369 ad.lPort,
7370 ad.lDevice,
7371 mUserData->s.strName.c_str());
7372 }
7373 }
7374 }
7375
7376 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7377 it != data.llAttachedDevices.end();
7378 ++it)
7379 {
7380 const settings::AttachedDevice &dev = *it;
7381 ComObjPtr<Medium> medium;
7382
7383 switch (dev.deviceType)
7384 {
7385 case DeviceType_Floppy:
7386 case DeviceType_DVD:
7387 rc = mParent->findRemoveableMedium(dev.deviceType, dev.uuid, false /* fRefresh */, medium);
7388 if (FAILED(rc))
7389 return rc;
7390 break;
7391
7392 case DeviceType_HardDisk:
7393 {
7394 /* find a hard disk by UUID */
7395 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7396 if (FAILED(rc))
7397 {
7398 if (isSnapshotMachine())
7399 {
7400 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7401 // so the user knows that the bad disk is in a snapshot somewhere
7402 com::ErrorInfo info;
7403 return setError(E_FAIL,
7404 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7405 puuidSnapshot->raw(),
7406 info.getText().raw());
7407 }
7408 else
7409 return rc;
7410 }
7411
7412 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7413
7414 if (medium->getType() == MediumType_Immutable)
7415 {
7416 if (isSnapshotMachine())
7417 return setError(E_FAIL,
7418 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7419 "of the virtual machine '%s' ('%s')"),
7420 medium->getLocationFull().c_str(),
7421 dev.uuid.raw(),
7422 puuidSnapshot->raw(),
7423 mUserData->s.strName.c_str(),
7424 mData->m_strConfigFileFull.c_str());
7425
7426 return setError(E_FAIL,
7427 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7428 medium->getLocationFull().c_str(),
7429 dev.uuid.raw(),
7430 mUserData->s.strName.c_str(),
7431 mData->m_strConfigFileFull.c_str());
7432 }
7433
7434 if ( !isSnapshotMachine()
7435 && medium->getChildren().size() != 0
7436 )
7437 return setError(E_FAIL,
7438 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7439 "because it has %d differencing child hard disks"),
7440 medium->getLocationFull().c_str(),
7441 dev.uuid.raw(),
7442 mUserData->s.strName.c_str(),
7443 mData->m_strConfigFileFull.c_str(),
7444 medium->getChildren().size());
7445
7446 if (findAttachment(mMediaData->mAttachments,
7447 medium))
7448 return setError(E_FAIL,
7449 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7450 medium->getLocationFull().c_str(),
7451 dev.uuid.raw(),
7452 mUserData->s.strName.c_str(),
7453 mData->m_strConfigFileFull.c_str());
7454
7455 break;
7456 }
7457
7458 default:
7459 return setError(E_FAIL,
7460 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7461 medium->getLocationFull().c_str(),
7462 mUserData->s.strName.c_str(),
7463 mData->m_strConfigFileFull.c_str());
7464 }
7465
7466 if (FAILED(rc))
7467 break;
7468
7469 const Bstr controllerName = aStorageController->getName();
7470 ComObjPtr<MediumAttachment> pAttachment;
7471 pAttachment.createObject();
7472 rc = pAttachment->init(this,
7473 medium,
7474 controllerName,
7475 dev.lPort,
7476 dev.lDevice,
7477 dev.deviceType,
7478 dev.fPassThrough,
7479 dev.ulBandwidthLimit);
7480 if (FAILED(rc)) break;
7481
7482 /* associate the medium with this machine and snapshot */
7483 if (!medium.isNull())
7484 {
7485 if (isSnapshotMachine())
7486 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7487 else
7488 rc = medium->addBackReference(mData->mUuid);
7489
7490 if (puuidRegistry)
7491 // caller wants registry ID to be set on all attached media (OVF import case)
7492 medium->addRegistry(*puuidRegistry);
7493 }
7494
7495 if (FAILED(rc))
7496 break;
7497
7498 /* back up mMediaData to let registeredInit() properly rollback on failure
7499 * (= limited accessibility) */
7500 setModified(IsModified_Storage);
7501 mMediaData.backup();
7502 mMediaData->mAttachments.push_back(pAttachment);
7503 }
7504
7505 return rc;
7506}
7507
7508/**
7509 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7510 *
7511 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7512 * @param aSnapshot where to return the found snapshot
7513 * @param aSetError true to set extended error info on failure
7514 */
7515HRESULT Machine::findSnapshotById(const Guid &aId,
7516 ComObjPtr<Snapshot> &aSnapshot,
7517 bool aSetError /* = false */)
7518{
7519 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7520
7521 if (!mData->mFirstSnapshot)
7522 {
7523 if (aSetError)
7524 return setError(E_FAIL, tr("This machine does not have any snapshots"));
7525 return E_FAIL;
7526 }
7527
7528 if (aId.isEmpty())
7529 aSnapshot = mData->mFirstSnapshot;
7530 else
7531 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
7532
7533 if (!aSnapshot)
7534 {
7535 if (aSetError)
7536 return setError(E_FAIL,
7537 tr("Could not find a snapshot with UUID {%s}"),
7538 aId.toString().c_str());
7539 return E_FAIL;
7540 }
7541
7542 return S_OK;
7543}
7544
7545/**
7546 * Returns the snapshot with the given name or fails of no such snapshot.
7547 *
7548 * @param aName snapshot name to find
7549 * @param aSnapshot where to return the found snapshot
7550 * @param aSetError true to set extended error info on failure
7551 */
7552HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
7553 ComObjPtr<Snapshot> &aSnapshot,
7554 bool aSetError /* = false */)
7555{
7556 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
7557
7558 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7559
7560 if (!mData->mFirstSnapshot)
7561 {
7562 if (aSetError)
7563 return setError(VBOX_E_OBJECT_NOT_FOUND,
7564 tr("This machine does not have any snapshots"));
7565 return VBOX_E_OBJECT_NOT_FOUND;
7566 }
7567
7568 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
7569
7570 if (!aSnapshot)
7571 {
7572 if (aSetError)
7573 return setError(VBOX_E_OBJECT_NOT_FOUND,
7574 tr("Could not find a snapshot named '%s'"), strName.c_str());
7575 return VBOX_E_OBJECT_NOT_FOUND;
7576 }
7577
7578 return S_OK;
7579}
7580
7581/**
7582 * Returns a storage controller object with the given name.
7583 *
7584 * @param aName storage controller name to find
7585 * @param aStorageController where to return the found storage controller
7586 * @param aSetError true to set extended error info on failure
7587 */
7588HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7589 ComObjPtr<StorageController> &aStorageController,
7590 bool aSetError /* = false */)
7591{
7592 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7593
7594 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7595 it != mStorageControllers->end();
7596 ++it)
7597 {
7598 if ((*it)->getName() == aName)
7599 {
7600 aStorageController = (*it);
7601 return S_OK;
7602 }
7603 }
7604
7605 if (aSetError)
7606 return setError(VBOX_E_OBJECT_NOT_FOUND,
7607 tr("Could not find a storage controller named '%s'"),
7608 aName.c_str());
7609 return VBOX_E_OBJECT_NOT_FOUND;
7610}
7611
7612HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7613 MediaData::AttachmentList &atts)
7614{
7615 AutoCaller autoCaller(this);
7616 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7617
7618 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7619
7620 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7621 it != mMediaData->mAttachments.end();
7622 ++it)
7623 {
7624 const ComObjPtr<MediumAttachment> &pAtt = *it;
7625
7626 // should never happen, but deal with NULL pointers in the list.
7627 AssertStmt(!pAtt.isNull(), continue);
7628
7629 // getControllerName() needs caller+read lock
7630 AutoCaller autoAttCaller(pAtt);
7631 if (FAILED(autoAttCaller.rc()))
7632 {
7633 atts.clear();
7634 return autoAttCaller.rc();
7635 }
7636 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7637
7638 if (pAtt->getControllerName() == aName)
7639 atts.push_back(pAtt);
7640 }
7641
7642 return S_OK;
7643}
7644
7645/**
7646 * Helper for #saveSettings. Cares about renaming the settings directory and
7647 * file if the machine name was changed and about creating a new settings file
7648 * if this is a new machine.
7649 *
7650 * @note Must be never called directly but only from #saveSettings().
7651 */
7652HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7653{
7654 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7655
7656 HRESULT rc = S_OK;
7657
7658 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7659
7660 /* attempt to rename the settings file if machine name is changed */
7661 if ( mUserData->s.fNameSync
7662 && mUserData.isBackedUp()
7663 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7664 )
7665 {
7666 bool dirRenamed = false;
7667 bool fileRenamed = false;
7668
7669 Utf8Str configFile, newConfigFile;
7670 Utf8Str configDir, newConfigDir;
7671
7672 do
7673 {
7674 int vrc = VINF_SUCCESS;
7675
7676 Utf8Str name = mUserData.backedUpData()->s.strName;
7677 Utf8Str newName = mUserData->s.strName;
7678
7679 configFile = mData->m_strConfigFileFull;
7680
7681 /* first, rename the directory if it matches the machine name */
7682 configDir = configFile;
7683 configDir.stripFilename();
7684 newConfigDir = configDir;
7685 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7686 {
7687 newConfigDir.stripFilename();
7688 newConfigDir.append(RTPATH_DELIMITER);
7689 newConfigDir.append(newName);
7690 /* new dir and old dir cannot be equal here because of 'if'
7691 * above and because name != newName */
7692 Assert(configDir != newConfigDir);
7693 if (!fSettingsFileIsNew)
7694 {
7695 /* perform real rename only if the machine is not new */
7696 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7697 if (RT_FAILURE(vrc))
7698 {
7699 rc = setError(E_FAIL,
7700 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7701 configDir.c_str(),
7702 newConfigDir.c_str(),
7703 vrc);
7704 break;
7705 }
7706 dirRenamed = true;
7707 }
7708 }
7709
7710 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
7711 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7712
7713 /* then try to rename the settings file itself */
7714 if (newConfigFile != configFile)
7715 {
7716 /* get the path to old settings file in renamed directory */
7717 configFile = Utf8StrFmt("%s%c%s",
7718 newConfigDir.c_str(),
7719 RTPATH_DELIMITER,
7720 RTPathFilename(configFile.c_str()));
7721 if (!fSettingsFileIsNew)
7722 {
7723 /* perform real rename only if the machine is not new */
7724 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7725 if (RT_FAILURE(vrc))
7726 {
7727 rc = setError(E_FAIL,
7728 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7729 configFile.c_str(),
7730 newConfigFile.c_str(),
7731 vrc);
7732 break;
7733 }
7734 fileRenamed = true;
7735 }
7736 }
7737
7738 // update m_strConfigFileFull amd mConfigFile
7739 mData->m_strConfigFileFull = newConfigFile;
7740 // compute the relative path too
7741 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7742
7743 // store the old and new so that VirtualBox::saveSettings() can update
7744 // the media registry
7745 if ( mData->mRegistered
7746 && configDir != newConfigDir)
7747 {
7748 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7749
7750 if (pfNeedsGlobalSaveSettings)
7751 *pfNeedsGlobalSaveSettings = true;
7752 }
7753
7754 /* update the saved state file path */
7755 Utf8Str path = mSSData->mStateFilePath;
7756 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7757 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
7758 newConfigDir.c_str(),
7759 path.c_str() + configDir.length());
7760
7761 /* Update saved state file paths of all online snapshots.
7762 * Note that saveSettings() will recognize name change
7763 * and will save all snapshots in this case. */
7764 if (mData->mFirstSnapshot)
7765 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7766 newConfigDir.c_str());
7767 }
7768 while (0);
7769
7770 if (FAILED(rc))
7771 {
7772 /* silently try to rename everything back */
7773 if (fileRenamed)
7774 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
7775 if (dirRenamed)
7776 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
7777 }
7778
7779 if (FAILED(rc)) return rc;
7780 }
7781
7782 if (fSettingsFileIsNew)
7783 {
7784 /* create a virgin config file */
7785 int vrc = VINF_SUCCESS;
7786
7787 /* ensure the settings directory exists */
7788 Utf8Str path(mData->m_strConfigFileFull);
7789 path.stripFilename();
7790 if (!RTDirExists(path.c_str()))
7791 {
7792 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7793 if (RT_FAILURE(vrc))
7794 {
7795 return setError(E_FAIL,
7796 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7797 path.c_str(),
7798 vrc);
7799 }
7800 }
7801
7802 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7803 path = Utf8Str(mData->m_strConfigFileFull);
7804 RTFILE f = NIL_RTFILE;
7805 vrc = RTFileOpen(&f, path.c_str(),
7806 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7807 if (RT_FAILURE(vrc))
7808 return setError(E_FAIL,
7809 tr("Could not create the settings file '%s' (%Rrc)"),
7810 path.c_str(),
7811 vrc);
7812 RTFileClose(f);
7813 }
7814
7815 return rc;
7816}
7817
7818/**
7819 * Saves and commits machine data, user data and hardware data.
7820 *
7821 * Note that on failure, the data remains uncommitted.
7822 *
7823 * @a aFlags may combine the following flags:
7824 *
7825 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7826 * Used when saving settings after an operation that makes them 100%
7827 * correspond to the settings from the current snapshot.
7828 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7829 * #isReallyModified() returns false. This is necessary for cases when we
7830 * change machine data directly, not through the backup()/commit() mechanism.
7831 * - SaveS_Force: settings will be saved without doing a deep compare of the
7832 * settings structures. This is used when this is called because snapshots
7833 * have changed to avoid the overhead of the deep compare.
7834 *
7835 * @note Must be called from under this object's write lock. Locks children for
7836 * writing.
7837 *
7838 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7839 * initialized to false and that will be set to true by this function if
7840 * the caller must invoke VirtualBox::saveSettings() because the global
7841 * settings have changed. This will happen if a machine rename has been
7842 * saved and the global machine and media registries will therefore need
7843 * updating.
7844 */
7845HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7846 int aFlags /*= 0*/)
7847{
7848 LogFlowThisFuncEnter();
7849
7850 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7851
7852 /* make sure child objects are unable to modify the settings while we are
7853 * saving them */
7854 ensureNoStateDependencies();
7855
7856 AssertReturn(!isSnapshotMachine(),
7857 E_FAIL);
7858
7859 HRESULT rc = S_OK;
7860 bool fNeedsWrite = false;
7861
7862 /* First, prepare to save settings. It will care about renaming the
7863 * settings directory and file if the machine name was changed and about
7864 * creating a new settings file if this is a new machine. */
7865 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7866 if (FAILED(rc)) return rc;
7867
7868 // keep a pointer to the current settings structures
7869 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7870 settings::MachineConfigFile *pNewConfig = NULL;
7871
7872 try
7873 {
7874 // make a fresh one to have everyone write stuff into
7875 pNewConfig = new settings::MachineConfigFile(NULL);
7876 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7877
7878 // now go and copy all the settings data from COM to the settings structures
7879 // (this calles saveSettings() on all the COM objects in the machine)
7880 copyMachineDataToSettings(*pNewConfig);
7881
7882 if (aFlags & SaveS_ResetCurStateModified)
7883 {
7884 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7885 mData->mCurrentStateModified = FALSE;
7886 fNeedsWrite = true; // always, no need to compare
7887 }
7888 else if (aFlags & SaveS_Force)
7889 {
7890 fNeedsWrite = true; // always, no need to compare
7891 }
7892 else
7893 {
7894 if (!mData->mCurrentStateModified)
7895 {
7896 // do a deep compare of the settings that we just saved with the settings
7897 // previously stored in the config file; this invokes MachineConfigFile::operator==
7898 // which does a deep compare of all the settings, which is expensive but less expensive
7899 // than writing out XML in vain
7900 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7901
7902 // could still be modified if any settings changed
7903 mData->mCurrentStateModified = fAnySettingsChanged;
7904
7905 fNeedsWrite = fAnySettingsChanged;
7906 }
7907 else
7908 fNeedsWrite = true;
7909 }
7910
7911 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7912
7913 if (fNeedsWrite)
7914 // now spit it all out!
7915 pNewConfig->write(mData->m_strConfigFileFull);
7916
7917 mData->pMachineConfigFile = pNewConfig;
7918 delete pOldConfig;
7919 commit();
7920
7921 // after saving settings, we are no longer different from the XML on disk
7922 mData->flModifications = 0;
7923 }
7924 catch (HRESULT err)
7925 {
7926 // we assume that error info is set by the thrower
7927 rc = err;
7928
7929 // restore old config
7930 delete pNewConfig;
7931 mData->pMachineConfigFile = pOldConfig;
7932 }
7933 catch (...)
7934 {
7935 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7936 }
7937
7938 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7939 {
7940 /* Fire the data change event, even on failure (since we've already
7941 * committed all data). This is done only for SessionMachines because
7942 * mutable Machine instances are always not registered (i.e. private
7943 * to the client process that creates them) and thus don't need to
7944 * inform callbacks. */
7945 if (isSessionMachine())
7946 mParent->onMachineDataChange(mData->mUuid);
7947 }
7948
7949 LogFlowThisFunc(("rc=%08X\n", rc));
7950 LogFlowThisFuncLeave();
7951 return rc;
7952}
7953
7954/**
7955 * Implementation for saving the machine settings into the given
7956 * settings::MachineConfigFile instance. This copies machine extradata
7957 * from the previous machine config file in the instance data, if any.
7958 *
7959 * This gets called from two locations:
7960 *
7961 * -- Machine::saveSettings(), during the regular XML writing;
7962 *
7963 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7964 * exported to OVF and we write the VirtualBox proprietary XML
7965 * into a <vbox:Machine> tag.
7966 *
7967 * This routine fills all the fields in there, including snapshots, *except*
7968 * for the following:
7969 *
7970 * -- fCurrentStateModified. There is some special logic associated with that.
7971 *
7972 * The caller can then call MachineConfigFile::write() or do something else
7973 * with it.
7974 *
7975 * Caller must hold the machine lock!
7976 *
7977 * This throws XML errors and HRESULT, so the caller must have a catch block!
7978 */
7979void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7980{
7981 // deep copy extradata
7982 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7983
7984 config.uuid = mData->mUuid;
7985
7986 // copy name, description, OS type, teleport, UTC etc.
7987 config.machineUserData = mUserData->s;
7988
7989 if ( mData->mMachineState == MachineState_Saved
7990 || mData->mMachineState == MachineState_Restoring
7991 // when deleting a snapshot we may or may not have a saved state in the current state,
7992 // so let's not assert here please
7993 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7994 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7995 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7996 && (!mSSData->mStateFilePath.isEmpty())
7997 )
7998 )
7999 {
8000 Assert(!mSSData->mStateFilePath.isEmpty());
8001 /* try to make the file name relative to the settings file dir */
8002 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
8003 }
8004 else
8005 {
8006 Assert(mSSData->mStateFilePath.isEmpty());
8007 config.strStateFile.setNull();
8008 }
8009
8010 if (mData->mCurrentSnapshot)
8011 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8012 else
8013 config.uuidCurrentSnapshot.clear();
8014
8015 config.timeLastStateChange = mData->mLastStateChange;
8016 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8017 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8018
8019 HRESULT rc = saveHardware(config.hardwareMachine);
8020 if (FAILED(rc)) throw rc;
8021
8022 rc = saveStorageControllers(config.storageMachine);
8023 if (FAILED(rc)) throw rc;
8024
8025 // save machine's media registry if this is VirtualBox 4.0 or later
8026 if (config.canHaveOwnMediaRegistry())
8027 {
8028 // determine machine folder
8029 Utf8Str strMachineFolder = getSettingsFileFull();
8030 strMachineFolder.stripFilename();
8031 mParent->saveMediaRegistry(config.mediaRegistry,
8032 getId(), // only media with registry ID == machine UUID
8033 strMachineFolder);
8034 // this throws HRESULT
8035 }
8036
8037 // save snapshots
8038 rc = saveAllSnapshots(config);
8039 if (FAILED(rc)) throw rc;
8040}
8041
8042/**
8043 * Saves all snapshots of the machine into the given machine config file. Called
8044 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8045 * @param config
8046 * @return
8047 */
8048HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8049{
8050 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8051
8052 HRESULT rc = S_OK;
8053
8054 try
8055 {
8056 config.llFirstSnapshot.clear();
8057
8058 if (mData->mFirstSnapshot)
8059 {
8060 settings::Snapshot snapNew;
8061 config.llFirstSnapshot.push_back(snapNew);
8062
8063 // get reference to the fresh copy of the snapshot on the list and
8064 // work on that copy directly to avoid excessive copying later
8065 settings::Snapshot &snap = config.llFirstSnapshot.front();
8066
8067 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8068 if (FAILED(rc)) throw rc;
8069 }
8070
8071// if (mType == IsSessionMachine)
8072// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8073
8074 }
8075 catch (HRESULT err)
8076 {
8077 /* we assume that error info is set by the thrower */
8078 rc = err;
8079 }
8080 catch (...)
8081 {
8082 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8083 }
8084
8085 return rc;
8086}
8087
8088/**
8089 * Saves the VM hardware configuration. It is assumed that the
8090 * given node is empty.
8091 *
8092 * @param aNode <Hardware> node to save the VM hardware configuration to.
8093 */
8094HRESULT Machine::saveHardware(settings::Hardware &data)
8095{
8096 HRESULT rc = S_OK;
8097
8098 try
8099 {
8100 /* The hardware version attribute (optional).
8101 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8102 if ( mHWData->mHWVersion == "1"
8103 && mSSData->mStateFilePath.isEmpty()
8104 )
8105 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. */
8106
8107 data.strVersion = mHWData->mHWVersion;
8108 data.uuid = mHWData->mHardwareUUID;
8109
8110 // CPU
8111 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8112 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8113 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8114 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8115 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8116 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8117 data.fPAE = !!mHWData->mPAEEnabled;
8118 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8119
8120 /* Standard and Extended CPUID leafs. */
8121 data.llCpuIdLeafs.clear();
8122 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8123 {
8124 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8125 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8126 }
8127 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8128 {
8129 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8130 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8131 }
8132
8133 data.cCPUs = mHWData->mCPUCount;
8134 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8135 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8136
8137 data.llCpus.clear();
8138 if (data.fCpuHotPlug)
8139 {
8140 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8141 {
8142 if (mHWData->mCPUAttached[idx])
8143 {
8144 settings::Cpu cpu;
8145 cpu.ulId = idx;
8146 data.llCpus.push_back(cpu);
8147 }
8148 }
8149 }
8150
8151 // memory
8152 data.ulMemorySizeMB = mHWData->mMemorySize;
8153 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8154
8155 // firmware
8156 data.firmwareType = mHWData->mFirmwareType;
8157
8158 // HID
8159 data.pointingHidType = mHWData->mPointingHidType;
8160 data.keyboardHidType = mHWData->mKeyboardHidType;
8161
8162 // chipset
8163 data.chipsetType = mHWData->mChipsetType;
8164
8165 // HPET
8166 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8167
8168 // boot order
8169 data.mapBootOrder.clear();
8170 for (size_t i = 0;
8171 i < RT_ELEMENTS(mHWData->mBootOrder);
8172 ++i)
8173 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8174
8175 // display
8176 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8177 data.cMonitors = mHWData->mMonitorCount;
8178 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8179 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8180
8181 /* VRDEServer settings (optional) */
8182 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8183 if (FAILED(rc)) throw rc;
8184
8185 /* BIOS (required) */
8186 rc = mBIOSSettings->saveSettings(data.biosSettings);
8187 if (FAILED(rc)) throw rc;
8188
8189 /* USB Controller (required) */
8190 rc = mUSBController->saveSettings(data.usbController);
8191 if (FAILED(rc)) throw rc;
8192
8193 /* Network adapters (required) */
8194 data.llNetworkAdapters.clear();
8195 for (ULONG slot = 0;
8196 slot < RT_ELEMENTS(mNetworkAdapters);
8197 ++slot)
8198 {
8199 settings::NetworkAdapter nic;
8200 nic.ulSlot = slot;
8201 rc = mNetworkAdapters[slot]->saveSettings(nic);
8202 if (FAILED(rc)) throw rc;
8203
8204 data.llNetworkAdapters.push_back(nic);
8205 }
8206
8207 /* Serial ports */
8208 data.llSerialPorts.clear();
8209 for (ULONG slot = 0;
8210 slot < RT_ELEMENTS(mSerialPorts);
8211 ++slot)
8212 {
8213 settings::SerialPort s;
8214 s.ulSlot = slot;
8215 rc = mSerialPorts[slot]->saveSettings(s);
8216 if (FAILED(rc)) return rc;
8217
8218 data.llSerialPorts.push_back(s);
8219 }
8220
8221 /* Parallel ports */
8222 data.llParallelPorts.clear();
8223 for (ULONG slot = 0;
8224 slot < RT_ELEMENTS(mParallelPorts);
8225 ++slot)
8226 {
8227 settings::ParallelPort p;
8228 p.ulSlot = slot;
8229 rc = mParallelPorts[slot]->saveSettings(p);
8230 if (FAILED(rc)) return rc;
8231
8232 data.llParallelPorts.push_back(p);
8233 }
8234
8235 /* Audio adapter */
8236 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8237 if (FAILED(rc)) return rc;
8238
8239 /* Shared folders */
8240 data.llSharedFolders.clear();
8241 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8242 it != mHWData->mSharedFolders.end();
8243 ++it)
8244 {
8245 ComObjPtr<SharedFolder> pFolder = *it;
8246 settings::SharedFolder sf;
8247 sf.strName = pFolder->getName();
8248 sf.strHostPath = pFolder->getHostPath();
8249 sf.fWritable = !!pFolder->isWritable();
8250 sf.fAutoMount = !!pFolder->isAutoMounted();
8251
8252 data.llSharedFolders.push_back(sf);
8253 }
8254
8255 // clipboard
8256 data.clipboardMode = mHWData->mClipboardMode;
8257
8258 /* Guest */
8259 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8260
8261 // IO settings
8262 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8263 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8264
8265 // guest properties
8266 data.llGuestProperties.clear();
8267#ifdef VBOX_WITH_GUEST_PROPS
8268 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8269 it != mHWData->mGuestProperties.end();
8270 ++it)
8271 {
8272 HWData::GuestProperty property = *it;
8273
8274 /* Remove transient guest properties at shutdown unless we
8275 * are saving state */
8276 if ( ( mData->mMachineState == MachineState_PoweredOff
8277 || mData->mMachineState == MachineState_Aborted
8278 || mData->mMachineState == MachineState_Teleported)
8279 && property.mFlags & guestProp::TRANSIENT)
8280 continue;
8281 settings::GuestProperty prop;
8282 prop.strName = property.strName;
8283 prop.strValue = property.strValue;
8284 prop.timestamp = property.mTimestamp;
8285 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8286 guestProp::writeFlags(property.mFlags, szFlags);
8287 prop.strFlags = szFlags;
8288
8289 data.llGuestProperties.push_back(prop);
8290 }
8291
8292 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8293 /* I presume this doesn't require a backup(). */
8294 mData->mGuestPropertiesModified = FALSE;
8295#endif /* VBOX_WITH_GUEST_PROPS defined */
8296 }
8297 catch(std::bad_alloc &)
8298 {
8299 return E_OUTOFMEMORY;
8300 }
8301
8302 AssertComRC(rc);
8303 return rc;
8304}
8305
8306/**
8307 * Saves the storage controller configuration.
8308 *
8309 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8310 */
8311HRESULT Machine::saveStorageControllers(settings::Storage &data)
8312{
8313 data.llStorageControllers.clear();
8314
8315 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8316 it != mStorageControllers->end();
8317 ++it)
8318 {
8319 HRESULT rc;
8320 ComObjPtr<StorageController> pCtl = *it;
8321
8322 settings::StorageController ctl;
8323 ctl.strName = pCtl->getName();
8324 ctl.controllerType = pCtl->getControllerType();
8325 ctl.storageBus = pCtl->getStorageBus();
8326 ctl.ulInstance = pCtl->getInstance();
8327 ctl.fBootable = pCtl->getBootable();
8328
8329 /* Save the port count. */
8330 ULONG portCount;
8331 rc = pCtl->COMGETTER(PortCount)(&portCount);
8332 ComAssertComRCRet(rc, rc);
8333 ctl.ulPortCount = portCount;
8334
8335 /* Save fUseHostIOCache */
8336 BOOL fUseHostIOCache;
8337 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8338 ComAssertComRCRet(rc, rc);
8339 ctl.fUseHostIOCache = !!fUseHostIOCache;
8340
8341 /* Save IDE emulation settings. */
8342 if (ctl.controllerType == StorageControllerType_IntelAhci)
8343 {
8344 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8345 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8346 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8347 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8348 )
8349 ComAssertComRCRet(rc, rc);
8350 }
8351
8352 /* save the devices now. */
8353 rc = saveStorageDevices(pCtl, ctl);
8354 ComAssertComRCRet(rc, rc);
8355
8356 data.llStorageControllers.push_back(ctl);
8357 }
8358
8359 return S_OK;
8360}
8361
8362/**
8363 * Saves the hard disk configuration.
8364 */
8365HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8366 settings::StorageController &data)
8367{
8368 MediaData::AttachmentList atts;
8369
8370 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8371 if (FAILED(rc)) return rc;
8372
8373 data.llAttachedDevices.clear();
8374 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8375 it != atts.end();
8376 ++it)
8377 {
8378 settings::AttachedDevice dev;
8379
8380 MediumAttachment *pAttach = *it;
8381 Medium *pMedium = pAttach->getMedium();
8382
8383 dev.deviceType = pAttach->getType();
8384 dev.lPort = pAttach->getPort();
8385 dev.lDevice = pAttach->getDevice();
8386 if (pMedium)
8387 {
8388 if (pMedium->isHostDrive())
8389 dev.strHostDriveSrc = pMedium->getLocationFull();
8390 else
8391 dev.uuid = pMedium->getId();
8392 dev.fPassThrough = pAttach->getPassthrough();
8393 }
8394
8395 data.llAttachedDevices.push_back(dev);
8396 }
8397
8398 return S_OK;
8399}
8400
8401/**
8402 * Saves machine state settings as defined by aFlags
8403 * (SaveSTS_* values).
8404 *
8405 * @param aFlags Combination of SaveSTS_* flags.
8406 *
8407 * @note Locks objects for writing.
8408 */
8409HRESULT Machine::saveStateSettings(int aFlags)
8410{
8411 if (aFlags == 0)
8412 return S_OK;
8413
8414 AutoCaller autoCaller(this);
8415 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8416
8417 /* This object's write lock is also necessary to serialize file access
8418 * (prevent concurrent reads and writes) */
8419 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8420
8421 HRESULT rc = S_OK;
8422
8423 Assert(mData->pMachineConfigFile);
8424
8425 try
8426 {
8427 if (aFlags & SaveSTS_CurStateModified)
8428 mData->pMachineConfigFile->fCurrentStateModified = true;
8429
8430 if (aFlags & SaveSTS_StateFilePath)
8431 {
8432 if (!mSSData->mStateFilePath.isEmpty())
8433 /* try to make the file name relative to the settings file dir */
8434 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8435 else
8436 mData->pMachineConfigFile->strStateFile.setNull();
8437 }
8438
8439 if (aFlags & SaveSTS_StateTimeStamp)
8440 {
8441 Assert( mData->mMachineState != MachineState_Aborted
8442 || mSSData->mStateFilePath.isEmpty());
8443
8444 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8445
8446 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8447//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8448 }
8449
8450 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8451 }
8452 catch (...)
8453 {
8454 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8455 }
8456
8457 return rc;
8458}
8459
8460/**
8461 * Creates differencing hard disks for all normal hard disks attached to this
8462 * machine and a new set of attachments to refer to created disks.
8463 *
8464 * Used when taking a snapshot or when deleting the current state. Gets called
8465 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8466 *
8467 * This method assumes that mMediaData contains the original hard disk attachments
8468 * it needs to create diffs for. On success, these attachments will be replaced
8469 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8470 * called to delete created diffs which will also rollback mMediaData and restore
8471 * whatever was backed up before calling this method.
8472 *
8473 * Attachments with non-normal hard disks are left as is.
8474 *
8475 * If @a aOnline is @c false then the original hard disks that require implicit
8476 * diffs will be locked for reading. Otherwise it is assumed that they are
8477 * already locked for writing (when the VM was started). Note that in the latter
8478 * case it is responsibility of the caller to lock the newly created diffs for
8479 * writing if this method succeeds.
8480 *
8481 * @param aProgress Progress object to run (must contain at least as
8482 * many operations left as the number of hard disks
8483 * attached).
8484 * @param aOnline Whether the VM was online prior to this operation.
8485 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
8486 *
8487 * @note The progress object is not marked as completed, neither on success nor
8488 * on failure. This is a responsibility of the caller.
8489 *
8490 * @note Locks this object for writing.
8491 */
8492HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8493 ULONG aWeight,
8494 bool aOnline,
8495 GuidList *pllRegistriesThatNeedSaving)
8496{
8497 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8498
8499 AutoCaller autoCaller(this);
8500 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8501
8502 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8503
8504 /* must be in a protective state because we leave the lock below */
8505 AssertReturn( mData->mMachineState == MachineState_Saving
8506 || mData->mMachineState == MachineState_LiveSnapshotting
8507 || mData->mMachineState == MachineState_RestoringSnapshot
8508 || mData->mMachineState == MachineState_DeletingSnapshot
8509 , E_FAIL);
8510
8511 HRESULT rc = S_OK;
8512
8513 MediumLockListMap lockedMediaOffline;
8514 MediumLockListMap *lockedMediaMap;
8515 if (aOnline)
8516 lockedMediaMap = &mData->mSession.mLockedMedia;
8517 else
8518 lockedMediaMap = &lockedMediaOffline;
8519
8520 try
8521 {
8522 if (!aOnline)
8523 {
8524 /* lock all attached hard disks early to detect "in use"
8525 * situations before creating actual diffs */
8526 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8527 it != mMediaData->mAttachments.end();
8528 ++it)
8529 {
8530 MediumAttachment* pAtt = *it;
8531 if (pAtt->getType() == DeviceType_HardDisk)
8532 {
8533 Medium* pMedium = pAtt->getMedium();
8534 Assert(pMedium);
8535
8536 MediumLockList *pMediumLockList(new MediumLockList());
8537 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8538 false /* fMediumLockWrite */,
8539 NULL,
8540 *pMediumLockList);
8541 if (FAILED(rc))
8542 {
8543 delete pMediumLockList;
8544 throw rc;
8545 }
8546 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8547 if (FAILED(rc))
8548 {
8549 throw setError(rc,
8550 tr("Collecting locking information for all attached media failed"));
8551 }
8552 }
8553 }
8554
8555 /* Now lock all media. If this fails, nothing is locked. */
8556 rc = lockedMediaMap->Lock();
8557 if (FAILED(rc))
8558 {
8559 throw setError(rc,
8560 tr("Locking of attached media failed"));
8561 }
8562 }
8563
8564 /* remember the current list (note that we don't use backup() since
8565 * mMediaData may be already backed up) */
8566 MediaData::AttachmentList atts = mMediaData->mAttachments;
8567
8568 /* start from scratch */
8569 mMediaData->mAttachments.clear();
8570
8571 /* go through remembered attachments and create diffs for normal hard
8572 * disks and attach them */
8573 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8574 it != atts.end();
8575 ++it)
8576 {
8577 MediumAttachment* pAtt = *it;
8578
8579 DeviceType_T devType = pAtt->getType();
8580 Medium* pMedium = pAtt->getMedium();
8581
8582 if ( devType != DeviceType_HardDisk
8583 || pMedium == NULL
8584 || pMedium->getType() != MediumType_Normal)
8585 {
8586 /* copy the attachment as is */
8587
8588 /** @todo the progress object created in Console::TakeSnaphot
8589 * only expects operations for hard disks. Later other
8590 * device types need to show up in the progress as well. */
8591 if (devType == DeviceType_HardDisk)
8592 {
8593 if (pMedium == NULL)
8594 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
8595 aWeight); // weight
8596 else
8597 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8598 pMedium->getBase()->getName().c_str()).raw(),
8599 aWeight); // weight
8600 }
8601
8602 mMediaData->mAttachments.push_back(pAtt);
8603 continue;
8604 }
8605
8606 /* need a diff */
8607 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8608 pMedium->getBase()->getName().c_str()).raw(),
8609 aWeight); // weight
8610
8611 Utf8Str strFullSnapshotFolder;
8612 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
8613
8614 ComObjPtr<Medium> diff;
8615 diff.createObject();
8616 rc = diff->init(mParent,
8617 pMedium->getPreferredDiffFormat(),
8618 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
8619 pMedium->getFirstRegistryMachineId(), // store the diff in the same registry as the parent
8620 pllRegistriesThatNeedSaving);
8621 if (FAILED(rc)) throw rc;
8622
8623 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8624 * the push_back? Looks like we're going to leave medium with the
8625 * wrong kind of lock (general issue with if we fail anywhere at all)
8626 * and an orphaned VDI in the snapshots folder. */
8627
8628 /* update the appropriate lock list */
8629 MediumLockList *pMediumLockList;
8630 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8631 AssertComRCThrowRC(rc);
8632 if (aOnline)
8633 {
8634 rc = pMediumLockList->Update(pMedium, false);
8635 AssertComRCThrowRC(rc);
8636 }
8637
8638 /* leave the lock before the potentially lengthy operation */
8639 alock.leave();
8640 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8641 pMediumLockList,
8642 NULL /* aProgress */,
8643 true /* aWait */,
8644 pllRegistriesThatNeedSaving);
8645 alock.enter();
8646 if (FAILED(rc)) throw rc;
8647
8648 rc = lockedMediaMap->Unlock();
8649 AssertComRCThrowRC(rc);
8650 rc = pMediumLockList->Append(diff, true);
8651 AssertComRCThrowRC(rc);
8652 rc = lockedMediaMap->Lock();
8653 AssertComRCThrowRC(rc);
8654
8655 rc = diff->addBackReference(mData->mUuid);
8656 AssertComRCThrowRC(rc);
8657
8658 /* add a new attachment */
8659 ComObjPtr<MediumAttachment> attachment;
8660 attachment.createObject();
8661 rc = attachment->init(this,
8662 diff,
8663 pAtt->getControllerName(),
8664 pAtt->getPort(),
8665 pAtt->getDevice(),
8666 DeviceType_HardDisk,
8667 true /* aImplicit */,
8668 0 /* No bandwidth limit */);
8669 if (FAILED(rc)) throw rc;
8670
8671 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8672 AssertComRCThrowRC(rc);
8673 mMediaData->mAttachments.push_back(attachment);
8674 }
8675 }
8676 catch (HRESULT aRC) { rc = aRC; }
8677
8678 /* unlock all hard disks we locked */
8679 if (!aOnline)
8680 {
8681 ErrorInfoKeeper eik;
8682
8683 rc = lockedMediaMap->Clear();
8684 AssertComRC(rc);
8685 }
8686
8687 if (FAILED(rc))
8688 {
8689 MultiResult mrc = rc;
8690
8691 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
8692 }
8693
8694 return rc;
8695}
8696
8697/**
8698 * Deletes implicit differencing hard disks created either by
8699 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8700 *
8701 * Note that to delete hard disks created by #AttachMedium() this method is
8702 * called from #fixupMedia() when the changes are rolled back.
8703 *
8704 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8705 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8706 *
8707 * @note Locks this object for writing.
8708 */
8709HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
8710{
8711 AutoCaller autoCaller(this);
8712 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8713
8714 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8715 LogFlowThisFuncEnter();
8716
8717 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8718
8719 HRESULT rc = S_OK;
8720
8721 MediaData::AttachmentList implicitAtts;
8722
8723 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8724
8725 /* enumerate new attachments */
8726 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8727 it != mMediaData->mAttachments.end();
8728 ++it)
8729 {
8730 ComObjPtr<Medium> hd = (*it)->getMedium();
8731 if (hd.isNull())
8732 continue;
8733
8734 if ((*it)->isImplicit())
8735 {
8736 /* deassociate and mark for deletion */
8737 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8738 rc = hd->removeBackReference(mData->mUuid);
8739 AssertComRC(rc);
8740 implicitAtts.push_back(*it);
8741 continue;
8742 }
8743
8744 /* was this hard disk attached before? */
8745 if (!findAttachment(oldAtts, hd))
8746 {
8747 /* no: de-associate */
8748 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8749 rc = hd->removeBackReference(mData->mUuid);
8750 AssertComRC(rc);
8751 continue;
8752 }
8753 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8754 }
8755
8756 /* rollback hard disk changes */
8757 mMediaData.rollback();
8758
8759 MultiResult mrc(S_OK);
8760
8761 /* delete unused implicit diffs */
8762 if (implicitAtts.size() != 0)
8763 {
8764 /* will leave the lock before the potentially lengthy
8765 * operation, so protect with the special state (unless already
8766 * protected) */
8767 MachineState_T oldState = mData->mMachineState;
8768 if ( oldState != MachineState_Saving
8769 && oldState != MachineState_LiveSnapshotting
8770 && oldState != MachineState_RestoringSnapshot
8771 && oldState != MachineState_DeletingSnapshot
8772 && oldState != MachineState_DeletingSnapshotOnline
8773 && oldState != MachineState_DeletingSnapshotPaused
8774 )
8775 setMachineState(MachineState_SettingUp);
8776
8777 alock.leave();
8778
8779 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8780 it != implicitAtts.end();
8781 ++it)
8782 {
8783 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8784 ComObjPtr<Medium> hd = (*it)->getMedium();
8785
8786 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8787 pllRegistriesThatNeedSaving);
8788 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8789 mrc = rc;
8790 }
8791
8792 alock.enter();
8793
8794 if (mData->mMachineState == MachineState_SettingUp)
8795 setMachineState(oldState);
8796 }
8797
8798 return mrc;
8799}
8800
8801/**
8802 * Looks through the given list of media attachments for one with the given parameters
8803 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8804 * can be searched as well if needed.
8805 *
8806 * @param list
8807 * @param aControllerName
8808 * @param aControllerPort
8809 * @param aDevice
8810 * @return
8811 */
8812MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8813 IN_BSTR aControllerName,
8814 LONG aControllerPort,
8815 LONG aDevice)
8816{
8817 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8818 it != ll.end();
8819 ++it)
8820 {
8821 MediumAttachment *pAttach = *it;
8822 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8823 return pAttach;
8824 }
8825
8826 return NULL;
8827}
8828
8829/**
8830 * Looks through the given list of media attachments for one with the given parameters
8831 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8832 * can be searched as well if needed.
8833 *
8834 * @param list
8835 * @param aControllerName
8836 * @param aControllerPort
8837 * @param aDevice
8838 * @return
8839 */
8840MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8841 ComObjPtr<Medium> pMedium)
8842{
8843 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8844 it != ll.end();
8845 ++it)
8846 {
8847 MediumAttachment *pAttach = *it;
8848 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8849 if (pMediumThis == pMedium)
8850 return pAttach;
8851 }
8852
8853 return NULL;
8854}
8855
8856/**
8857 * Looks through the given list of media attachments for one with the given parameters
8858 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8859 * can be searched as well if needed.
8860 *
8861 * @param list
8862 * @param aControllerName
8863 * @param aControllerPort
8864 * @param aDevice
8865 * @return
8866 */
8867MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8868 Guid &id)
8869{
8870 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8871 it != ll.end();
8872 ++it)
8873 {
8874 MediumAttachment *pAttach = *it;
8875 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8876 if (pMediumThis->getId() == id)
8877 return pAttach;
8878 }
8879
8880 return NULL;
8881}
8882
8883/**
8884 * Main implementation for Machine::DetachDevice. This also gets called
8885 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8886 *
8887 * @param pAttach Medium attachment to detach.
8888 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8889 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8890 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8891 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8892 * @return
8893 */
8894HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8895 AutoWriteLock &writeLock,
8896 Snapshot *pSnapshot,
8897 GuidList *pllRegistriesThatNeedSaving)
8898{
8899 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8900 DeviceType_T mediumType = pAttach->getType();
8901
8902 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8903
8904 if (pAttach->isImplicit())
8905 {
8906 /* attempt to implicitly delete the implicitly created diff */
8907
8908 /// @todo move the implicit flag from MediumAttachment to Medium
8909 /// and forbid any hard disk operation when it is implicit. Or maybe
8910 /// a special media state for it to make it even more simple.
8911
8912 Assert(mMediaData.isBackedUp());
8913
8914 /* will leave the lock before the potentially lengthy operation, so
8915 * protect with the special state */
8916 MachineState_T oldState = mData->mMachineState;
8917 setMachineState(MachineState_SettingUp);
8918
8919 writeLock.release();
8920
8921 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8922 pllRegistriesThatNeedSaving);
8923
8924 writeLock.acquire();
8925
8926 setMachineState(oldState);
8927
8928 if (FAILED(rc)) return rc;
8929 }
8930
8931 setModified(IsModified_Storage);
8932 mMediaData.backup();
8933
8934 // we cannot use erase (it) below because backup() above will create
8935 // a copy of the list and make this copy active, but the iterator
8936 // still refers to the original and is not valid for the copy
8937 mMediaData->mAttachments.remove(pAttach);
8938
8939 if (!oldmedium.isNull())
8940 {
8941 // if this is from a snapshot, do not defer detachment to commitMedia()
8942 if (pSnapshot)
8943 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8944 // else if non-hard disk media, do not defer detachment to commitMedia() either
8945 else if (mediumType != DeviceType_HardDisk)
8946 oldmedium->removeBackReference(mData->mUuid);
8947 }
8948
8949 return S_OK;
8950}
8951
8952/**
8953 * Goes thru all medium attachments of the list and calls detachDevice() on each
8954 * of them and attaches all Medium objects found in the process to the given list,
8955 * depending on cleanupMode.
8956 *
8957 * This gets called from Machine::Unregister, both for the actual Machine and
8958 * the SnapshotMachine objects that might be found in the snapshots.
8959 *
8960 * Requires caller and locking.
8961 *
8962 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8963 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8964 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
8965 * otherwise no media get added.
8966 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
8967 * @return
8968 */
8969HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8970 Snapshot *pSnapshot,
8971 CleanupMode_T cleanupMode,
8972 MediaList &llMedia)
8973{
8974 Assert(isWriteLockOnCurrentThread());
8975
8976 HRESULT rc;
8977
8978 // make a temporary list because detachDevice invalidates iterators into
8979 // mMediaData->mAttachments
8980 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8981
8982 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8983 it != llAttachments2.end();
8984 ++it)
8985 {
8986 ComObjPtr<MediumAttachment> pAttach = *it;
8987 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8988
8989 if (!pMedium.isNull())
8990 {
8991 DeviceType_T devType = pMedium->getDeviceType();
8992 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
8993 && devType == DeviceType_HardDisk)
8994 || (cleanupMode == CleanupMode_Full)
8995 )
8996 llMedia.push_back(pMedium);
8997 }
8998
8999 // real machine: then we need to use the proper method
9000 rc = detachDevice(pAttach,
9001 writeLock,
9002 pSnapshot,
9003 NULL /* pfNeedsSaveSettings */);
9004
9005 if (FAILED(rc))
9006 return rc;
9007 }
9008
9009 return S_OK;
9010}
9011
9012/**
9013 * Perform deferred hard disk detachments.
9014 *
9015 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9016 * backed up).
9017 *
9018 * If @a aOnline is @c true then this method will also unlock the old hard disks
9019 * for which the new implicit diffs were created and will lock these new diffs for
9020 * writing.
9021 *
9022 * @param aOnline Whether the VM was online prior to this operation.
9023 *
9024 * @note Locks this object for writing!
9025 */
9026void Machine::commitMedia(bool aOnline /*= false*/)
9027{
9028 AutoCaller autoCaller(this);
9029 AssertComRCReturnVoid(autoCaller.rc());
9030
9031 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9032
9033 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9034
9035 HRESULT rc = S_OK;
9036
9037 /* no attach/detach operations -- nothing to do */
9038 if (!mMediaData.isBackedUp())
9039 return;
9040
9041 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9042 bool fMediaNeedsLocking = false;
9043
9044 /* enumerate new attachments */
9045 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9046 it != mMediaData->mAttachments.end();
9047 ++it)
9048 {
9049 MediumAttachment *pAttach = *it;
9050
9051 pAttach->commit();
9052
9053 Medium* pMedium = pAttach->getMedium();
9054 bool fImplicit = pAttach->isImplicit();
9055
9056 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9057 (pMedium) ? pMedium->getName().c_str() : "NULL",
9058 fImplicit));
9059
9060 /** @todo convert all this Machine-based voodoo to MediumAttachment
9061 * based commit logic. */
9062 if (fImplicit)
9063 {
9064 /* convert implicit attachment to normal */
9065 pAttach->setImplicit(false);
9066
9067 if ( aOnline
9068 && pMedium
9069 && pAttach->getType() == DeviceType_HardDisk
9070 )
9071 {
9072 ComObjPtr<Medium> parent = pMedium->getParent();
9073 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9074
9075 /* update the appropriate lock list */
9076 MediumLockList *pMediumLockList;
9077 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9078 AssertComRC(rc);
9079 if (pMediumLockList)
9080 {
9081 /* unlock if there's a need to change the locking */
9082 if (!fMediaNeedsLocking)
9083 {
9084 rc = mData->mSession.mLockedMedia.Unlock();
9085 AssertComRC(rc);
9086 fMediaNeedsLocking = true;
9087 }
9088 rc = pMediumLockList->Update(parent, false);
9089 AssertComRC(rc);
9090 rc = pMediumLockList->Append(pMedium, true);
9091 AssertComRC(rc);
9092 }
9093 }
9094
9095 continue;
9096 }
9097
9098 if (pMedium)
9099 {
9100 /* was this medium attached before? */
9101 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9102 oldIt != oldAtts.end();
9103 ++oldIt)
9104 {
9105 MediumAttachment *pOldAttach = *oldIt;
9106 if (pOldAttach->getMedium() == pMedium)
9107 {
9108 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9109
9110 /* yes: remove from old to avoid de-association */
9111 oldAtts.erase(oldIt);
9112 break;
9113 }
9114 }
9115 }
9116 }
9117
9118 /* enumerate remaining old attachments and de-associate from the
9119 * current machine state */
9120 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9121 it != oldAtts.end();
9122 ++it)
9123 {
9124 MediumAttachment *pAttach = *it;
9125 Medium* pMedium = pAttach->getMedium();
9126
9127 /* Detach only hard disks, since DVD/floppy media is detached
9128 * instantly in MountMedium. */
9129 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9130 {
9131 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9132
9133 /* now de-associate from the current machine state */
9134 rc = pMedium->removeBackReference(mData->mUuid);
9135 AssertComRC(rc);
9136
9137 if (aOnline)
9138 {
9139 /* unlock since medium is not used anymore */
9140 MediumLockList *pMediumLockList;
9141 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9142 AssertComRC(rc);
9143 if (pMediumLockList)
9144 {
9145 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9146 AssertComRC(rc);
9147 }
9148 }
9149 }
9150 }
9151
9152 /* take media locks again so that the locking state is consistent */
9153 if (fMediaNeedsLocking)
9154 {
9155 Assert(aOnline);
9156 rc = mData->mSession.mLockedMedia.Lock();
9157 AssertComRC(rc);
9158 }
9159
9160 /* commit the hard disk changes */
9161 mMediaData.commit();
9162
9163 if (isSessionMachine())
9164 {
9165 /* attach new data to the primary machine and reshare it */
9166 mPeer->mMediaData.attach(mMediaData);
9167 }
9168
9169 return;
9170}
9171
9172/**
9173 * Perform deferred deletion of implicitly created diffs.
9174 *
9175 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9176 * backed up).
9177 *
9178 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9179 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9180 *
9181 * @note Locks this object for writing!
9182 */
9183void Machine::rollbackMedia()
9184{
9185 AutoCaller autoCaller(this);
9186 AssertComRCReturnVoid (autoCaller.rc());
9187
9188 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9189
9190 LogFlowThisFunc(("Entering\n"));
9191
9192 HRESULT rc = S_OK;
9193
9194 /* no attach/detach operations -- nothing to do */
9195 if (!mMediaData.isBackedUp())
9196 return;
9197
9198 /* enumerate new attachments */
9199 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9200 it != mMediaData->mAttachments.end();
9201 ++it)
9202 {
9203 MediumAttachment *pAttach = *it;
9204 /* Fix up the backrefs for DVD/floppy media. */
9205 if (pAttach->getType() != DeviceType_HardDisk)
9206 {
9207 Medium* pMedium = pAttach->getMedium();
9208 if (pMedium)
9209 {
9210 rc = pMedium->removeBackReference(mData->mUuid);
9211 AssertComRC(rc);
9212 }
9213 }
9214
9215 (*it)->rollback();
9216
9217 pAttach = *it;
9218 /* Fix up the backrefs for DVD/floppy media. */
9219 if (pAttach->getType() != DeviceType_HardDisk)
9220 {
9221 Medium* pMedium = pAttach->getMedium();
9222 if (pMedium)
9223 {
9224 rc = pMedium->addBackReference(mData->mUuid);
9225 AssertComRC(rc);
9226 }
9227 }
9228 }
9229
9230 /** @todo convert all this Machine-based voodoo to MediumAttachment
9231 * based rollback logic. */
9232 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9233 // which gets called if Machine::registeredInit() fails...
9234 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9235
9236 return;
9237}
9238
9239/**
9240 * Returns true if the settings file is located in the directory named exactly
9241 * as the machine; this means, among other things, that the machine directory
9242 * should be auto-renamed.
9243 *
9244 * @param aSettingsDir if not NULL, the full machine settings file directory
9245 * name will be assigned there.
9246 *
9247 * @note Doesn't lock anything.
9248 * @note Not thread safe (must be called from this object's lock).
9249 */
9250bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9251{
9252 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9253 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9254 if (aSettingsDir)
9255 *aSettingsDir = strMachineDirName;
9256 strMachineDirName.stripPath(); // vmname
9257 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9258 strConfigFileOnly.stripPath() // vmname.vbox
9259 .stripExt(); // vmname
9260
9261 AssertReturn(!strMachineDirName.isEmpty(), false);
9262 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9263
9264 return strMachineDirName == strConfigFileOnly;
9265}
9266
9267/**
9268 * Discards all changes to machine settings.
9269 *
9270 * @param aNotify Whether to notify the direct session about changes or not.
9271 *
9272 * @note Locks objects for writing!
9273 */
9274void Machine::rollback(bool aNotify)
9275{
9276 AutoCaller autoCaller(this);
9277 AssertComRCReturn(autoCaller.rc(), (void)0);
9278
9279 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9280
9281 if (!mStorageControllers.isNull())
9282 {
9283 if (mStorageControllers.isBackedUp())
9284 {
9285 /* unitialize all new devices (absent in the backed up list). */
9286 StorageControllerList::const_iterator it = mStorageControllers->begin();
9287 StorageControllerList *backedList = mStorageControllers.backedUpData();
9288 while (it != mStorageControllers->end())
9289 {
9290 if ( std::find(backedList->begin(), backedList->end(), *it)
9291 == backedList->end()
9292 )
9293 {
9294 (*it)->uninit();
9295 }
9296 ++it;
9297 }
9298
9299 /* restore the list */
9300 mStorageControllers.rollback();
9301 }
9302
9303 /* rollback any changes to devices after restoring the list */
9304 if (mData->flModifications & IsModified_Storage)
9305 {
9306 StorageControllerList::const_iterator it = mStorageControllers->begin();
9307 while (it != mStorageControllers->end())
9308 {
9309 (*it)->rollback();
9310 ++it;
9311 }
9312 }
9313 }
9314
9315 mUserData.rollback();
9316
9317 mHWData.rollback();
9318
9319 if (mData->flModifications & IsModified_Storage)
9320 rollbackMedia();
9321
9322 if (mBIOSSettings)
9323 mBIOSSettings->rollback();
9324
9325 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9326 mVRDEServer->rollback();
9327
9328 if (mAudioAdapter)
9329 mAudioAdapter->rollback();
9330
9331 if (mUSBController && (mData->flModifications & IsModified_USB))
9332 mUSBController->rollback();
9333
9334 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9335 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9336 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9337
9338 if (mData->flModifications & IsModified_NetworkAdapters)
9339 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9340 if ( mNetworkAdapters[slot]
9341 && mNetworkAdapters[slot]->isModified())
9342 {
9343 mNetworkAdapters[slot]->rollback();
9344 networkAdapters[slot] = mNetworkAdapters[slot];
9345 }
9346
9347 if (mData->flModifications & IsModified_SerialPorts)
9348 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9349 if ( mSerialPorts[slot]
9350 && mSerialPorts[slot]->isModified())
9351 {
9352 mSerialPorts[slot]->rollback();
9353 serialPorts[slot] = mSerialPorts[slot];
9354 }
9355
9356 if (mData->flModifications & IsModified_ParallelPorts)
9357 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9358 if ( mParallelPorts[slot]
9359 && mParallelPorts[slot]->isModified())
9360 {
9361 mParallelPorts[slot]->rollback();
9362 parallelPorts[slot] = mParallelPorts[slot];
9363 }
9364
9365 if (aNotify)
9366 {
9367 /* inform the direct session about changes */
9368
9369 ComObjPtr<Machine> that = this;
9370 uint32_t flModifications = mData->flModifications;
9371 alock.leave();
9372
9373 if (flModifications & IsModified_SharedFolders)
9374 that->onSharedFolderChange();
9375
9376 if (flModifications & IsModified_VRDEServer)
9377 that->onVRDEServerChange(/* aRestart */ TRUE);
9378 if (flModifications & IsModified_USB)
9379 that->onUSBControllerChange();
9380
9381 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9382 if (networkAdapters[slot])
9383 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9384 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9385 if (serialPorts[slot])
9386 that->onSerialPortChange(serialPorts[slot]);
9387 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9388 if (parallelPorts[slot])
9389 that->onParallelPortChange(parallelPorts[slot]);
9390
9391 if (flModifications & IsModified_Storage)
9392 that->onStorageControllerChange();
9393 }
9394}
9395
9396/**
9397 * Commits all the changes to machine settings.
9398 *
9399 * Note that this operation is supposed to never fail.
9400 *
9401 * @note Locks this object and children for writing.
9402 */
9403void Machine::commit()
9404{
9405 AutoCaller autoCaller(this);
9406 AssertComRCReturnVoid(autoCaller.rc());
9407
9408 AutoCaller peerCaller(mPeer);
9409 AssertComRCReturnVoid(peerCaller.rc());
9410
9411 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9412
9413 /*
9414 * use safe commit to ensure Snapshot machines (that share mUserData)
9415 * will still refer to a valid memory location
9416 */
9417 mUserData.commitCopy();
9418
9419 mHWData.commit();
9420
9421 if (mMediaData.isBackedUp())
9422 commitMedia();
9423
9424 mBIOSSettings->commit();
9425 mVRDEServer->commit();
9426 mAudioAdapter->commit();
9427 mUSBController->commit();
9428
9429 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9430 mNetworkAdapters[slot]->commit();
9431 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9432 mSerialPorts[slot]->commit();
9433 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9434 mParallelPorts[slot]->commit();
9435
9436 bool commitStorageControllers = false;
9437
9438 if (mStorageControllers.isBackedUp())
9439 {
9440 mStorageControllers.commit();
9441
9442 if (mPeer)
9443 {
9444 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9445
9446 /* Commit all changes to new controllers (this will reshare data with
9447 * peers for those who have peers) */
9448 StorageControllerList *newList = new StorageControllerList();
9449 StorageControllerList::const_iterator it = mStorageControllers->begin();
9450 while (it != mStorageControllers->end())
9451 {
9452 (*it)->commit();
9453
9454 /* look if this controller has a peer device */
9455 ComObjPtr<StorageController> peer = (*it)->getPeer();
9456 if (!peer)
9457 {
9458 /* no peer means the device is a newly created one;
9459 * create a peer owning data this device share it with */
9460 peer.createObject();
9461 peer->init(mPeer, *it, true /* aReshare */);
9462 }
9463 else
9464 {
9465 /* remove peer from the old list */
9466 mPeer->mStorageControllers->remove(peer);
9467 }
9468 /* and add it to the new list */
9469 newList->push_back(peer);
9470
9471 ++it;
9472 }
9473
9474 /* uninit old peer's controllers that are left */
9475 it = mPeer->mStorageControllers->begin();
9476 while (it != mPeer->mStorageControllers->end())
9477 {
9478 (*it)->uninit();
9479 ++it;
9480 }
9481
9482 /* attach new list of controllers to our peer */
9483 mPeer->mStorageControllers.attach(newList);
9484 }
9485 else
9486 {
9487 /* we have no peer (our parent is the newly created machine);
9488 * just commit changes to devices */
9489 commitStorageControllers = true;
9490 }
9491 }
9492 else
9493 {
9494 /* the list of controllers itself is not changed,
9495 * just commit changes to controllers themselves */
9496 commitStorageControllers = true;
9497 }
9498
9499 if (commitStorageControllers)
9500 {
9501 StorageControllerList::const_iterator it = mStorageControllers->begin();
9502 while (it != mStorageControllers->end())
9503 {
9504 (*it)->commit();
9505 ++it;
9506 }
9507 }
9508
9509 if (isSessionMachine())
9510 {
9511 /* attach new data to the primary machine and reshare it */
9512 mPeer->mUserData.attach(mUserData);
9513 mPeer->mHWData.attach(mHWData);
9514 /* mMediaData is reshared by fixupMedia */
9515 // mPeer->mMediaData.attach(mMediaData);
9516 Assert(mPeer->mMediaData.data() == mMediaData.data());
9517 }
9518}
9519
9520/**
9521 * Copies all the hardware data from the given machine.
9522 *
9523 * Currently, only called when the VM is being restored from a snapshot. In
9524 * particular, this implies that the VM is not running during this method's
9525 * call.
9526 *
9527 * @note This method must be called from under this object's lock.
9528 *
9529 * @note This method doesn't call #commit(), so all data remains backed up and
9530 * unsaved.
9531 */
9532void Machine::copyFrom(Machine *aThat)
9533{
9534 AssertReturnVoid(!isSnapshotMachine());
9535 AssertReturnVoid(aThat->isSnapshotMachine());
9536
9537 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9538
9539 mHWData.assignCopy(aThat->mHWData);
9540
9541 // create copies of all shared folders (mHWData after attaching a copy
9542 // contains just references to original objects)
9543 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9544 it != mHWData->mSharedFolders.end();
9545 ++it)
9546 {
9547 ComObjPtr<SharedFolder> folder;
9548 folder.createObject();
9549 HRESULT rc = folder->initCopy(getMachine(), *it);
9550 AssertComRC(rc);
9551 *it = folder;
9552 }
9553
9554 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9555 mVRDEServer->copyFrom(aThat->mVRDEServer);
9556 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9557 mUSBController->copyFrom(aThat->mUSBController);
9558
9559 /* create private copies of all controllers */
9560 mStorageControllers.backup();
9561 mStorageControllers->clear();
9562 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9563 it != aThat->mStorageControllers->end();
9564 ++it)
9565 {
9566 ComObjPtr<StorageController> ctrl;
9567 ctrl.createObject();
9568 ctrl->initCopy(this, *it);
9569 mStorageControllers->push_back(ctrl);
9570 }
9571
9572 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9573 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9574 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9575 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9576 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9577 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9578}
9579
9580#ifdef VBOX_WITH_RESOURCE_USAGE_API
9581
9582void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9583{
9584 AssertReturnVoid(isWriteLockOnCurrentThread());
9585 AssertPtrReturnVoid(aCollector);
9586
9587 pm::CollectorHAL *hal = aCollector->getHAL();
9588 /* Create sub metrics */
9589 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9590 "Percentage of processor time spent in user mode by the VM process.");
9591 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9592 "Percentage of processor time spent in kernel mode by the VM process.");
9593 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9594 "Size of resident portion of VM process in memory.");
9595 /* Create and register base metrics */
9596 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9597 cpuLoadUser, cpuLoadKernel);
9598 aCollector->registerBaseMetric(cpuLoad);
9599 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9600 ramUsageUsed);
9601 aCollector->registerBaseMetric(ramUsage);
9602
9603 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9604 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9605 new pm::AggregateAvg()));
9606 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9607 new pm::AggregateMin()));
9608 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9609 new pm::AggregateMax()));
9610 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9611 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9612 new pm::AggregateAvg()));
9613 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9614 new pm::AggregateMin()));
9615 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9616 new pm::AggregateMax()));
9617
9618 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9619 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9620 new pm::AggregateAvg()));
9621 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9622 new pm::AggregateMin()));
9623 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9624 new pm::AggregateMax()));
9625
9626
9627 /* Guest metrics */
9628 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9629
9630 /* Create sub metrics */
9631 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9632 "Percentage of processor time spent in user mode as seen by the guest.");
9633 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9634 "Percentage of processor time spent in kernel mode as seen by the guest.");
9635 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9636 "Percentage of processor time spent idling as seen by the guest.");
9637
9638 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9639 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9640 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9641 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9642 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9643 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9644
9645 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9646
9647 /* Create and register base metrics */
9648 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9649 aCollector->registerBaseMetric(guestCpuLoad);
9650
9651 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9652 guestMemCache, guestPagedTotal);
9653 aCollector->registerBaseMetric(guestCpuMem);
9654
9655 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9656 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9657 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9658 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9659
9660 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9661 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9662 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9663 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9664
9665 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9666 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9667 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9668 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9669
9670 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9671 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9672 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9673 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9674
9675 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9676 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9677 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9678 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9679
9680 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9681 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9682 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9683 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9684
9685 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9686 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9687 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9688 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9689
9690 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9691 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9692 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9693 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9694
9695 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9696 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9697 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9698 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9699}
9700
9701void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9702{
9703 AssertReturnVoid(isWriteLockOnCurrentThread());
9704
9705 if (aCollector)
9706 {
9707 aCollector->unregisterMetricsFor(aMachine);
9708 aCollector->unregisterBaseMetricsFor(aMachine);
9709 }
9710
9711 if (mGuestHAL)
9712 {
9713 delete mGuestHAL;
9714 mGuestHAL = NULL;
9715 }
9716}
9717
9718#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9719
9720
9721////////////////////////////////////////////////////////////////////////////////
9722
9723DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9724
9725HRESULT SessionMachine::FinalConstruct()
9726{
9727 LogFlowThisFunc(("\n"));
9728
9729#if defined(RT_OS_WINDOWS)
9730 mIPCSem = NULL;
9731#elif defined(RT_OS_OS2)
9732 mIPCSem = NULLHANDLE;
9733#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9734 mIPCSem = -1;
9735#else
9736# error "Port me!"
9737#endif
9738
9739 return S_OK;
9740}
9741
9742void SessionMachine::FinalRelease()
9743{
9744 LogFlowThisFunc(("\n"));
9745
9746 uninit(Uninit::Unexpected);
9747}
9748
9749/**
9750 * @note Must be called only by Machine::openSession() from its own write lock.
9751 */
9752HRESULT SessionMachine::init(Machine *aMachine)
9753{
9754 LogFlowThisFuncEnter();
9755 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9756
9757 AssertReturn(aMachine, E_INVALIDARG);
9758
9759 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9760
9761 /* Enclose the state transition NotReady->InInit->Ready */
9762 AutoInitSpan autoInitSpan(this);
9763 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9764
9765 /* create the interprocess semaphore */
9766#if defined(RT_OS_WINDOWS)
9767 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9768 for (size_t i = 0; i < mIPCSemName.length(); i++)
9769 if (mIPCSemName.raw()[i] == '\\')
9770 mIPCSemName.raw()[i] = '/';
9771 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
9772 ComAssertMsgRet(mIPCSem,
9773 ("Cannot create IPC mutex '%ls', err=%d",
9774 mIPCSemName.raw(), ::GetLastError()),
9775 E_FAIL);
9776#elif defined(RT_OS_OS2)
9777 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9778 aMachine->mData->mUuid.raw());
9779 mIPCSemName = ipcSem;
9780 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
9781 ComAssertMsgRet(arc == NO_ERROR,
9782 ("Cannot create IPC mutex '%s', arc=%ld",
9783 ipcSem.c_str(), arc),
9784 E_FAIL);
9785#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9786# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9787# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9788 /** @todo Check that this still works correctly. */
9789 AssertCompileSize(key_t, 8);
9790# else
9791 AssertCompileSize(key_t, 4);
9792# endif
9793 key_t key;
9794 mIPCSem = -1;
9795 mIPCKey = "0";
9796 for (uint32_t i = 0; i < 1 << 24; i++)
9797 {
9798 key = ((uint32_t)'V' << 24) | i;
9799 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9800 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9801 {
9802 mIPCSem = sem;
9803 if (sem >= 0)
9804 mIPCKey = BstrFmt("%u", key);
9805 break;
9806 }
9807 }
9808# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9809 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9810 char *pszSemName = NULL;
9811 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9812 key_t key = ::ftok(pszSemName, 'V');
9813 RTStrFree(pszSemName);
9814
9815 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9816# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9817
9818 int errnoSave = errno;
9819 if (mIPCSem < 0 && errnoSave == ENOSYS)
9820 {
9821 setError(E_FAIL,
9822 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9823 "support for SysV IPC. Check the host kernel configuration for "
9824 "CONFIG_SYSVIPC=y"));
9825 return E_FAIL;
9826 }
9827 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9828 * the IPC semaphores */
9829 if (mIPCSem < 0 && errnoSave == ENOSPC)
9830 {
9831#ifdef RT_OS_LINUX
9832 setError(E_FAIL,
9833 tr("Cannot create IPC semaphore because the system limit for the "
9834 "maximum number of semaphore sets (SEMMNI), or the system wide "
9835 "maximum number of semaphores (SEMMNS) would be exceeded. The "
9836 "current set of SysV IPC semaphores can be determined from "
9837 "the file /proc/sysvipc/sem"));
9838#else
9839 setError(E_FAIL,
9840 tr("Cannot create IPC semaphore because the system-imposed limit "
9841 "on the maximum number of allowed semaphores or semaphore "
9842 "identifiers system-wide would be exceeded"));
9843#endif
9844 return E_FAIL;
9845 }
9846 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9847 E_FAIL);
9848 /* set the initial value to 1 */
9849 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9850 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9851 E_FAIL);
9852#else
9853# error "Port me!"
9854#endif
9855
9856 /* memorize the peer Machine */
9857 unconst(mPeer) = aMachine;
9858 /* share the parent pointer */
9859 unconst(mParent) = aMachine->mParent;
9860
9861 /* take the pointers to data to share */
9862 mData.share(aMachine->mData);
9863 mSSData.share(aMachine->mSSData);
9864
9865 mUserData.share(aMachine->mUserData);
9866 mHWData.share(aMachine->mHWData);
9867 mMediaData.share(aMachine->mMediaData);
9868
9869 mStorageControllers.allocate();
9870 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9871 it != aMachine->mStorageControllers->end();
9872 ++it)
9873 {
9874 ComObjPtr<StorageController> ctl;
9875 ctl.createObject();
9876 ctl->init(this, *it);
9877 mStorageControllers->push_back(ctl);
9878 }
9879
9880 unconst(mBIOSSettings).createObject();
9881 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9882 /* create another VRDEServer object that will be mutable */
9883 unconst(mVRDEServer).createObject();
9884 mVRDEServer->init(this, aMachine->mVRDEServer);
9885 /* create another audio adapter object that will be mutable */
9886 unconst(mAudioAdapter).createObject();
9887 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9888 /* create a list of serial ports that will be mutable */
9889 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9890 {
9891 unconst(mSerialPorts[slot]).createObject();
9892 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9893 }
9894 /* create a list of parallel ports that will be mutable */
9895 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9896 {
9897 unconst(mParallelPorts[slot]).createObject();
9898 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9899 }
9900 /* create another USB controller object that will be mutable */
9901 unconst(mUSBController).createObject();
9902 mUSBController->init(this, aMachine->mUSBController);
9903
9904 /* create a list of network adapters that will be mutable */
9905 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9906 {
9907 unconst(mNetworkAdapters[slot]).createObject();
9908 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9909 }
9910
9911 /* default is to delete saved state on Saved -> PoweredOff transition */
9912 mRemoveSavedState = true;
9913
9914 /* Confirm a successful initialization when it's the case */
9915 autoInitSpan.setSucceeded();
9916
9917 LogFlowThisFuncLeave();
9918 return S_OK;
9919}
9920
9921/**
9922 * Uninitializes this session object. If the reason is other than
9923 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9924 *
9925 * @param aReason uninitialization reason
9926 *
9927 * @note Locks mParent + this object for writing.
9928 */
9929void SessionMachine::uninit(Uninit::Reason aReason)
9930{
9931 LogFlowThisFuncEnter();
9932 LogFlowThisFunc(("reason=%d\n", aReason));
9933
9934 /*
9935 * Strongly reference ourselves to prevent this object deletion after
9936 * mData->mSession.mMachine.setNull() below (which can release the last
9937 * reference and call the destructor). Important: this must be done before
9938 * accessing any members (and before AutoUninitSpan that does it as well).
9939 * This self reference will be released as the very last step on return.
9940 */
9941 ComObjPtr<SessionMachine> selfRef = this;
9942
9943 /* Enclose the state transition Ready->InUninit->NotReady */
9944 AutoUninitSpan autoUninitSpan(this);
9945 if (autoUninitSpan.uninitDone())
9946 {
9947 LogFlowThisFunc(("Already uninitialized\n"));
9948 LogFlowThisFuncLeave();
9949 return;
9950 }
9951
9952 if (autoUninitSpan.initFailed())
9953 {
9954 /* We've been called by init() because it's failed. It's not really
9955 * necessary (nor it's safe) to perform the regular uninit sequence
9956 * below, the following is enough.
9957 */
9958 LogFlowThisFunc(("Initialization failed.\n"));
9959#if defined(RT_OS_WINDOWS)
9960 if (mIPCSem)
9961 ::CloseHandle(mIPCSem);
9962 mIPCSem = NULL;
9963#elif defined(RT_OS_OS2)
9964 if (mIPCSem != NULLHANDLE)
9965 ::DosCloseMutexSem(mIPCSem);
9966 mIPCSem = NULLHANDLE;
9967#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9968 if (mIPCSem >= 0)
9969 ::semctl(mIPCSem, 0, IPC_RMID);
9970 mIPCSem = -1;
9971# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9972 mIPCKey = "0";
9973# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9974#else
9975# error "Port me!"
9976#endif
9977 uninitDataAndChildObjects();
9978 mData.free();
9979 unconst(mParent) = NULL;
9980 unconst(mPeer) = NULL;
9981 LogFlowThisFuncLeave();
9982 return;
9983 }
9984
9985 MachineState_T lastState;
9986 {
9987 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9988 lastState = mData->mMachineState;
9989 }
9990 NOREF(lastState);
9991
9992#ifdef VBOX_WITH_USB
9993 // release all captured USB devices, but do this before requesting the locks below
9994 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9995 {
9996 /* Console::captureUSBDevices() is called in the VM process only after
9997 * setting the machine state to Starting or Restoring.
9998 * Console::detachAllUSBDevices() will be called upon successful
9999 * termination. So, we need to release USB devices only if there was
10000 * an abnormal termination of a running VM.
10001 *
10002 * This is identical to SessionMachine::DetachAllUSBDevices except
10003 * for the aAbnormal argument. */
10004 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10005 AssertComRC(rc);
10006 NOREF(rc);
10007
10008 USBProxyService *service = mParent->host()->usbProxyService();
10009 if (service)
10010 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10011 }
10012#endif /* VBOX_WITH_USB */
10013
10014 // we need to lock this object in uninit() because the lock is shared
10015 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10016 // and others need mParent lock, and USB needs host lock.
10017 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10018
10019 // Trigger async cleanup tasks, avoid doing things here which are not
10020 // vital to be done immediately and maybe need more locks. This calls
10021 // Machine::unregisterMetrics().
10022 mParent->onMachineUninit(mPeer);
10023
10024 if (aReason == Uninit::Abnormal)
10025 {
10026 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10027 Global::IsOnlineOrTransient(lastState)));
10028
10029 /* reset the state to Aborted */
10030 if (mData->mMachineState != MachineState_Aborted)
10031 setMachineState(MachineState_Aborted);
10032 }
10033
10034 // any machine settings modified?
10035 if (mData->flModifications)
10036 {
10037 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10038 rollback(false /* aNotify */);
10039 }
10040
10041 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
10042 if (!mSnapshotData.mStateFilePath.isEmpty())
10043 {
10044 LogWarningThisFunc(("canceling failed save state request!\n"));
10045 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10046 }
10047 else if (!mSnapshotData.mSnapshot.isNull())
10048 {
10049 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10050
10051 /* delete all differencing hard disks created (this will also attach
10052 * their parents back by rolling back mMediaData) */
10053 rollbackMedia();
10054 /* delete the saved state file (it might have been already created) */
10055 if (mSnapshotData.mSnapshot->stateFilePath().length())
10056 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
10057
10058 mSnapshotData.mSnapshot->uninit();
10059 }
10060
10061 if (!mData->mSession.mType.isEmpty())
10062 {
10063 /* mType is not null when this machine's process has been started by
10064 * Machine::launchVMProcess(), therefore it is our child. We
10065 * need to queue the PID to reap the process (and avoid zombies on
10066 * Linux). */
10067 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10068 mParent->addProcessToReap(mData->mSession.mPid);
10069 }
10070
10071 mData->mSession.mPid = NIL_RTPROCESS;
10072
10073 if (aReason == Uninit::Unexpected)
10074 {
10075 /* Uninitialization didn't come from #checkForDeath(), so tell the
10076 * client watcher thread to update the set of machines that have open
10077 * sessions. */
10078 mParent->updateClientWatcher();
10079 }
10080
10081 /* uninitialize all remote controls */
10082 if (mData->mSession.mRemoteControls.size())
10083 {
10084 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10085 mData->mSession.mRemoteControls.size()));
10086
10087 Data::Session::RemoteControlList::iterator it =
10088 mData->mSession.mRemoteControls.begin();
10089 while (it != mData->mSession.mRemoteControls.end())
10090 {
10091 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10092 HRESULT rc = (*it)->Uninitialize();
10093 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10094 if (FAILED(rc))
10095 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10096 ++it;
10097 }
10098 mData->mSession.mRemoteControls.clear();
10099 }
10100
10101 /*
10102 * An expected uninitialization can come only from #checkForDeath().
10103 * Otherwise it means that something's gone really wrong (for example,
10104 * the Session implementation has released the VirtualBox reference
10105 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10106 * etc). However, it's also possible, that the client releases the IPC
10107 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10108 * but the VirtualBox release event comes first to the server process.
10109 * This case is practically possible, so we should not assert on an
10110 * unexpected uninit, just log a warning.
10111 */
10112
10113 if ((aReason == Uninit::Unexpected))
10114 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10115
10116 if (aReason != Uninit::Normal)
10117 {
10118 mData->mSession.mDirectControl.setNull();
10119 }
10120 else
10121 {
10122 /* this must be null here (see #OnSessionEnd()) */
10123 Assert(mData->mSession.mDirectControl.isNull());
10124 Assert(mData->mSession.mState == SessionState_Unlocking);
10125 Assert(!mData->mSession.mProgress.isNull());
10126 }
10127 if (mData->mSession.mProgress)
10128 {
10129 if (aReason == Uninit::Normal)
10130 mData->mSession.mProgress->notifyComplete(S_OK);
10131 else
10132 mData->mSession.mProgress->notifyComplete(E_FAIL,
10133 COM_IIDOF(ISession),
10134 getComponentName(),
10135 tr("The VM session was aborted"));
10136 mData->mSession.mProgress.setNull();
10137 }
10138
10139 /* remove the association between the peer machine and this session machine */
10140 Assert( (SessionMachine*)mData->mSession.mMachine == this
10141 || aReason == Uninit::Unexpected);
10142
10143 /* reset the rest of session data */
10144 mData->mSession.mMachine.setNull();
10145 mData->mSession.mState = SessionState_Unlocked;
10146 mData->mSession.mType.setNull();
10147
10148 /* close the interprocess semaphore before leaving the exclusive lock */
10149#if defined(RT_OS_WINDOWS)
10150 if (mIPCSem)
10151 ::CloseHandle(mIPCSem);
10152 mIPCSem = NULL;
10153#elif defined(RT_OS_OS2)
10154 if (mIPCSem != NULLHANDLE)
10155 ::DosCloseMutexSem(mIPCSem);
10156 mIPCSem = NULLHANDLE;
10157#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10158 if (mIPCSem >= 0)
10159 ::semctl(mIPCSem, 0, IPC_RMID);
10160 mIPCSem = -1;
10161# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10162 mIPCKey = "0";
10163# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10164#else
10165# error "Port me!"
10166#endif
10167
10168 /* fire an event */
10169 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10170
10171 uninitDataAndChildObjects();
10172
10173 /* free the essential data structure last */
10174 mData.free();
10175
10176#if 1 /** @todo Please review this change! (bird) */
10177 /* drop the exclusive lock before setting the below two to NULL */
10178 multilock.release();
10179#else
10180 /* leave the exclusive lock before setting the below two to NULL */
10181 multilock.leave();
10182#endif
10183
10184 unconst(mParent) = NULL;
10185 unconst(mPeer) = NULL;
10186
10187 LogFlowThisFuncLeave();
10188}
10189
10190// util::Lockable interface
10191////////////////////////////////////////////////////////////////////////////////
10192
10193/**
10194 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10195 * with the primary Machine instance (mPeer).
10196 */
10197RWLockHandle *SessionMachine::lockHandle() const
10198{
10199 AssertReturn(mPeer != NULL, NULL);
10200 return mPeer->lockHandle();
10201}
10202
10203// IInternalMachineControl methods
10204////////////////////////////////////////////////////////////////////////////////
10205
10206/**
10207 * @note Locks this object for writing.
10208 */
10209STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10210{
10211 AutoCaller autoCaller(this);
10212 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10213
10214 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10215
10216 mRemoveSavedState = aRemove;
10217
10218 return S_OK;
10219}
10220
10221/**
10222 * @note Locks the same as #setMachineState() does.
10223 */
10224STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10225{
10226 return setMachineState(aMachineState);
10227}
10228
10229/**
10230 * @note Locks this object for reading.
10231 */
10232STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10233{
10234 AutoCaller autoCaller(this);
10235 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10236
10237 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10238
10239#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10240 mIPCSemName.cloneTo(aId);
10241 return S_OK;
10242#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10243# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10244 mIPCKey.cloneTo(aId);
10245# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10246 mData->m_strConfigFileFull.cloneTo(aId);
10247# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10248 return S_OK;
10249#else
10250# error "Port me!"
10251#endif
10252}
10253
10254/**
10255 * @note Locks this object for writing.
10256 */
10257STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10258{
10259 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10260 AutoCaller autoCaller(this);
10261 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10262
10263 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10264
10265 if (mData->mSession.mState != SessionState_Locked)
10266 return VBOX_E_INVALID_OBJECT_STATE;
10267
10268 if (!mData->mSession.mProgress.isNull())
10269 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10270
10271 LogFlowThisFunc(("returns S_OK.\n"));
10272 return S_OK;
10273}
10274
10275
10276/**
10277 * @note Locks this object for writing.
10278 */
10279STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10280{
10281 AutoCaller autoCaller(this);
10282 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10283
10284 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10285
10286 if (mData->mSession.mState != SessionState_Locked)
10287 return VBOX_E_INVALID_OBJECT_STATE;
10288
10289 /* Finalize the openRemoteSession progress object. */
10290 if (mData->mSession.mProgress)
10291 {
10292 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10293 mData->mSession.mProgress.setNull();
10294 }
10295
10296 if (SUCCEEDED((HRESULT)iResult))
10297 {
10298#ifdef VBOX_WITH_RESOURCE_USAGE_API
10299 /* The VM has been powered up successfully, so it makes sense
10300 * now to offer the performance metrics for a running machine
10301 * object. Doing it earlier wouldn't be safe. */
10302 registerMetrics(mParent->performanceCollector(), mPeer,
10303 mData->mSession.mPid);
10304#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10305 }
10306
10307 return S_OK;
10308}
10309
10310/**
10311 * Goes through the USB filters of the given machine to see if the given
10312 * device matches any filter or not.
10313 *
10314 * @note Locks the same as USBController::hasMatchingFilter() does.
10315 */
10316STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10317 BOOL *aMatched,
10318 ULONG *aMaskedIfs)
10319{
10320 LogFlowThisFunc(("\n"));
10321
10322 CheckComArgNotNull(aUSBDevice);
10323 CheckComArgOutPointerValid(aMatched);
10324
10325 AutoCaller autoCaller(this);
10326 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10327
10328#ifdef VBOX_WITH_USB
10329 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10330#else
10331 NOREF(aUSBDevice);
10332 NOREF(aMaskedIfs);
10333 *aMatched = FALSE;
10334#endif
10335
10336 return S_OK;
10337}
10338
10339/**
10340 * @note Locks the same as Host::captureUSBDevice() does.
10341 */
10342STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10343{
10344 LogFlowThisFunc(("\n"));
10345
10346 AutoCaller autoCaller(this);
10347 AssertComRCReturnRC(autoCaller.rc());
10348
10349#ifdef VBOX_WITH_USB
10350 /* if captureDeviceForVM() fails, it must have set extended error info */
10351 MultiResult rc = mParent->host()->checkUSBProxyService();
10352 if (FAILED(rc)) return rc;
10353
10354 USBProxyService *service = mParent->host()->usbProxyService();
10355 AssertReturn(service, E_FAIL);
10356 return service->captureDeviceForVM(this, Guid(aId).ref());
10357#else
10358 NOREF(aId);
10359 return E_NOTIMPL;
10360#endif
10361}
10362
10363/**
10364 * @note Locks the same as Host::detachUSBDevice() does.
10365 */
10366STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10367{
10368 LogFlowThisFunc(("\n"));
10369
10370 AutoCaller autoCaller(this);
10371 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10372
10373#ifdef VBOX_WITH_USB
10374 USBProxyService *service = mParent->host()->usbProxyService();
10375 AssertReturn(service, E_FAIL);
10376 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10377#else
10378 NOREF(aId);
10379 NOREF(aDone);
10380 return E_NOTIMPL;
10381#endif
10382}
10383
10384/**
10385 * Inserts all machine filters to the USB proxy service and then calls
10386 * Host::autoCaptureUSBDevices().
10387 *
10388 * Called by Console from the VM process upon VM startup.
10389 *
10390 * @note Locks what called methods lock.
10391 */
10392STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10393{
10394 LogFlowThisFunc(("\n"));
10395
10396 AutoCaller autoCaller(this);
10397 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10398
10399#ifdef VBOX_WITH_USB
10400 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10401 AssertComRC(rc);
10402 NOREF(rc);
10403
10404 USBProxyService *service = mParent->host()->usbProxyService();
10405 AssertReturn(service, E_FAIL);
10406 return service->autoCaptureDevicesForVM(this);
10407#else
10408 return S_OK;
10409#endif
10410}
10411
10412/**
10413 * Removes all machine filters from the USB proxy service and then calls
10414 * Host::detachAllUSBDevices().
10415 *
10416 * Called by Console from the VM process upon normal VM termination or by
10417 * SessionMachine::uninit() upon abnormal VM termination (from under the
10418 * Machine/SessionMachine lock).
10419 *
10420 * @note Locks what called methods lock.
10421 */
10422STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10423{
10424 LogFlowThisFunc(("\n"));
10425
10426 AutoCaller autoCaller(this);
10427 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10428
10429#ifdef VBOX_WITH_USB
10430 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10431 AssertComRC(rc);
10432 NOREF(rc);
10433
10434 USBProxyService *service = mParent->host()->usbProxyService();
10435 AssertReturn(service, E_FAIL);
10436 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10437#else
10438 NOREF(aDone);
10439 return S_OK;
10440#endif
10441}
10442
10443/**
10444 * @note Locks this object for writing.
10445 */
10446STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10447 IProgress **aProgress)
10448{
10449 LogFlowThisFuncEnter();
10450
10451 AssertReturn(aSession, E_INVALIDARG);
10452 AssertReturn(aProgress, E_INVALIDARG);
10453
10454 AutoCaller autoCaller(this);
10455
10456 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10457 /*
10458 * We don't assert below because it might happen that a non-direct session
10459 * informs us it is closed right after we've been uninitialized -- it's ok.
10460 */
10461 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10462
10463 /* get IInternalSessionControl interface */
10464 ComPtr<IInternalSessionControl> control(aSession);
10465
10466 ComAssertRet(!control.isNull(), E_INVALIDARG);
10467
10468 /* Creating a Progress object requires the VirtualBox lock, and
10469 * thus locking it here is required by the lock order rules. */
10470 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10471
10472 if (control == mData->mSession.mDirectControl)
10473 {
10474 ComAssertRet(aProgress, E_POINTER);
10475
10476 /* The direct session is being normally closed by the client process
10477 * ----------------------------------------------------------------- */
10478
10479 /* go to the closing state (essential for all open*Session() calls and
10480 * for #checkForDeath()) */
10481 Assert(mData->mSession.mState == SessionState_Locked);
10482 mData->mSession.mState = SessionState_Unlocking;
10483
10484 /* set direct control to NULL to release the remote instance */
10485 mData->mSession.mDirectControl.setNull();
10486 LogFlowThisFunc(("Direct control is set to NULL\n"));
10487
10488 if (mData->mSession.mProgress)
10489 {
10490 /* finalize the progress, someone might wait if a frontend
10491 * closes the session before powering on the VM. */
10492 mData->mSession.mProgress->notifyComplete(E_FAIL,
10493 COM_IIDOF(ISession),
10494 getComponentName(),
10495 tr("The VM session was closed before any attempt to power it on"));
10496 mData->mSession.mProgress.setNull();
10497 }
10498
10499 /* Create the progress object the client will use to wait until
10500 * #checkForDeath() is called to uninitialize this session object after
10501 * it releases the IPC semaphore.
10502 * Note! Because we're "reusing" mProgress here, this must be a proxy
10503 * object just like for openRemoteSession. */
10504 Assert(mData->mSession.mProgress.isNull());
10505 ComObjPtr<ProgressProxy> progress;
10506 progress.createObject();
10507 ComPtr<IUnknown> pPeer(mPeer);
10508 progress->init(mParent, pPeer,
10509 Bstr(tr("Closing session")).raw(),
10510 FALSE /* aCancelable */);
10511 progress.queryInterfaceTo(aProgress);
10512 mData->mSession.mProgress = progress;
10513 }
10514 else
10515 {
10516 /* the remote session is being normally closed */
10517 Data::Session::RemoteControlList::iterator it =
10518 mData->mSession.mRemoteControls.begin();
10519 while (it != mData->mSession.mRemoteControls.end())
10520 {
10521 if (control == *it)
10522 break;
10523 ++it;
10524 }
10525 BOOL found = it != mData->mSession.mRemoteControls.end();
10526 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10527 E_INVALIDARG);
10528 mData->mSession.mRemoteControls.remove(*it);
10529 }
10530
10531 LogFlowThisFuncLeave();
10532 return S_OK;
10533}
10534
10535/**
10536 * @note Locks this object for writing.
10537 */
10538STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
10539{
10540 LogFlowThisFuncEnter();
10541
10542 CheckComArgOutPointerValid(aProgress);
10543 CheckComArgOutPointerValid(aStateFilePath);
10544
10545 AutoCaller autoCaller(this);
10546 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10547
10548 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10549
10550 AssertReturn( mData->mMachineState == MachineState_Paused
10551 && mSnapshotData.mLastState == MachineState_Null
10552 && mSnapshotData.mStateFilePath.isEmpty(),
10553 E_FAIL);
10554
10555 /* create a progress object to track operation completion */
10556 ComObjPtr<Progress> pProgress;
10557 pProgress.createObject();
10558 pProgress->init(getVirtualBox(),
10559 static_cast<IMachine *>(this) /* aInitiator */,
10560 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
10561 FALSE /* aCancelable */);
10562
10563 Bstr stateFilePath;
10564 /* stateFilePath is null when the machine is not running */
10565 if (mData->mMachineState == MachineState_Paused)
10566 {
10567 Utf8Str strFullSnapshotFolder;
10568 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10569 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10570 strFullSnapshotFolder.c_str(),
10571 RTPATH_DELIMITER,
10572 mData->mUuid.raw());
10573 }
10574
10575 /* fill in the snapshot data */
10576 mSnapshotData.mLastState = mData->mMachineState;
10577 mSnapshotData.mStateFilePath = stateFilePath;
10578 mSnapshotData.mProgress = pProgress;
10579
10580 /* set the state to Saving (this is expected by Console::SaveState()) */
10581 setMachineState(MachineState_Saving);
10582
10583 stateFilePath.cloneTo(aStateFilePath);
10584 pProgress.queryInterfaceTo(aProgress);
10585
10586 return S_OK;
10587}
10588
10589/**
10590 * @note Locks mParent + this object for writing.
10591 */
10592STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
10593{
10594 LogFlowThisFunc(("\n"));
10595
10596 AutoCaller autoCaller(this);
10597 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10598
10599 /* endSavingState() need mParent lock */
10600 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10601
10602 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
10603 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
10604 && mSnapshotData.mLastState != MachineState_Null
10605 && !mSnapshotData.mStateFilePath.isEmpty(),
10606 E_FAIL);
10607
10608 /*
10609 * On failure, set the state to the state we had when BeginSavingState()
10610 * was called (this is expected by Console::SaveState() and the associated
10611 * task). On success the VM process already changed the state to
10612 * MachineState_Saved, so no need to do anything.
10613 */
10614 if (FAILED(iResult))
10615 setMachineState(mSnapshotData.mLastState);
10616
10617 return endSavingState(iResult, aErrMsg);
10618}
10619
10620/**
10621 * @note Locks this object for writing.
10622 */
10623STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10624{
10625 LogFlowThisFunc(("\n"));
10626
10627 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10628
10629 AutoCaller autoCaller(this);
10630 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10631
10632 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10633
10634 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10635 || mData->mMachineState == MachineState_Teleported
10636 || mData->mMachineState == MachineState_Aborted
10637 , E_FAIL); /** @todo setError. */
10638
10639 Utf8Str stateFilePathFull = aSavedStateFile;
10640 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10641 if (RT_FAILURE(vrc))
10642 return setError(VBOX_E_FILE_ERROR,
10643 tr("Invalid saved state file path '%ls' (%Rrc)"),
10644 aSavedStateFile,
10645 vrc);
10646
10647 mSSData->mStateFilePath = stateFilePathFull;
10648
10649 /* The below setMachineState() will detect the state transition and will
10650 * update the settings file */
10651
10652 return setMachineState(MachineState_Saved);
10653}
10654
10655STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10656 ComSafeArrayOut(BSTR, aValues),
10657 ComSafeArrayOut(LONG64, aTimestamps),
10658 ComSafeArrayOut(BSTR, aFlags))
10659{
10660 LogFlowThisFunc(("\n"));
10661
10662#ifdef VBOX_WITH_GUEST_PROPS
10663 using namespace guestProp;
10664
10665 AutoCaller autoCaller(this);
10666 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10667
10668 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10669
10670 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10671 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10672 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10673 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10674
10675 size_t cEntries = mHWData->mGuestProperties.size();
10676 com::SafeArray<BSTR> names(cEntries);
10677 com::SafeArray<BSTR> values(cEntries);
10678 com::SafeArray<LONG64> timestamps(cEntries);
10679 com::SafeArray<BSTR> flags(cEntries);
10680 unsigned i = 0;
10681 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10682 it != mHWData->mGuestProperties.end();
10683 ++it)
10684 {
10685 char szFlags[MAX_FLAGS_LEN + 1];
10686 it->strName.cloneTo(&names[i]);
10687 it->strValue.cloneTo(&values[i]);
10688 timestamps[i] = it->mTimestamp;
10689 /* If it is NULL, keep it NULL. */
10690 if (it->mFlags)
10691 {
10692 writeFlags(it->mFlags, szFlags);
10693 Bstr(szFlags).cloneTo(&flags[i]);
10694 }
10695 else
10696 flags[i] = NULL;
10697 ++i;
10698 }
10699 names.detachTo(ComSafeArrayOutArg(aNames));
10700 values.detachTo(ComSafeArrayOutArg(aValues));
10701 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10702 flags.detachTo(ComSafeArrayOutArg(aFlags));
10703 return S_OK;
10704#else
10705 ReturnComNotImplemented();
10706#endif
10707}
10708
10709STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10710 IN_BSTR aValue,
10711 LONG64 aTimestamp,
10712 IN_BSTR aFlags)
10713{
10714 LogFlowThisFunc(("\n"));
10715
10716#ifdef VBOX_WITH_GUEST_PROPS
10717 using namespace guestProp;
10718
10719 CheckComArgStrNotEmptyOrNull(aName);
10720 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10721 return E_POINTER; /* aValue can be NULL to indicate deletion */
10722
10723 try
10724 {
10725 /*
10726 * Convert input up front.
10727 */
10728 Utf8Str utf8Name(aName);
10729 uint32_t fFlags = NILFLAG;
10730 if (aFlags)
10731 {
10732 Utf8Str utf8Flags(aFlags);
10733 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
10734 AssertRCReturn(vrc, E_INVALIDARG);
10735 }
10736
10737 /*
10738 * Now grab the object lock, validate the state and do the update.
10739 */
10740 AutoCaller autoCaller(this);
10741 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10742
10743 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10744
10745 switch (mData->mMachineState)
10746 {
10747 case MachineState_Paused:
10748 case MachineState_Running:
10749 case MachineState_Teleporting:
10750 case MachineState_TeleportingPausedVM:
10751 case MachineState_LiveSnapshotting:
10752 case MachineState_DeletingSnapshotOnline:
10753 case MachineState_DeletingSnapshotPaused:
10754 case MachineState_Saving:
10755 break;
10756
10757 default:
10758#ifndef DEBUG_sunlover
10759 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10760 VBOX_E_INVALID_VM_STATE);
10761#else
10762 return VBOX_E_INVALID_VM_STATE;
10763#endif
10764 }
10765
10766 setModified(IsModified_MachineData);
10767 mHWData.backup();
10768
10769 /** @todo r=bird: The careful memory handling doesn't work out here because
10770 * the catch block won't undo any damage we've done. So, if push_back throws
10771 * bad_alloc then you've lost the value.
10772 *
10773 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10774 * since values that changes actually bubbles to the end of the list. Using
10775 * something that has an efficient lookup and can tolerate a bit of updates
10776 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10777 * combination of RTStrCache (for sharing names and getting uniqueness into
10778 * the bargain) and hash/tree is another. */
10779 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10780 iter != mHWData->mGuestProperties.end();
10781 ++iter)
10782 if (utf8Name == iter->strName)
10783 {
10784 mHWData->mGuestProperties.erase(iter);
10785 mData->mGuestPropertiesModified = TRUE;
10786 break;
10787 }
10788 if (aValue != NULL)
10789 {
10790 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10791 mHWData->mGuestProperties.push_back(property);
10792 mData->mGuestPropertiesModified = TRUE;
10793 }
10794
10795 /*
10796 * Send a callback notification if appropriate
10797 */
10798 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10799 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
10800 RTSTR_MAX,
10801 utf8Name.c_str(),
10802 RTSTR_MAX, NULL)
10803 )
10804 {
10805 alock.leave();
10806
10807 mParent->onGuestPropertyChange(mData->mUuid,
10808 aName,
10809 aValue,
10810 aFlags);
10811 }
10812 }
10813 catch (...)
10814 {
10815 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10816 }
10817 return S_OK;
10818#else
10819 ReturnComNotImplemented();
10820#endif
10821}
10822
10823// public methods only for internal purposes
10824/////////////////////////////////////////////////////////////////////////////
10825
10826/**
10827 * Called from the client watcher thread to check for expected or unexpected
10828 * death of the client process that has a direct session to this machine.
10829 *
10830 * On Win32 and on OS/2, this method is called only when we've got the
10831 * mutex (i.e. the client has either died or terminated normally) so it always
10832 * returns @c true (the client is terminated, the session machine is
10833 * uninitialized).
10834 *
10835 * On other platforms, the method returns @c true if the client process has
10836 * terminated normally or abnormally and the session machine was uninitialized,
10837 * and @c false if the client process is still alive.
10838 *
10839 * @note Locks this object for writing.
10840 */
10841bool SessionMachine::checkForDeath()
10842{
10843 Uninit::Reason reason;
10844 bool terminated = false;
10845
10846 /* Enclose autoCaller with a block because calling uninit() from under it
10847 * will deadlock. */
10848 {
10849 AutoCaller autoCaller(this);
10850 if (!autoCaller.isOk())
10851 {
10852 /* return true if not ready, to cause the client watcher to exclude
10853 * the corresponding session from watching */
10854 LogFlowThisFunc(("Already uninitialized!\n"));
10855 return true;
10856 }
10857
10858 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10859
10860 /* Determine the reason of death: if the session state is Closing here,
10861 * everything is fine. Otherwise it means that the client did not call
10862 * OnSessionEnd() before it released the IPC semaphore. This may happen
10863 * either because the client process has abnormally terminated, or
10864 * because it simply forgot to call ISession::Close() before exiting. We
10865 * threat the latter also as an abnormal termination (see
10866 * Session::uninit() for details). */
10867 reason = mData->mSession.mState == SessionState_Unlocking ?
10868 Uninit::Normal :
10869 Uninit::Abnormal;
10870
10871#if defined(RT_OS_WINDOWS)
10872
10873 AssertMsg(mIPCSem, ("semaphore must be created"));
10874
10875 /* release the IPC mutex */
10876 ::ReleaseMutex(mIPCSem);
10877
10878 terminated = true;
10879
10880#elif defined(RT_OS_OS2)
10881
10882 AssertMsg(mIPCSem, ("semaphore must be created"));
10883
10884 /* release the IPC mutex */
10885 ::DosReleaseMutexSem(mIPCSem);
10886
10887 terminated = true;
10888
10889#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10890
10891 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10892
10893 int val = ::semctl(mIPCSem, 0, GETVAL);
10894 if (val > 0)
10895 {
10896 /* the semaphore is signaled, meaning the session is terminated */
10897 terminated = true;
10898 }
10899
10900#else
10901# error "Port me!"
10902#endif
10903
10904 } /* AutoCaller block */
10905
10906 if (terminated)
10907 uninit(reason);
10908
10909 return terminated;
10910}
10911
10912/**
10913 * @note Locks this object for reading.
10914 */
10915HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10916{
10917 LogFlowThisFunc(("\n"));
10918
10919 AutoCaller autoCaller(this);
10920 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10921
10922 ComPtr<IInternalSessionControl> directControl;
10923 {
10924 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10925 directControl = mData->mSession.mDirectControl;
10926 }
10927
10928 /* ignore notifications sent after #OnSessionEnd() is called */
10929 if (!directControl)
10930 return S_OK;
10931
10932 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10933}
10934
10935/**
10936 * @note Locks this object for reading.
10937 */
10938HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
10939 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
10940{
10941 LogFlowThisFunc(("\n"));
10942
10943 AutoCaller autoCaller(this);
10944 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10945
10946 ComPtr<IInternalSessionControl> directControl;
10947 {
10948 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10949 directControl = mData->mSession.mDirectControl;
10950 }
10951
10952 /* ignore notifications sent after #OnSessionEnd() is called */
10953 if (!directControl)
10954 return S_OK;
10955 /*
10956 * instead acting like callback we ask IVirtualBox deliver corresponding event
10957 */
10958
10959 mParent->onNatRedirectChange(getId(), ulSlot, aNatRuleRemove, aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
10960 return S_OK;
10961}
10962
10963/**
10964 * @note Locks this object for reading.
10965 */
10966HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10967{
10968 LogFlowThisFunc(("\n"));
10969
10970 AutoCaller autoCaller(this);
10971 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10972
10973 ComPtr<IInternalSessionControl> directControl;
10974 {
10975 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10976 directControl = mData->mSession.mDirectControl;
10977 }
10978
10979 /* ignore notifications sent after #OnSessionEnd() is called */
10980 if (!directControl)
10981 return S_OK;
10982
10983 return directControl->OnSerialPortChange(serialPort);
10984}
10985
10986/**
10987 * @note Locks this object for reading.
10988 */
10989HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10990{
10991 LogFlowThisFunc(("\n"));
10992
10993 AutoCaller autoCaller(this);
10994 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10995
10996 ComPtr<IInternalSessionControl> directControl;
10997 {
10998 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10999 directControl = mData->mSession.mDirectControl;
11000 }
11001
11002 /* ignore notifications sent after #OnSessionEnd() is called */
11003 if (!directControl)
11004 return S_OK;
11005
11006 return directControl->OnParallelPortChange(parallelPort);
11007}
11008
11009/**
11010 * @note Locks this object for reading.
11011 */
11012HRESULT SessionMachine::onStorageControllerChange()
11013{
11014 LogFlowThisFunc(("\n"));
11015
11016 AutoCaller autoCaller(this);
11017 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11018
11019 ComPtr<IInternalSessionControl> directControl;
11020 {
11021 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11022 directControl = mData->mSession.mDirectControl;
11023 }
11024
11025 /* ignore notifications sent after #OnSessionEnd() is called */
11026 if (!directControl)
11027 return S_OK;
11028
11029 return directControl->OnStorageControllerChange();
11030}
11031
11032/**
11033 * @note Locks this object for reading.
11034 */
11035HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11036{
11037 LogFlowThisFunc(("\n"));
11038
11039 AutoCaller autoCaller(this);
11040 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11041
11042 ComPtr<IInternalSessionControl> directControl;
11043 {
11044 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11045 directControl = mData->mSession.mDirectControl;
11046 }
11047
11048 /* ignore notifications sent after #OnSessionEnd() is called */
11049 if (!directControl)
11050 return S_OK;
11051
11052 return directControl->OnMediumChange(aAttachment, aForce);
11053}
11054
11055/**
11056 * @note Locks this object for reading.
11057 */
11058HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11059{
11060 LogFlowThisFunc(("\n"));
11061
11062 AutoCaller autoCaller(this);
11063 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11064
11065 ComPtr<IInternalSessionControl> directControl;
11066 {
11067 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11068 directControl = mData->mSession.mDirectControl;
11069 }
11070
11071 /* ignore notifications sent after #OnSessionEnd() is called */
11072 if (!directControl)
11073 return S_OK;
11074
11075 return directControl->OnCPUChange(aCPU, aRemove);
11076}
11077
11078HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11079{
11080 LogFlowThisFunc(("\n"));
11081
11082 AutoCaller autoCaller(this);
11083 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11084
11085 ComPtr<IInternalSessionControl> directControl;
11086 {
11087 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11088 directControl = mData->mSession.mDirectControl;
11089 }
11090
11091 /* ignore notifications sent after #OnSessionEnd() is called */
11092 if (!directControl)
11093 return S_OK;
11094
11095 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11096}
11097
11098/**
11099 * @note Locks this object for reading.
11100 */
11101HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11102{
11103 LogFlowThisFunc(("\n"));
11104
11105 AutoCaller autoCaller(this);
11106 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11107
11108 ComPtr<IInternalSessionControl> directControl;
11109 {
11110 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11111 directControl = mData->mSession.mDirectControl;
11112 }
11113
11114 /* ignore notifications sent after #OnSessionEnd() is called */
11115 if (!directControl)
11116 return S_OK;
11117
11118 return directControl->OnVRDEServerChange(aRestart);
11119}
11120
11121/**
11122 * @note Locks this object for reading.
11123 */
11124HRESULT SessionMachine::onUSBControllerChange()
11125{
11126 LogFlowThisFunc(("\n"));
11127
11128 AutoCaller autoCaller(this);
11129 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11130
11131 ComPtr<IInternalSessionControl> directControl;
11132 {
11133 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11134 directControl = mData->mSession.mDirectControl;
11135 }
11136
11137 /* ignore notifications sent after #OnSessionEnd() is called */
11138 if (!directControl)
11139 return S_OK;
11140
11141 return directControl->OnUSBControllerChange();
11142}
11143
11144/**
11145 * @note Locks this object for reading.
11146 */
11147HRESULT SessionMachine::onSharedFolderChange()
11148{
11149 LogFlowThisFunc(("\n"));
11150
11151 AutoCaller autoCaller(this);
11152 AssertComRCReturnRC(autoCaller.rc());
11153
11154 ComPtr<IInternalSessionControl> directControl;
11155 {
11156 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11157 directControl = mData->mSession.mDirectControl;
11158 }
11159
11160 /* ignore notifications sent after #OnSessionEnd() is called */
11161 if (!directControl)
11162 return S_OK;
11163
11164 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11165}
11166
11167/**
11168 * Returns @c true if this machine's USB controller reports it has a matching
11169 * filter for the given USB device and @c false otherwise.
11170 *
11171 * @note Caller must have requested machine read lock.
11172 */
11173bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11174{
11175 AutoCaller autoCaller(this);
11176 /* silently return if not ready -- this method may be called after the
11177 * direct machine session has been called */
11178 if (!autoCaller.isOk())
11179 return false;
11180
11181
11182#ifdef VBOX_WITH_USB
11183 switch (mData->mMachineState)
11184 {
11185 case MachineState_Starting:
11186 case MachineState_Restoring:
11187 case MachineState_TeleportingIn:
11188 case MachineState_Paused:
11189 case MachineState_Running:
11190 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11191 * elsewhere... */
11192 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11193 default: break;
11194 }
11195#else
11196 NOREF(aDevice);
11197 NOREF(aMaskedIfs);
11198#endif
11199 return false;
11200}
11201
11202/**
11203 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11204 */
11205HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11206 IVirtualBoxErrorInfo *aError,
11207 ULONG aMaskedIfs)
11208{
11209 LogFlowThisFunc(("\n"));
11210
11211 AutoCaller autoCaller(this);
11212
11213 /* This notification may happen after the machine object has been
11214 * uninitialized (the session was closed), so don't assert. */
11215 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11216
11217 ComPtr<IInternalSessionControl> directControl;
11218 {
11219 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11220 directControl = mData->mSession.mDirectControl;
11221 }
11222
11223 /* fail on notifications sent after #OnSessionEnd() is called, it is
11224 * expected by the caller */
11225 if (!directControl)
11226 return E_FAIL;
11227
11228 /* No locks should be held at this point. */
11229 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11230 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11231
11232 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11233}
11234
11235/**
11236 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11237 */
11238HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11239 IVirtualBoxErrorInfo *aError)
11240{
11241 LogFlowThisFunc(("\n"));
11242
11243 AutoCaller autoCaller(this);
11244
11245 /* This notification may happen after the machine object has been
11246 * uninitialized (the session was closed), so don't assert. */
11247 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11248
11249 ComPtr<IInternalSessionControl> directControl;
11250 {
11251 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11252 directControl = mData->mSession.mDirectControl;
11253 }
11254
11255 /* fail on notifications sent after #OnSessionEnd() is called, it is
11256 * expected by the caller */
11257 if (!directControl)
11258 return E_FAIL;
11259
11260 /* No locks should be held at this point. */
11261 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11262 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11263
11264 return directControl->OnUSBDeviceDetach(aId, aError);
11265}
11266
11267// protected methods
11268/////////////////////////////////////////////////////////////////////////////
11269
11270/**
11271 * Helper method to finalize saving the state.
11272 *
11273 * @note Must be called from under this object's lock.
11274 *
11275 * @param aRc S_OK if the snapshot has been taken successfully
11276 * @param aErrMsg human readable error message for failure
11277 *
11278 * @note Locks mParent + this objects for writing.
11279 */
11280HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
11281{
11282 LogFlowThisFuncEnter();
11283
11284 AutoCaller autoCaller(this);
11285 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11286
11287 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11288
11289 HRESULT rc = S_OK;
11290
11291 if (SUCCEEDED(aRc))
11292 {
11293 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11294
11295 /* save all VM settings */
11296 rc = saveSettings(NULL);
11297 // no need to check whether VirtualBox.xml needs saving also since
11298 // we can't have a name change pending at this point
11299 }
11300 else
11301 {
11302 /* delete the saved state file (it might have been already created) */
11303 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11304 }
11305
11306 /* notify the progress object about operation completion */
11307 Assert(mSnapshotData.mProgress);
11308 if (SUCCEEDED(aRc))
11309 mSnapshotData.mProgress->notifyComplete(S_OK);
11310 else
11311 {
11312 if (aErrMsg.length())
11313 mSnapshotData.mProgress->notifyComplete(aRc,
11314 COM_IIDOF(ISession),
11315 getComponentName(),
11316 aErrMsg.c_str());
11317 else
11318 mSnapshotData.mProgress->notifyComplete(aRc);
11319 }
11320
11321 /* clear out the temporary saved state data */
11322 mSnapshotData.mLastState = MachineState_Null;
11323 mSnapshotData.mStateFilePath.setNull();
11324 mSnapshotData.mProgress.setNull();
11325
11326 LogFlowThisFuncLeave();
11327 return rc;
11328}
11329
11330/**
11331 * Locks the attached media.
11332 *
11333 * All attached hard disks are locked for writing and DVD/floppy are locked for
11334 * reading. Parents of attached hard disks (if any) are locked for reading.
11335 *
11336 * This method also performs accessibility check of all media it locks: if some
11337 * media is inaccessible, the method will return a failure and a bunch of
11338 * extended error info objects per each inaccessible medium.
11339 *
11340 * Note that this method is atomic: if it returns a success, all media are
11341 * locked as described above; on failure no media is locked at all (all
11342 * succeeded individual locks will be undone).
11343 *
11344 * This method is intended to be called when the machine is in Starting or
11345 * Restoring state and asserts otherwise.
11346 *
11347 * The locks made by this method must be undone by calling #unlockMedia() when
11348 * no more needed.
11349 */
11350HRESULT SessionMachine::lockMedia()
11351{
11352 AutoCaller autoCaller(this);
11353 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11354
11355 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11356
11357 AssertReturn( mData->mMachineState == MachineState_Starting
11358 || mData->mMachineState == MachineState_Restoring
11359 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11360 /* bail out if trying to lock things with already set up locking */
11361 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11362
11363 MultiResult mrc(S_OK);
11364
11365 /* Collect locking information for all medium objects attached to the VM. */
11366 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11367 it != mMediaData->mAttachments.end();
11368 ++it)
11369 {
11370 MediumAttachment* pAtt = *it;
11371 DeviceType_T devType = pAtt->getType();
11372 Medium *pMedium = pAtt->getMedium();
11373
11374 MediumLockList *pMediumLockList(new MediumLockList());
11375 // There can be attachments without a medium (floppy/dvd), and thus
11376 // it's impossible to create a medium lock list. It still makes sense
11377 // to have the empty medium lock list in the map in case a medium is
11378 // attached later.
11379 if (pMedium != NULL)
11380 {
11381 MediumType_T mediumType = pMedium->getType();
11382 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
11383 || mediumType == MediumType_Shareable;
11384 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11385
11386 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11387 !fIsReadOnlyLock /* fMediumLockWrite */,
11388 NULL,
11389 *pMediumLockList);
11390 if (FAILED(mrc))
11391 {
11392 delete pMediumLockList;
11393 mData->mSession.mLockedMedia.Clear();
11394 break;
11395 }
11396 }
11397
11398 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11399 if (FAILED(rc))
11400 {
11401 mData->mSession.mLockedMedia.Clear();
11402 mrc = setError(rc,
11403 tr("Collecting locking information for all attached media failed"));
11404 break;
11405 }
11406 }
11407
11408 if (SUCCEEDED(mrc))
11409 {
11410 /* Now lock all media. If this fails, nothing is locked. */
11411 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11412 if (FAILED(rc))
11413 {
11414 mrc = setError(rc,
11415 tr("Locking of attached media failed"));
11416 }
11417 }
11418
11419 return mrc;
11420}
11421
11422/**
11423 * Undoes the locks made by by #lockMedia().
11424 */
11425void SessionMachine::unlockMedia()
11426{
11427 AutoCaller autoCaller(this);
11428 AssertComRCReturnVoid(autoCaller.rc());
11429
11430 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11431
11432 /* we may be holding important error info on the current thread;
11433 * preserve it */
11434 ErrorInfoKeeper eik;
11435
11436 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11437 AssertComRC(rc);
11438}
11439
11440/**
11441 * Helper to change the machine state (reimplementation).
11442 *
11443 * @note Locks this object for writing.
11444 */
11445HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11446{
11447 LogFlowThisFuncEnter();
11448 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11449
11450 AutoCaller autoCaller(this);
11451 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11452
11453 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11454
11455 MachineState_T oldMachineState = mData->mMachineState;
11456
11457 AssertMsgReturn(oldMachineState != aMachineState,
11458 ("oldMachineState=%s, aMachineState=%s\n",
11459 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11460 E_FAIL);
11461
11462 HRESULT rc = S_OK;
11463
11464 int stsFlags = 0;
11465 bool deleteSavedState = false;
11466
11467 /* detect some state transitions */
11468
11469 if ( ( oldMachineState == MachineState_Saved
11470 && aMachineState == MachineState_Restoring)
11471 || ( ( oldMachineState == MachineState_PoweredOff
11472 || oldMachineState == MachineState_Teleported
11473 || oldMachineState == MachineState_Aborted
11474 )
11475 && ( aMachineState == MachineState_TeleportingIn
11476 || aMachineState == MachineState_Starting
11477 )
11478 )
11479 )
11480 {
11481 /* The EMT thread is about to start */
11482
11483 /* Nothing to do here for now... */
11484
11485 /// @todo NEWMEDIA don't let mDVDDrive and other children
11486 /// change anything when in the Starting/Restoring state
11487 }
11488 else if ( ( oldMachineState == MachineState_Running
11489 || oldMachineState == MachineState_Paused
11490 || oldMachineState == MachineState_Teleporting
11491 || oldMachineState == MachineState_LiveSnapshotting
11492 || oldMachineState == MachineState_Stuck
11493 || oldMachineState == MachineState_Starting
11494 || oldMachineState == MachineState_Stopping
11495 || oldMachineState == MachineState_Saving
11496 || oldMachineState == MachineState_Restoring
11497 || oldMachineState == MachineState_TeleportingPausedVM
11498 || oldMachineState == MachineState_TeleportingIn
11499 )
11500 && ( aMachineState == MachineState_PoweredOff
11501 || aMachineState == MachineState_Saved
11502 || aMachineState == MachineState_Teleported
11503 || aMachineState == MachineState_Aborted
11504 )
11505 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11506 * snapshot */
11507 && ( mSnapshotData.mSnapshot.isNull()
11508 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11509 )
11510 )
11511 {
11512 /* The EMT thread has just stopped, unlock attached media. Note that as
11513 * opposed to locking that is done from Console, we do unlocking here
11514 * because the VM process may have aborted before having a chance to
11515 * properly unlock all media it locked. */
11516
11517 unlockMedia();
11518 }
11519
11520 if (oldMachineState == MachineState_Restoring)
11521 {
11522 if (aMachineState != MachineState_Saved)
11523 {
11524 /*
11525 * delete the saved state file once the machine has finished
11526 * restoring from it (note that Console sets the state from
11527 * Restoring to Saved if the VM couldn't restore successfully,
11528 * to give the user an ability to fix an error and retry --
11529 * we keep the saved state file in this case)
11530 */
11531 deleteSavedState = true;
11532 }
11533 }
11534 else if ( oldMachineState == MachineState_Saved
11535 && ( aMachineState == MachineState_PoweredOff
11536 || aMachineState == MachineState_Aborted
11537 || aMachineState == MachineState_Teleported
11538 )
11539 )
11540 {
11541 /*
11542 * delete the saved state after Console::ForgetSavedState() is called
11543 * or if the VM process (owning a direct VM session) crashed while the
11544 * VM was Saved
11545 */
11546
11547 /// @todo (dmik)
11548 // Not sure that deleting the saved state file just because of the
11549 // client death before it attempted to restore the VM is a good
11550 // thing. But when it crashes we need to go to the Aborted state
11551 // which cannot have the saved state file associated... The only
11552 // way to fix this is to make the Aborted condition not a VM state
11553 // but a bool flag: i.e., when a crash occurs, set it to true and
11554 // change the state to PoweredOff or Saved depending on the
11555 // saved state presence.
11556
11557 deleteSavedState = true;
11558 mData->mCurrentStateModified = TRUE;
11559 stsFlags |= SaveSTS_CurStateModified;
11560 }
11561
11562 if ( aMachineState == MachineState_Starting
11563 || aMachineState == MachineState_Restoring
11564 || aMachineState == MachineState_TeleportingIn
11565 )
11566 {
11567 /* set the current state modified flag to indicate that the current
11568 * state is no more identical to the state in the
11569 * current snapshot */
11570 if (!mData->mCurrentSnapshot.isNull())
11571 {
11572 mData->mCurrentStateModified = TRUE;
11573 stsFlags |= SaveSTS_CurStateModified;
11574 }
11575 }
11576
11577 if (deleteSavedState)
11578 {
11579 if (mRemoveSavedState)
11580 {
11581 Assert(!mSSData->mStateFilePath.isEmpty());
11582 RTFileDelete(mSSData->mStateFilePath.c_str());
11583 }
11584 mSSData->mStateFilePath.setNull();
11585 stsFlags |= SaveSTS_StateFilePath;
11586 }
11587
11588 /* redirect to the underlying peer machine */
11589 mPeer->setMachineState(aMachineState);
11590
11591 if ( aMachineState == MachineState_PoweredOff
11592 || aMachineState == MachineState_Teleported
11593 || aMachineState == MachineState_Aborted
11594 || aMachineState == MachineState_Saved)
11595 {
11596 /* the machine has stopped execution
11597 * (or the saved state file was adopted) */
11598 stsFlags |= SaveSTS_StateTimeStamp;
11599 }
11600
11601 if ( ( oldMachineState == MachineState_PoweredOff
11602 || oldMachineState == MachineState_Aborted
11603 || oldMachineState == MachineState_Teleported
11604 )
11605 && aMachineState == MachineState_Saved)
11606 {
11607 /* the saved state file was adopted */
11608 Assert(!mSSData->mStateFilePath.isEmpty());
11609 stsFlags |= SaveSTS_StateFilePath;
11610 }
11611
11612#ifdef VBOX_WITH_GUEST_PROPS
11613 if ( aMachineState == MachineState_PoweredOff
11614 || aMachineState == MachineState_Aborted
11615 || aMachineState == MachineState_Teleported)
11616 {
11617 /* Make sure any transient guest properties get removed from the
11618 * property store on shutdown. */
11619
11620 HWData::GuestPropertyList::iterator it;
11621 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11622 if (!fNeedsSaving)
11623 for (it = mHWData->mGuestProperties.begin();
11624 it != mHWData->mGuestProperties.end(); ++it)
11625 if (it->mFlags & guestProp::TRANSIENT)
11626 {
11627 fNeedsSaving = true;
11628 break;
11629 }
11630 if (fNeedsSaving)
11631 {
11632 mData->mCurrentStateModified = TRUE;
11633 stsFlags |= SaveSTS_CurStateModified;
11634 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11635 }
11636 }
11637#endif
11638
11639 rc = saveStateSettings(stsFlags);
11640
11641 if ( ( oldMachineState != MachineState_PoweredOff
11642 && oldMachineState != MachineState_Aborted
11643 && oldMachineState != MachineState_Teleported
11644 )
11645 && ( aMachineState == MachineState_PoweredOff
11646 || aMachineState == MachineState_Aborted
11647 || aMachineState == MachineState_Teleported
11648 )
11649 )
11650 {
11651 /* we've been shut down for any reason */
11652 /* no special action so far */
11653 }
11654
11655 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11656 LogFlowThisFuncLeave();
11657 return rc;
11658}
11659
11660/**
11661 * Sends the current machine state value to the VM process.
11662 *
11663 * @note Locks this object for reading, then calls a client process.
11664 */
11665HRESULT SessionMachine::updateMachineStateOnClient()
11666{
11667 AutoCaller autoCaller(this);
11668 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11669
11670 ComPtr<IInternalSessionControl> directControl;
11671 {
11672 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11673 AssertReturn(!!mData, E_FAIL);
11674 directControl = mData->mSession.mDirectControl;
11675
11676 /* directControl may be already set to NULL here in #OnSessionEnd()
11677 * called too early by the direct session process while there is still
11678 * some operation (like deleting the snapshot) in progress. The client
11679 * process in this case is waiting inside Session::close() for the
11680 * "end session" process object to complete, while #uninit() called by
11681 * #checkForDeath() on the Watcher thread is waiting for the pending
11682 * operation to complete. For now, we accept this inconsistent behavior
11683 * and simply do nothing here. */
11684
11685 if (mData->mSession.mState == SessionState_Unlocking)
11686 return S_OK;
11687
11688 AssertReturn(!directControl.isNull(), E_FAIL);
11689 }
11690
11691 return directControl->UpdateMachineState(mData->mMachineState);
11692}
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