VirtualBox

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

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

Main: fix snapshot folder and log folder regression (since 4.0 directory changes)

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