VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MachineImpl.cpp@ 36365

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

Main: Fix for parameter handling in setGuestPropertyToVM().

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

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