VirtualBox

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

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

Addressed some guest property (transient reset) todos.

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

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