VirtualBox

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

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

PCI: Main and VBoxManage work

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 409.2 KB
Line 
1/* $Id: MachineImpl.cpp 36630 2011-04-08 18:41:51Z 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
2206 clearError();
2207 MultiResult rc(S_OK);
2208
2209# ifdef VBOX_WITH_USB
2210 rc = mParent->host()->checkUSBProxyService();
2211 if (FAILED(rc)) return rc;
2212# endif
2213
2214 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2215
2216 return rc = mUSBController.queryInterfaceTo(aUSBController);
2217#else
2218 /* Note: The GUI depends on this method returning E_NOTIMPL with no
2219 * extended error info to indicate that USB is simply not available
2220 * (w/o treating it as a failure), for example, as in OSE */
2221 NOREF(aUSBController);
2222 ReturnComNotImplemented();
2223#endif /* VBOX_WITH_VUSB */
2224}
2225
2226STDMETHODIMP Machine::COMGETTER(SettingsFilePath)(BSTR *aFilePath)
2227{
2228 CheckComArgOutPointerValid(aFilePath);
2229
2230 AutoLimitedCaller autoCaller(this);
2231 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2232
2233 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2234
2235 mData->m_strConfigFileFull.cloneTo(aFilePath);
2236 return S_OK;
2237}
2238
2239STDMETHODIMP Machine::COMGETTER(SettingsModified)(BOOL *aModified)
2240{
2241 CheckComArgOutPointerValid(aModified);
2242
2243 AutoCaller autoCaller(this);
2244 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2245
2246 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2247
2248 HRESULT rc = checkStateDependency(MutableStateDep);
2249 if (FAILED(rc)) return rc;
2250
2251 if (!mData->pMachineConfigFile->fileExists())
2252 // this is a new machine, and no config file exists yet:
2253 *aModified = TRUE;
2254 else
2255 *aModified = (mData->flModifications != 0);
2256
2257 return S_OK;
2258}
2259
2260STDMETHODIMP Machine::COMGETTER(SessionState)(SessionState_T *aSessionState)
2261{
2262 CheckComArgOutPointerValid(aSessionState);
2263
2264 AutoCaller autoCaller(this);
2265 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2266
2267 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2268
2269 *aSessionState = mData->mSession.mState;
2270
2271 return S_OK;
2272}
2273
2274STDMETHODIMP Machine::COMGETTER(SessionType)(BSTR *aSessionType)
2275{
2276 CheckComArgOutPointerValid(aSessionType);
2277
2278 AutoCaller autoCaller(this);
2279 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2280
2281 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2282
2283 mData->mSession.mType.cloneTo(aSessionType);
2284
2285 return S_OK;
2286}
2287
2288STDMETHODIMP Machine::COMGETTER(SessionPid)(ULONG *aSessionPid)
2289{
2290 CheckComArgOutPointerValid(aSessionPid);
2291
2292 AutoCaller autoCaller(this);
2293 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2294
2295 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2296
2297 *aSessionPid = mData->mSession.mPid;
2298
2299 return S_OK;
2300}
2301
2302STDMETHODIMP Machine::COMGETTER(State)(MachineState_T *machineState)
2303{
2304 if (!machineState)
2305 return E_POINTER;
2306
2307 AutoCaller autoCaller(this);
2308 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2309
2310 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2311
2312 *machineState = mData->mMachineState;
2313
2314 return S_OK;
2315}
2316
2317STDMETHODIMP Machine::COMGETTER(LastStateChange)(LONG64 *aLastStateChange)
2318{
2319 CheckComArgOutPointerValid(aLastStateChange);
2320
2321 AutoCaller autoCaller(this);
2322 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2323
2324 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2325
2326 *aLastStateChange = RTTimeSpecGetMilli(&mData->mLastStateChange);
2327
2328 return S_OK;
2329}
2330
2331STDMETHODIMP Machine::COMGETTER(StateFilePath)(BSTR *aStateFilePath)
2332{
2333 CheckComArgOutPointerValid(aStateFilePath);
2334
2335 AutoCaller autoCaller(this);
2336 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2337
2338 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2339
2340 mSSData->strStateFilePath.cloneTo(aStateFilePath);
2341
2342 return S_OK;
2343}
2344
2345STDMETHODIMP Machine::COMGETTER(LogFolder)(BSTR *aLogFolder)
2346{
2347 CheckComArgOutPointerValid(aLogFolder);
2348
2349 AutoCaller autoCaller(this);
2350 AssertComRCReturnRC(autoCaller.rc());
2351
2352 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2353
2354 Utf8Str logFolder;
2355 getLogFolder(logFolder);
2356 logFolder.cloneTo(aLogFolder);
2357
2358 return S_OK;
2359}
2360
2361STDMETHODIMP Machine::COMGETTER(CurrentSnapshot) (ISnapshot **aCurrentSnapshot)
2362{
2363 CheckComArgOutPointerValid(aCurrentSnapshot);
2364
2365 AutoCaller autoCaller(this);
2366 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2367
2368 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2369
2370 mData->mCurrentSnapshot.queryInterfaceTo(aCurrentSnapshot);
2371
2372 return S_OK;
2373}
2374
2375STDMETHODIMP Machine::COMGETTER(SnapshotCount)(ULONG *aSnapshotCount)
2376{
2377 CheckComArgOutPointerValid(aSnapshotCount);
2378
2379 AutoCaller autoCaller(this);
2380 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2381
2382 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2383
2384 *aSnapshotCount = mData->mFirstSnapshot.isNull()
2385 ? 0
2386 : mData->mFirstSnapshot->getAllChildrenCount() + 1;
2387
2388 return S_OK;
2389}
2390
2391STDMETHODIMP Machine::COMGETTER(CurrentStateModified)(BOOL *aCurrentStateModified)
2392{
2393 CheckComArgOutPointerValid(aCurrentStateModified);
2394
2395 AutoCaller autoCaller(this);
2396 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2397
2398 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2399
2400 /* Note: for machines with no snapshots, we always return FALSE
2401 * (mData->mCurrentStateModified will be TRUE in this case, for historical
2402 * reasons :) */
2403
2404 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
2405 ? FALSE
2406 : mData->mCurrentStateModified;
2407
2408 return S_OK;
2409}
2410
2411STDMETHODIMP Machine::COMGETTER(SharedFolders)(ComSafeArrayOut(ISharedFolder *, aSharedFolders))
2412{
2413 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
2414
2415 AutoCaller autoCaller(this);
2416 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2417
2418 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2419
2420 SafeIfaceArray<ISharedFolder> folders(mHWData->mSharedFolders);
2421 folders.detachTo(ComSafeArrayOutArg(aSharedFolders));
2422
2423 return S_OK;
2424}
2425
2426STDMETHODIMP Machine::COMGETTER(ClipboardMode)(ClipboardMode_T *aClipboardMode)
2427{
2428 CheckComArgOutPointerValid(aClipboardMode);
2429
2430 AutoCaller autoCaller(this);
2431 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2432
2433 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2434
2435 *aClipboardMode = mHWData->mClipboardMode;
2436
2437 return S_OK;
2438}
2439
2440STDMETHODIMP
2441Machine::COMSETTER(ClipboardMode)(ClipboardMode_T aClipboardMode)
2442{
2443 AutoCaller autoCaller(this);
2444 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2445
2446 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2447
2448 HRESULT rc = checkStateDependency(MutableStateDep);
2449 if (FAILED(rc)) return rc;
2450
2451 setModified(IsModified_MachineData);
2452 mHWData.backup();
2453 mHWData->mClipboardMode = aClipboardMode;
2454
2455 return S_OK;
2456}
2457
2458STDMETHODIMP
2459Machine::COMGETTER(GuestPropertyNotificationPatterns)(BSTR *aPatterns)
2460{
2461 CheckComArgOutPointerValid(aPatterns);
2462
2463 AutoCaller autoCaller(this);
2464 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2465
2466 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2467
2468 try
2469 {
2470 mHWData->mGuestPropertyNotificationPatterns.cloneTo(aPatterns);
2471 }
2472 catch (...)
2473 {
2474 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
2475 }
2476
2477 return S_OK;
2478}
2479
2480STDMETHODIMP
2481Machine::COMSETTER(GuestPropertyNotificationPatterns)(IN_BSTR aPatterns)
2482{
2483 AutoCaller autoCaller(this);
2484 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2485
2486 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2487
2488 HRESULT rc = checkStateDependency(MutableStateDep);
2489 if (FAILED(rc)) return rc;
2490
2491 setModified(IsModified_MachineData);
2492 mHWData.backup();
2493 mHWData->mGuestPropertyNotificationPatterns = aPatterns;
2494 return rc;
2495}
2496
2497STDMETHODIMP
2498Machine::COMGETTER(StorageControllers)(ComSafeArrayOut(IStorageController *, aStorageControllers))
2499{
2500 CheckComArgOutSafeArrayPointerValid(aStorageControllers);
2501
2502 AutoCaller autoCaller(this);
2503 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2504
2505 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2506
2507 SafeIfaceArray<IStorageController> ctrls(*mStorageControllers.data());
2508 ctrls.detachTo(ComSafeArrayOutArg(aStorageControllers));
2509
2510 return S_OK;
2511}
2512
2513STDMETHODIMP
2514Machine::COMGETTER(TeleporterEnabled)(BOOL *aEnabled)
2515{
2516 CheckComArgOutPointerValid(aEnabled);
2517
2518 AutoCaller autoCaller(this);
2519 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2520
2521 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2522
2523 *aEnabled = mUserData->s.fTeleporterEnabled;
2524
2525 return S_OK;
2526}
2527
2528STDMETHODIMP Machine::COMSETTER(TeleporterEnabled)(BOOL aEnabled)
2529{
2530 AutoCaller autoCaller(this);
2531 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2532
2533 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2534
2535 /* Only allow it to be set to true when PoweredOff or Aborted.
2536 (Clearing it is always permitted.) */
2537 if ( aEnabled
2538 && mData->mRegistered
2539 && ( !isSessionMachine()
2540 || ( mData->mMachineState != MachineState_PoweredOff
2541 && mData->mMachineState != MachineState_Teleported
2542 && mData->mMachineState != MachineState_Aborted
2543 )
2544 )
2545 )
2546 return setError(VBOX_E_INVALID_VM_STATE,
2547 tr("The machine is not powered off (state is %s)"),
2548 Global::stringifyMachineState(mData->mMachineState));
2549
2550 setModified(IsModified_MachineData);
2551 mUserData.backup();
2552 mUserData->s.fTeleporterEnabled = !!aEnabled;
2553
2554 return S_OK;
2555}
2556
2557STDMETHODIMP Machine::COMGETTER(TeleporterPort)(ULONG *aPort)
2558{
2559 CheckComArgOutPointerValid(aPort);
2560
2561 AutoCaller autoCaller(this);
2562 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2563
2564 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2565
2566 *aPort = (ULONG)mUserData->s.uTeleporterPort;
2567
2568 return S_OK;
2569}
2570
2571STDMETHODIMP Machine::COMSETTER(TeleporterPort)(ULONG aPort)
2572{
2573 if (aPort >= _64K)
2574 return setError(E_INVALIDARG, tr("Invalid port number %d"), aPort);
2575
2576 AutoCaller autoCaller(this);
2577 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2578
2579 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2580
2581 HRESULT rc = checkStateDependency(MutableStateDep);
2582 if (FAILED(rc)) return rc;
2583
2584 setModified(IsModified_MachineData);
2585 mUserData.backup();
2586 mUserData->s.uTeleporterPort = (uint32_t)aPort;
2587
2588 return S_OK;
2589}
2590
2591STDMETHODIMP Machine::COMGETTER(TeleporterAddress)(BSTR *aAddress)
2592{
2593 CheckComArgOutPointerValid(aAddress);
2594
2595 AutoCaller autoCaller(this);
2596 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2597
2598 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2599
2600 mUserData->s.strTeleporterAddress.cloneTo(aAddress);
2601
2602 return S_OK;
2603}
2604
2605STDMETHODIMP Machine::COMSETTER(TeleporterAddress)(IN_BSTR aAddress)
2606{
2607 AutoCaller autoCaller(this);
2608 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2609
2610 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2611
2612 HRESULT rc = checkStateDependency(MutableStateDep);
2613 if (FAILED(rc)) return rc;
2614
2615 setModified(IsModified_MachineData);
2616 mUserData.backup();
2617 mUserData->s.strTeleporterAddress = aAddress;
2618
2619 return S_OK;
2620}
2621
2622STDMETHODIMP Machine::COMGETTER(TeleporterPassword)(BSTR *aPassword)
2623{
2624 CheckComArgOutPointerValid(aPassword);
2625
2626 AutoCaller autoCaller(this);
2627 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2628
2629 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2630
2631 mUserData->s.strTeleporterPassword.cloneTo(aPassword);
2632
2633 return S_OK;
2634}
2635
2636STDMETHODIMP Machine::COMSETTER(TeleporterPassword)(IN_BSTR aPassword)
2637{
2638 AutoCaller autoCaller(this);
2639 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2640
2641 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2642
2643 HRESULT rc = checkStateDependency(MutableStateDep);
2644 if (FAILED(rc)) return rc;
2645
2646 setModified(IsModified_MachineData);
2647 mUserData.backup();
2648 mUserData->s.strTeleporterPassword = aPassword;
2649
2650 return S_OK;
2651}
2652
2653STDMETHODIMP Machine::COMGETTER(FaultToleranceState)(FaultToleranceState_T *aState)
2654{
2655 CheckComArgOutPointerValid(aState);
2656
2657 AutoCaller autoCaller(this);
2658 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2659
2660 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2661
2662 *aState = mUserData->s.enmFaultToleranceState;
2663 return S_OK;
2664}
2665
2666STDMETHODIMP Machine::COMSETTER(FaultToleranceState)(FaultToleranceState_T aState)
2667{
2668 AutoCaller autoCaller(this);
2669 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2670
2671 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2672
2673 /* @todo deal with running state change. */
2674 HRESULT rc = checkStateDependency(MutableStateDep);
2675 if (FAILED(rc)) return rc;
2676
2677 setModified(IsModified_MachineData);
2678 mUserData.backup();
2679 mUserData->s.enmFaultToleranceState = aState;
2680 return S_OK;
2681}
2682
2683STDMETHODIMP Machine::COMGETTER(FaultToleranceAddress)(BSTR *aAddress)
2684{
2685 CheckComArgOutPointerValid(aAddress);
2686
2687 AutoCaller autoCaller(this);
2688 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2689
2690 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2691
2692 mUserData->s.strFaultToleranceAddress.cloneTo(aAddress);
2693 return S_OK;
2694}
2695
2696STDMETHODIMP Machine::COMSETTER(FaultToleranceAddress)(IN_BSTR aAddress)
2697{
2698 AutoCaller autoCaller(this);
2699 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2700
2701 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2702
2703 /* @todo deal with running state change. */
2704 HRESULT rc = checkStateDependency(MutableStateDep);
2705 if (FAILED(rc)) return rc;
2706
2707 setModified(IsModified_MachineData);
2708 mUserData.backup();
2709 mUserData->s.strFaultToleranceAddress = aAddress;
2710 return S_OK;
2711}
2712
2713STDMETHODIMP Machine::COMGETTER(FaultTolerancePort)(ULONG *aPort)
2714{
2715 CheckComArgOutPointerValid(aPort);
2716
2717 AutoCaller autoCaller(this);
2718 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2719
2720 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2721
2722 *aPort = mUserData->s.uFaultTolerancePort;
2723 return S_OK;
2724}
2725
2726STDMETHODIMP Machine::COMSETTER(FaultTolerancePort)(ULONG aPort)
2727{
2728 AutoCaller autoCaller(this);
2729 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2730
2731 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2732
2733 /* @todo deal with running state change. */
2734 HRESULT rc = checkStateDependency(MutableStateDep);
2735 if (FAILED(rc)) return rc;
2736
2737 setModified(IsModified_MachineData);
2738 mUserData.backup();
2739 mUserData->s.uFaultTolerancePort = aPort;
2740 return S_OK;
2741}
2742
2743STDMETHODIMP Machine::COMGETTER(FaultTolerancePassword)(BSTR *aPassword)
2744{
2745 CheckComArgOutPointerValid(aPassword);
2746
2747 AutoCaller autoCaller(this);
2748 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2749
2750 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2751
2752 mUserData->s.strFaultTolerancePassword.cloneTo(aPassword);
2753
2754 return S_OK;
2755}
2756
2757STDMETHODIMP Machine::COMSETTER(FaultTolerancePassword)(IN_BSTR aPassword)
2758{
2759 AutoCaller autoCaller(this);
2760 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2761
2762 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2763
2764 /* @todo deal with running state change. */
2765 HRESULT rc = checkStateDependency(MutableStateDep);
2766 if (FAILED(rc)) return rc;
2767
2768 setModified(IsModified_MachineData);
2769 mUserData.backup();
2770 mUserData->s.strFaultTolerancePassword = aPassword;
2771
2772 return S_OK;
2773}
2774
2775STDMETHODIMP Machine::COMGETTER(FaultToleranceSyncInterval)(ULONG *aInterval)
2776{
2777 CheckComArgOutPointerValid(aInterval);
2778
2779 AutoCaller autoCaller(this);
2780 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2781
2782 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2783
2784 *aInterval = mUserData->s.uFaultToleranceInterval;
2785 return S_OK;
2786}
2787
2788STDMETHODIMP Machine::COMSETTER(FaultToleranceSyncInterval)(ULONG aInterval)
2789{
2790 AutoCaller autoCaller(this);
2791 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2792
2793 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2794
2795 /* @todo deal with running state change. */
2796 HRESULT rc = checkStateDependency(MutableStateDep);
2797 if (FAILED(rc)) return rc;
2798
2799 setModified(IsModified_MachineData);
2800 mUserData.backup();
2801 mUserData->s.uFaultToleranceInterval = aInterval;
2802 return S_OK;
2803}
2804
2805STDMETHODIMP Machine::COMGETTER(RTCUseUTC)(BOOL *aEnabled)
2806{
2807 CheckComArgOutPointerValid(aEnabled);
2808
2809 AutoCaller autoCaller(this);
2810 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2811
2812 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2813
2814 *aEnabled = mUserData->s.fRTCUseUTC;
2815
2816 return S_OK;
2817}
2818
2819STDMETHODIMP Machine::COMSETTER(RTCUseUTC)(BOOL aEnabled)
2820{
2821 AutoCaller autoCaller(this);
2822 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2823
2824 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2825
2826 /* Only allow it to be set to true when PoweredOff or Aborted.
2827 (Clearing it is always permitted.) */
2828 if ( aEnabled
2829 && mData->mRegistered
2830 && ( !isSessionMachine()
2831 || ( mData->mMachineState != MachineState_PoweredOff
2832 && mData->mMachineState != MachineState_Teleported
2833 && mData->mMachineState != MachineState_Aborted
2834 )
2835 )
2836 )
2837 return setError(VBOX_E_INVALID_VM_STATE,
2838 tr("The machine is not powered off (state is %s)"),
2839 Global::stringifyMachineState(mData->mMachineState));
2840
2841 setModified(IsModified_MachineData);
2842 mUserData.backup();
2843 mUserData->s.fRTCUseUTC = !!aEnabled;
2844
2845 return S_OK;
2846}
2847
2848STDMETHODIMP Machine::COMGETTER(IoCacheEnabled)(BOOL *aEnabled)
2849{
2850 CheckComArgOutPointerValid(aEnabled);
2851
2852 AutoCaller autoCaller(this);
2853 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2854
2855 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2856
2857 *aEnabled = mHWData->mIoCacheEnabled;
2858
2859 return S_OK;
2860}
2861
2862STDMETHODIMP Machine::COMSETTER(IoCacheEnabled)(BOOL aEnabled)
2863{
2864 AutoCaller autoCaller(this);
2865 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2866
2867 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2868
2869 HRESULT rc = checkStateDependency(MutableStateDep);
2870 if (FAILED(rc)) return rc;
2871
2872 setModified(IsModified_MachineData);
2873 mHWData.backup();
2874 mHWData->mIoCacheEnabled = aEnabled;
2875
2876 return S_OK;
2877}
2878
2879STDMETHODIMP Machine::COMGETTER(IoCacheSize)(ULONG *aIoCacheSize)
2880{
2881 CheckComArgOutPointerValid(aIoCacheSize);
2882
2883 AutoCaller autoCaller(this);
2884 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2885
2886 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2887
2888 *aIoCacheSize = mHWData->mIoCacheSize;
2889
2890 return S_OK;
2891}
2892
2893STDMETHODIMP Machine::COMSETTER(IoCacheSize)(ULONG aIoCacheSize)
2894{
2895 AutoCaller autoCaller(this);
2896 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2897
2898 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2899
2900 HRESULT rc = checkStateDependency(MutableStateDep);
2901 if (FAILED(rc)) return rc;
2902
2903 setModified(IsModified_MachineData);
2904 mHWData.backup();
2905 mHWData->mIoCacheSize = aIoCacheSize;
2906
2907 return S_OK;
2908}
2909
2910
2911/**
2912 * @note Locks objects!
2913 */
2914STDMETHODIMP Machine::LockMachine(ISession *aSession,
2915 LockType_T lockType)
2916{
2917 CheckComArgNotNull(aSession);
2918
2919 AutoCaller autoCaller(this);
2920 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2921
2922 /* check the session state */
2923 SessionState_T state;
2924 HRESULT rc = aSession->COMGETTER(State)(&state);
2925 if (FAILED(rc)) return rc;
2926
2927 if (state != SessionState_Unlocked)
2928 return setError(VBOX_E_INVALID_OBJECT_STATE,
2929 tr("The given session is busy"));
2930
2931 // get the client's IInternalSessionControl interface
2932 ComPtr<IInternalSessionControl> pSessionControl = aSession;
2933 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
2934 E_INVALIDARG);
2935
2936 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2937
2938 if (!mData->mRegistered)
2939 return setError(E_UNEXPECTED,
2940 tr("The machine '%s' is not registered"),
2941 mUserData->s.strName.c_str());
2942
2943 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
2944
2945 SessionState_T oldState = mData->mSession.mState;
2946 /* Hack: in case the session is closing and there is a progress object
2947 * which allows waiting for the session to be closed, take the opportunity
2948 * and do a limited wait (max. 1 second). This helps a lot when the system
2949 * is busy and thus session closing can take a little while. */
2950 if ( mData->mSession.mState == SessionState_Unlocking
2951 && mData->mSession.mProgress)
2952 {
2953 alock.release();
2954 mData->mSession.mProgress->WaitForCompletion(1000);
2955 alock.acquire();
2956 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
2957 }
2958
2959 // try again now
2960 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already (i.e. session machine exists)
2961 && (lockType == LockType_Shared) // caller wants a shared link to the existing session that holds the write lock:
2962 )
2963 {
2964 // OK, share the session... we are now dealing with three processes:
2965 // 1) VBoxSVC (where this code runs);
2966 // 2) process C: the caller's client process (who wants a shared session);
2967 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
2968
2969 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
2970 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
2971 ComAssertRet(!pSessionW.isNull(), E_FAIL);
2972 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
2973 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
2974
2975 /*
2976 * Leave the lock before calling the client process. It's safe here
2977 * since the only thing to do after we get the lock again is to add
2978 * the remote control to the list (which doesn't directly influence
2979 * anything).
2980 */
2981 alock.leave();
2982
2983 // get the console of the session holding the write lock (this is a remote call)
2984 ComPtr<IConsole> pConsoleW;
2985 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
2986 rc = pSessionW->GetRemoteConsole(pConsoleW.asOutParam());
2987 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
2988 if (FAILED(rc))
2989 // the failure may occur w/o any error info (from RPC), so provide one
2990 return setError(VBOX_E_VM_ERROR,
2991 tr("Failed to get a console object from the direct session (%Rrc)"), rc);
2992
2993 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
2994
2995 // share the session machine and W's console with the caller's session
2996 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
2997 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
2998 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
2999
3000 if (FAILED(rc))
3001 // the failure may occur w/o any error info (from RPC), so provide one
3002 return setError(VBOX_E_VM_ERROR,
3003 tr("Failed to assign the machine to the session (%Rrc)"), rc);
3004 alock.enter();
3005
3006 // need to revalidate the state after entering the lock again
3007 if (mData->mSession.mState != SessionState_Locked)
3008 {
3009 pSessionControl->Uninitialize();
3010 return setError(VBOX_E_INVALID_SESSION_STATE,
3011 tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
3012 mUserData->s.strName.c_str());
3013 }
3014
3015 // add the caller's session to the list
3016 mData->mSession.mRemoteControls.push_back(pSessionControl);
3017 }
3018 else if ( mData->mSession.mState == SessionState_Locked
3019 || mData->mSession.mState == SessionState_Unlocking
3020 )
3021 {
3022 // sharing not permitted, or machine still unlocking:
3023 return setError(VBOX_E_INVALID_OBJECT_STATE,
3024 tr("The machine '%s' is already locked for a session (or being unlocked)"),
3025 mUserData->s.strName.c_str());
3026 }
3027 else
3028 {
3029 // machine is not locked: then write-lock the machine (create the session machine)
3030
3031 // must not be busy
3032 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
3033
3034 // get the caller's session PID
3035 RTPROCESS pid = NIL_RTPROCESS;
3036 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
3037 pSessionControl->GetPID((ULONG*)&pid);
3038 Assert(pid != NIL_RTPROCESS);
3039
3040 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
3041
3042 if (fLaunchingVMProcess)
3043 {
3044 // this machine is awaiting for a spawning session to be opened:
3045 // then the calling process must be the one that got started by
3046 // launchVMProcess()
3047
3048 LogFlowThisFunc(("mSession.mPid=%d(0x%x)\n", mData->mSession.mPid, mData->mSession.mPid));
3049 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3050
3051 if (mData->mSession.mPid != pid)
3052 return setError(E_ACCESSDENIED,
3053 tr("An unexpected process (PID=0x%08X) has tried to lock the "
3054 "machine '%s', while only the process started by launchVMProcess (PID=0x%08X) is allowed"),
3055 pid, mUserData->s.strName.c_str(), mData->mSession.mPid);
3056 }
3057
3058 // create the mutable SessionMachine from the current machine
3059 ComObjPtr<SessionMachine> sessionMachine;
3060 sessionMachine.createObject();
3061 rc = sessionMachine->init(this);
3062 AssertComRC(rc);
3063
3064 /* NOTE: doing return from this function after this point but
3065 * before the end is forbidden since it may call SessionMachine::uninit()
3066 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3067 * lock while still holding the Machine lock in alock so that a deadlock
3068 * is possible due to the wrong lock order. */
3069
3070 if (SUCCEEDED(rc))
3071 {
3072 /*
3073 * Set the session state to Spawning to protect against subsequent
3074 * attempts to open a session and to unregister the machine after
3075 * we leave the lock.
3076 */
3077 SessionState_T origState = mData->mSession.mState;
3078 mData->mSession.mState = SessionState_Spawning;
3079
3080 /*
3081 * Leave the lock before calling the client process -- it will call
3082 * Machine/SessionMachine methods. Leaving the lock here is quite safe
3083 * because the state is Spawning, so that openRemotesession() and
3084 * openExistingSession() calls will fail. This method, called before we
3085 * enter the lock again, will fail because of the wrong PID.
3086 *
3087 * Note that mData->mSession.mRemoteControls accessed outside
3088 * the lock may not be modified when state is Spawning, so it's safe.
3089 */
3090 alock.leave();
3091
3092 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3093 rc = pSessionControl->AssignMachine(sessionMachine);
3094 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3095
3096 /* The failure may occur w/o any error info (from RPC), so provide one */
3097 if (FAILED(rc))
3098 setError(VBOX_E_VM_ERROR,
3099 tr("Failed to assign the machine to the session (%Rrc)"), rc);
3100
3101 if ( SUCCEEDED(rc)
3102 && fLaunchingVMProcess
3103 )
3104 {
3105 /* complete the remote session initialization */
3106
3107 /* get the console from the direct session */
3108 ComPtr<IConsole> console;
3109 rc = pSessionControl->GetRemoteConsole(console.asOutParam());
3110 ComAssertComRC(rc);
3111
3112 if (SUCCEEDED(rc) && !console)
3113 {
3114 ComAssert(!!console);
3115 rc = E_FAIL;
3116 }
3117
3118 /* assign machine & console to the remote session */
3119 if (SUCCEEDED(rc))
3120 {
3121 /*
3122 * after openRemoteSession(), the first and the only
3123 * entry in remoteControls is that remote session
3124 */
3125 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3126 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
3127 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3128
3129 /* The failure may occur w/o any error info (from RPC), so provide one */
3130 if (FAILED(rc))
3131 setError(VBOX_E_VM_ERROR,
3132 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
3133 }
3134
3135 if (FAILED(rc))
3136 pSessionControl->Uninitialize();
3137 }
3138
3139 /* enter the lock again */
3140 alock.enter();
3141
3142 /* Restore the session state */
3143 mData->mSession.mState = origState;
3144 }
3145
3146 // finalize spawning anyway (this is why we don't return on errors above)
3147 if (fLaunchingVMProcess)
3148 {
3149 /* Note that the progress object is finalized later */
3150 /** @todo Consider checking mData->mSession.mProgress for cancellation
3151 * around here. */
3152
3153 /* We don't reset mSession.mPid here because it is necessary for
3154 * SessionMachine::uninit() to reap the child process later. */
3155
3156 if (FAILED(rc))
3157 {
3158 /* Close the remote session, remove the remote control from the list
3159 * and reset session state to Closed (@note keep the code in sync
3160 * with the relevant part in openSession()). */
3161
3162 Assert(mData->mSession.mRemoteControls.size() == 1);
3163 if (mData->mSession.mRemoteControls.size() == 1)
3164 {
3165 ErrorInfoKeeper eik;
3166 mData->mSession.mRemoteControls.front()->Uninitialize();
3167 }
3168
3169 mData->mSession.mRemoteControls.clear();
3170 mData->mSession.mState = SessionState_Unlocked;
3171 }
3172 }
3173 else
3174 {
3175 /* memorize PID of the directly opened session */
3176 if (SUCCEEDED(rc))
3177 mData->mSession.mPid = pid;
3178 }
3179
3180 if (SUCCEEDED(rc))
3181 {
3182 /* memorize the direct session control and cache IUnknown for it */
3183 mData->mSession.mDirectControl = pSessionControl;
3184 mData->mSession.mState = SessionState_Locked;
3185 /* associate the SessionMachine with this Machine */
3186 mData->mSession.mMachine = sessionMachine;
3187
3188 /* request an IUnknown pointer early from the remote party for later
3189 * identity checks (it will be internally cached within mDirectControl
3190 * at least on XPCOM) */
3191 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3192 NOREF(unk);
3193 }
3194
3195 /* Leave the lock since SessionMachine::uninit() locks VirtualBox which
3196 * would break the lock order */
3197 alock.leave();
3198
3199 /* uninitialize the created session machine on failure */
3200 if (FAILED(rc))
3201 sessionMachine->uninit();
3202
3203 }
3204
3205 if (SUCCEEDED(rc))
3206 {
3207 /*
3208 * tell the client watcher thread to update the set of
3209 * machines that have open sessions
3210 */
3211 mParent->updateClientWatcher();
3212
3213 if (oldState != SessionState_Locked)
3214 /* fire an event */
3215 mParent->onSessionStateChange(getId(), SessionState_Locked);
3216 }
3217
3218 return rc;
3219}
3220
3221/**
3222 * @note Locks objects!
3223 */
3224STDMETHODIMP Machine::LaunchVMProcess(ISession *aSession,
3225 IN_BSTR aType,
3226 IN_BSTR aEnvironment,
3227 IProgress **aProgress)
3228{
3229 CheckComArgNotNull(aSession);
3230 CheckComArgStrNotEmptyOrNull(aType);
3231 CheckComArgOutPointerValid(aProgress);
3232
3233 AutoCaller autoCaller(this);
3234 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3235
3236 /* check the session state */
3237 SessionState_T state;
3238 HRESULT rc = aSession->COMGETTER(State)(&state);
3239 if (FAILED(rc)) return rc;
3240
3241 if (state != SessionState_Unlocked)
3242 return setError(VBOX_E_INVALID_OBJECT_STATE,
3243 tr("The given session is busy"));
3244
3245 /* get the IInternalSessionControl interface */
3246 ComPtr<IInternalSessionControl> control = aSession;
3247 ComAssertMsgRet(!!control, ("No IInternalSessionControl interface"),
3248 E_INVALIDARG);
3249
3250 /* get the teleporter enable state for the progress object init. */
3251 BOOL fTeleporterEnabled;
3252 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3253 if (FAILED(rc))
3254 return rc;
3255
3256 /* create a progress object */
3257 ComObjPtr<ProgressProxy> progress;
3258 progress.createObject();
3259 rc = progress->init(mParent,
3260 static_cast<IMachine*>(this),
3261 Bstr(tr("Spawning session")).raw(),
3262 TRUE /* aCancelable */,
3263 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3264 Bstr(tr("Spawning session")).raw(),
3265 2 /* uFirstOperationWeight */,
3266 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3267 if (SUCCEEDED(rc))
3268 {
3269 rc = openRemoteSession(control, aType, aEnvironment, progress);
3270 if (SUCCEEDED(rc))
3271 {
3272 progress.queryInterfaceTo(aProgress);
3273
3274 /* signal the client watcher thread */
3275 mParent->updateClientWatcher();
3276
3277 /* fire an event */
3278 mParent->onSessionStateChange(getId(), SessionState_Spawning);
3279 }
3280 }
3281
3282 return rc;
3283}
3284
3285STDMETHODIMP Machine::SetBootOrder(ULONG aPosition, DeviceType_T aDevice)
3286{
3287 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3288 return setError(E_INVALIDARG,
3289 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3290 aPosition, SchemaDefs::MaxBootPosition);
3291
3292 if (aDevice == DeviceType_USB)
3293 return setError(E_NOTIMPL,
3294 tr("Booting from USB device is currently not supported"));
3295
3296 AutoCaller autoCaller(this);
3297 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3298
3299 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3300
3301 HRESULT rc = checkStateDependency(MutableStateDep);
3302 if (FAILED(rc)) return rc;
3303
3304 setModified(IsModified_MachineData);
3305 mHWData.backup();
3306 mHWData->mBootOrder[aPosition - 1] = aDevice;
3307
3308 return S_OK;
3309}
3310
3311STDMETHODIMP Machine::GetBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3312{
3313 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3314 return setError(E_INVALIDARG,
3315 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3316 aPosition, SchemaDefs::MaxBootPosition);
3317
3318 AutoCaller autoCaller(this);
3319 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3320
3321 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3322
3323 *aDevice = mHWData->mBootOrder[aPosition - 1];
3324
3325 return S_OK;
3326}
3327
3328STDMETHODIMP Machine::AttachDevice(IN_BSTR aControllerName,
3329 LONG aControllerPort,
3330 LONG aDevice,
3331 DeviceType_T aType,
3332 IMedium *aMedium)
3333{
3334 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aType=%d aId=\"%ls\"\n",
3335 aControllerName, aControllerPort, aDevice, aType, aMedium));
3336
3337 CheckComArgStrNotEmptyOrNull(aControllerName);
3338
3339 AutoCaller autoCaller(this);
3340 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3341
3342 // request the host lock first, since might be calling Host methods for getting host drives;
3343 // next, protect the media tree all the while we're in here, as well as our member variables
3344 AutoMultiWriteLock2 alock(mParent->host()->lockHandle(),
3345 this->lockHandle() COMMA_LOCKVAL_SRC_POS);
3346 AutoWriteLock treeLock(&mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3347
3348 HRESULT rc = checkStateDependency(MutableStateDep);
3349 if (FAILED(rc)) return rc;
3350
3351 GuidList llRegistriesThatNeedSaving;
3352
3353 /// @todo NEWMEDIA implicit machine registration
3354 if (!mData->mRegistered)
3355 return setError(VBOX_E_INVALID_OBJECT_STATE,
3356 tr("Cannot attach storage devices to an unregistered machine"));
3357
3358 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3359
3360 if (Global::IsOnlineOrTransient(mData->mMachineState))
3361 return setError(VBOX_E_INVALID_VM_STATE,
3362 tr("Invalid machine state: %s"),
3363 Global::stringifyMachineState(mData->mMachineState));
3364
3365 /* Check for an existing controller. */
3366 ComObjPtr<StorageController> ctl;
3367 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
3368 if (FAILED(rc)) return rc;
3369
3370 // check that the port and device are not out of range
3371 rc = ctl->checkPortAndDeviceValid(aControllerPort, aDevice);
3372 if (FAILED(rc)) return rc;
3373
3374 /* check if the device slot is already busy */
3375 MediumAttachment *pAttachTemp;
3376 if ((pAttachTemp = findAttachment(mMediaData->mAttachments,
3377 aControllerName,
3378 aControllerPort,
3379 aDevice)))
3380 {
3381 Medium *pMedium = pAttachTemp->getMedium();
3382 if (pMedium)
3383 {
3384 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3385 return setError(VBOX_E_OBJECT_IN_USE,
3386 tr("Medium '%s' is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3387 pMedium->getLocationFull().c_str(),
3388 aControllerPort,
3389 aDevice,
3390 aControllerName);
3391 }
3392 else
3393 return setError(VBOX_E_OBJECT_IN_USE,
3394 tr("Device is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3395 aControllerPort, aDevice, aControllerName);
3396 }
3397
3398 ComObjPtr<Medium> medium = static_cast<Medium*>(aMedium);
3399 if (aMedium && medium.isNull())
3400 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3401
3402 AutoCaller mediumCaller(medium);
3403 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3404
3405 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3406
3407 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
3408 && !medium.isNull()
3409 )
3410 return setError(VBOX_E_OBJECT_IN_USE,
3411 tr("Medium '%s' is already attached to this virtual machine"),
3412 medium->getLocationFull().c_str());
3413
3414 if (!medium.isNull())
3415 {
3416 MediumType_T mtype = medium->getType();
3417 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3418 // For DVDs it's not written to the config file, so needs no global config
3419 // version bump. For floppies it's a new attribute "type", which is ignored
3420 // by older VirtualBox version, so needs no global config version bump either.
3421 // For hard disks this type is not accepted.
3422 if (mtype == MediumType_MultiAttach)
3423 {
3424 // This type is new with VirtualBox 4.0 and therefore requires settings
3425 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3426 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3427 // two reasons: The medium type is a property of the media registry tree, which
3428 // can reside in the global config file (for pre-4.0 media); we would therefore
3429 // possibly need to bump the global config version. We don't want to do that though
3430 // because that might make downgrading to pre-4.0 impossible.
3431 // As a result, we can only use these two new types if the medium is NOT in the
3432 // global registry:
3433 const Guid &uuidGlobalRegistry = mParent->getGlobalRegistryId();
3434 if ( medium->isInRegistry(uuidGlobalRegistry)
3435 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3436 )
3437 return setError(VBOX_E_INVALID_OBJECT_STATE,
3438 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3439 "to machines that were created with VirtualBox 4.0 or later"),
3440 medium->getLocationFull().c_str());
3441 }
3442 }
3443
3444 bool fIndirect = false;
3445 if (!medium.isNull())
3446 fIndirect = medium->isReadOnly();
3447 bool associate = true;
3448
3449 do
3450 {
3451 if ( aType == DeviceType_HardDisk
3452 && mMediaData.isBackedUp())
3453 {
3454 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3455
3456 /* check if the medium was attached to the VM before we started
3457 * changing attachments in which case the attachment just needs to
3458 * be restored */
3459 if ((pAttachTemp = findAttachment(oldAtts, medium)))
3460 {
3461 AssertReturn(!fIndirect, E_FAIL);
3462
3463 /* see if it's the same bus/channel/device */
3464 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
3465 {
3466 /* the simplest case: restore the whole attachment
3467 * and return, nothing else to do */
3468 mMediaData->mAttachments.push_back(pAttachTemp);
3469 return S_OK;
3470 }
3471
3472 /* bus/channel/device differ; we need a new attachment object,
3473 * but don't try to associate it again */
3474 associate = false;
3475 break;
3476 }
3477 }
3478
3479 /* go further only if the attachment is to be indirect */
3480 if (!fIndirect)
3481 break;
3482
3483 /* perform the so called smart attachment logic for indirect
3484 * attachments. Note that smart attachment is only applicable to base
3485 * hard disks. */
3486
3487 if (medium->getParent().isNull())
3488 {
3489 /* first, investigate the backup copy of the current hard disk
3490 * attachments to make it possible to re-attach existing diffs to
3491 * another device slot w/o losing their contents */
3492 if (mMediaData.isBackedUp())
3493 {
3494 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3495
3496 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
3497 uint32_t foundLevel = 0;
3498
3499 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
3500 it != oldAtts.end();
3501 ++it)
3502 {
3503 uint32_t level = 0;
3504 MediumAttachment *pAttach = *it;
3505 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3506 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3507 if (pMedium.isNull())
3508 continue;
3509
3510 if (pMedium->getBase(&level) == medium)
3511 {
3512 /* skip the hard disk if its currently attached (we
3513 * cannot attach the same hard disk twice) */
3514 if (findAttachment(mMediaData->mAttachments,
3515 pMedium))
3516 continue;
3517
3518 /* matched device, channel and bus (i.e. attached to the
3519 * same place) will win and immediately stop the search;
3520 * otherwise the attachment that has the youngest
3521 * descendant of medium will be used
3522 */
3523 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
3524 {
3525 /* the simplest case: restore the whole attachment
3526 * and return, nothing else to do */
3527 mMediaData->mAttachments.push_back(*it);
3528 return S_OK;
3529 }
3530 else if ( foundIt == oldAtts.end()
3531 || level > foundLevel /* prefer younger */
3532 )
3533 {
3534 foundIt = it;
3535 foundLevel = level;
3536 }
3537 }
3538 }
3539
3540 if (foundIt != oldAtts.end())
3541 {
3542 /* use the previously attached hard disk */
3543 medium = (*foundIt)->getMedium();
3544 mediumCaller.attach(medium);
3545 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3546 mediumLock.attach(medium);
3547 /* not implicit, doesn't require association with this VM */
3548 fIndirect = false;
3549 associate = false;
3550 /* go right to the MediumAttachment creation */
3551 break;
3552 }
3553 }
3554
3555 /* must give up the medium lock and medium tree lock as below we
3556 * go over snapshots, which needs a lock with higher lock order. */
3557 mediumLock.release();
3558 treeLock.release();
3559
3560 /* then, search through snapshots for the best diff in the given
3561 * hard disk's chain to base the new diff on */
3562
3563 ComObjPtr<Medium> base;
3564 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
3565 while (snap)
3566 {
3567 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
3568
3569 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
3570
3571 MediumAttachment *pAttachFound = NULL;
3572 uint32_t foundLevel = 0;
3573
3574 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
3575 it != snapAtts.end();
3576 ++it)
3577 {
3578 MediumAttachment *pAttach = *it;
3579 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3580 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3581 if (pMedium.isNull())
3582 continue;
3583
3584 uint32_t level = 0;
3585 if (pMedium->getBase(&level) == medium)
3586 {
3587 /* matched device, channel and bus (i.e. attached to the
3588 * same place) will win and immediately stop the search;
3589 * otherwise the attachment that has the youngest
3590 * descendant of medium will be used
3591 */
3592 if ( pAttach->getDevice() == aDevice
3593 && pAttach->getPort() == aControllerPort
3594 && pAttach->getControllerName() == aControllerName
3595 )
3596 {
3597 pAttachFound = pAttach;
3598 break;
3599 }
3600 else if ( !pAttachFound
3601 || level > foundLevel /* prefer younger */
3602 )
3603 {
3604 pAttachFound = pAttach;
3605 foundLevel = level;
3606 }
3607 }
3608 }
3609
3610 if (pAttachFound)
3611 {
3612 base = pAttachFound->getMedium();
3613 break;
3614 }
3615
3616 snap = snap->getParent();
3617 }
3618
3619 /* re-lock medium tree and the medium, as we need it below */
3620 treeLock.acquire();
3621 mediumLock.acquire();
3622
3623 /* found a suitable diff, use it as a base */
3624 if (!base.isNull())
3625 {
3626 medium = base;
3627 mediumCaller.attach(medium);
3628 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3629 mediumLock.attach(medium);
3630 }
3631 }
3632
3633 Utf8Str strFullSnapshotFolder;
3634 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
3635
3636 ComObjPtr<Medium> diff;
3637 diff.createObject();
3638 // store this diff in the same registry as the parent
3639 Guid uuidRegistryParent;
3640 if (!medium->getFirstRegistryMachineId(uuidRegistryParent))
3641 {
3642 // parent image has no registry: this can happen if we're attaching a new immutable
3643 // image that has not yet been attached (medium then points to the base and we're
3644 // creating the diff image for the immutable, and the parent is not yet registered);
3645 // put the parent in the machine registry then
3646 addMediumToRegistry(medium, llRegistriesThatNeedSaving, &uuidRegistryParent);
3647 }
3648 rc = diff->init(mParent,
3649 medium->getPreferredDiffFormat(),
3650 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
3651 uuidRegistryParent,
3652 &llRegistriesThatNeedSaving);
3653 if (FAILED(rc)) return rc;
3654
3655 /* Apply the normal locking logic to the entire chain. */
3656 MediumLockList *pMediumLockList(new MediumLockList());
3657 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
3658 true /* fMediumLockWrite */,
3659 medium,
3660 *pMediumLockList);
3661 if (SUCCEEDED(rc))
3662 {
3663 rc = pMediumLockList->Lock();
3664 if (FAILED(rc))
3665 setError(rc,
3666 tr("Could not lock medium when creating diff '%s'"),
3667 diff->getLocationFull().c_str());
3668 else
3669 {
3670 /* will leave the lock before the potentially lengthy operation, so
3671 * protect with the special state */
3672 MachineState_T oldState = mData->mMachineState;
3673 setMachineState(MachineState_SettingUp);
3674
3675 mediumLock.leave();
3676 treeLock.leave();
3677 alock.leave();
3678
3679 rc = medium->createDiffStorage(diff,
3680 MediumVariant_Standard,
3681 pMediumLockList,
3682 NULL /* aProgress */,
3683 true /* aWait */,
3684 &llRegistriesThatNeedSaving);
3685
3686 alock.enter();
3687 treeLock.enter();
3688 mediumLock.enter();
3689
3690 setMachineState(oldState);
3691 }
3692 }
3693
3694 /* Unlock the media and free the associated memory. */
3695 delete pMediumLockList;
3696
3697 if (FAILED(rc)) return rc;
3698
3699 /* use the created diff for the actual attachment */
3700 medium = diff;
3701 mediumCaller.attach(medium);
3702 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3703 mediumLock.attach(medium);
3704 }
3705 while (0);
3706
3707 ComObjPtr<MediumAttachment> attachment;
3708 attachment.createObject();
3709 rc = attachment->init(this,
3710 medium,
3711 aControllerName,
3712 aControllerPort,
3713 aDevice,
3714 aType,
3715 fIndirect,
3716 Utf8Str::Empty);
3717 if (FAILED(rc)) return rc;
3718
3719 if (associate && !medium.isNull())
3720 {
3721 // as the last step, associate the medium to the VM
3722 rc = medium->addBackReference(mData->mUuid);
3723 // here we can fail because of Deleting, or being in process of creating a Diff
3724 if (FAILED(rc)) return rc;
3725
3726 addMediumToRegistry(medium,
3727 llRegistriesThatNeedSaving,
3728 NULL /* Guid *puuid */);
3729 }
3730
3731 /* success: finally remember the attachment */
3732 setModified(IsModified_Storage);
3733 mMediaData.backup();
3734 mMediaData->mAttachments.push_back(attachment);
3735
3736 mediumLock.release();
3737 treeLock.leave();
3738 alock.release();
3739
3740 mParent->saveRegistries(llRegistriesThatNeedSaving);
3741
3742 return rc;
3743}
3744
3745STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
3746 LONG aDevice)
3747{
3748 CheckComArgStrNotEmptyOrNull(aControllerName);
3749
3750 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3751 aControllerName, aControllerPort, aDevice));
3752
3753 AutoCaller autoCaller(this);
3754 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3755
3756 GuidList llRegistriesThatNeedSaving;
3757
3758 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3759
3760 HRESULT rc = checkStateDependency(MutableStateDep);
3761 if (FAILED(rc)) return rc;
3762
3763 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3764
3765 if (Global::IsOnlineOrTransient(mData->mMachineState))
3766 return setError(VBOX_E_INVALID_VM_STATE,
3767 tr("Invalid machine state: %s"),
3768 Global::stringifyMachineState(mData->mMachineState));
3769
3770 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3771 aControllerName,
3772 aControllerPort,
3773 aDevice);
3774 if (!pAttach)
3775 return setError(VBOX_E_OBJECT_NOT_FOUND,
3776 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3777 aDevice, aControllerPort, aControllerName);
3778
3779 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */, &llRegistriesThatNeedSaving);
3780
3781 alock.release();
3782
3783 if (SUCCEEDED(rc))
3784 rc = mParent->saveRegistries(llRegistriesThatNeedSaving);
3785
3786 return rc;
3787}
3788
3789STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
3790 LONG aDevice, BOOL aPassthrough)
3791{
3792 CheckComArgStrNotEmptyOrNull(aControllerName);
3793
3794 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aPassthrough=%d\n",
3795 aControllerName, aControllerPort, aDevice, aPassthrough));
3796
3797 AutoCaller autoCaller(this);
3798 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3799
3800 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3801
3802 HRESULT rc = checkStateDependency(MutableStateDep);
3803 if (FAILED(rc)) return rc;
3804
3805 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3806
3807 if (Global::IsOnlineOrTransient(mData->mMachineState))
3808 return setError(VBOX_E_INVALID_VM_STATE,
3809 tr("Invalid machine state: %s"),
3810 Global::stringifyMachineState(mData->mMachineState));
3811
3812 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3813 aControllerName,
3814 aControllerPort,
3815 aDevice);
3816 if (!pAttach)
3817 return setError(VBOX_E_OBJECT_NOT_FOUND,
3818 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3819 aDevice, aControllerPort, aControllerName);
3820
3821
3822 setModified(IsModified_Storage);
3823 mMediaData.backup();
3824
3825 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3826
3827 if (pAttach->getType() != DeviceType_DVD)
3828 return setError(E_INVALIDARG,
3829 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3830 aDevice, aControllerPort, aControllerName);
3831 pAttach->updatePassthrough(!!aPassthrough);
3832
3833 return S_OK;
3834}
3835
3836STDMETHODIMP Machine::SetBandwidthGroupForDevice(IN_BSTR aControllerName, LONG aControllerPort,
3837 LONG aDevice, IBandwidthGroup *aBandwidthGroup)
3838{
3839 CheckComArgStrNotEmptyOrNull(aControllerName);
3840
3841 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3842 aControllerName, aControllerPort, aDevice));
3843
3844 AutoCaller autoCaller(this);
3845 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3846
3847 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3848
3849 HRESULT rc = checkStateDependency(MutableStateDep);
3850 if (FAILED(rc)) return rc;
3851
3852 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3853
3854 if (Global::IsOnlineOrTransient(mData->mMachineState))
3855 return setError(VBOX_E_INVALID_VM_STATE,
3856 tr("Invalid machine state: %s"),
3857 Global::stringifyMachineState(mData->mMachineState));
3858
3859 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3860 aControllerName,
3861 aControllerPort,
3862 aDevice);
3863 if (!pAttach)
3864 return setError(VBOX_E_OBJECT_NOT_FOUND,
3865 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3866 aDevice, aControllerPort, aControllerName);
3867
3868
3869 setModified(IsModified_Storage);
3870 mMediaData.backup();
3871
3872 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(aBandwidthGroup);
3873 if (aBandwidthGroup && group.isNull())
3874 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
3875
3876 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3877
3878 const Utf8Str strBandwidthGroupOld = pAttach->getBandwidthGroup();
3879 if (strBandwidthGroupOld.isNotEmpty())
3880 {
3881 /* Get the bandwidth group object and release it - this must not fail. */
3882 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
3883 rc = getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
3884 Assert(SUCCEEDED(rc));
3885
3886 pBandwidthGroupOld->release();
3887 pAttach->updateBandwidthGroup(Utf8Str::Empty);
3888 }
3889
3890 if (!group.isNull())
3891 {
3892 group->reference();
3893 pAttach->updateBandwidthGroup(group->getName());
3894 }
3895
3896 return S_OK;
3897}
3898
3899
3900STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
3901 LONG aControllerPort,
3902 LONG aDevice,
3903 IMedium *aMedium,
3904 BOOL aForce)
3905{
3906 int rc = S_OK;
3907 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aForce=%d\n",
3908 aControllerName, aControllerPort, aDevice, aForce));
3909
3910 CheckComArgStrNotEmptyOrNull(aControllerName);
3911
3912 AutoCaller autoCaller(this);
3913 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3914
3915 // request the host lock first, since might be calling Host methods for getting host drives;
3916 // next, protect the media tree all the while we're in here, as well as our member variables
3917 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
3918 this->lockHandle(),
3919 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3920
3921 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3922 aControllerName,
3923 aControllerPort,
3924 aDevice);
3925 if (pAttach.isNull())
3926 return setError(VBOX_E_OBJECT_NOT_FOUND,
3927 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
3928 aDevice, aControllerPort, aControllerName);
3929
3930 /* Remember previously mounted medium. The medium before taking the
3931 * backup is not necessarily the same thing. */
3932 ComObjPtr<Medium> oldmedium;
3933 oldmedium = pAttach->getMedium();
3934
3935 ComObjPtr<Medium> pMedium = static_cast<Medium*>(aMedium);
3936 if (aMedium && pMedium.isNull())
3937 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3938
3939 AutoCaller mediumCaller(pMedium);
3940 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3941
3942 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3943 if (pMedium)
3944 {
3945 DeviceType_T mediumType = pAttach->getType();
3946 switch (mediumType)
3947 {
3948 case DeviceType_DVD:
3949 case DeviceType_Floppy:
3950 break;
3951
3952 default:
3953 return setError(VBOX_E_INVALID_OBJECT_STATE,
3954 tr("The device at port %d, device %d of controller '%ls' of this virtual machine is not removeable"),
3955 aControllerPort,
3956 aDevice,
3957 aControllerName);
3958 }
3959 }
3960
3961 setModified(IsModified_Storage);
3962 mMediaData.backup();
3963
3964 GuidList llRegistriesThatNeedSaving;
3965
3966 {
3967 // The backup operation makes the pAttach reference point to the
3968 // old settings. Re-get the correct reference.
3969 pAttach = findAttachment(mMediaData->mAttachments,
3970 aControllerName,
3971 aControllerPort,
3972 aDevice);
3973 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3974 if (!oldmedium.isNull())
3975 oldmedium->removeBackReference(mData->mUuid);
3976 if (!pMedium.isNull())
3977 {
3978 pMedium->addBackReference(mData->mUuid);
3979
3980 addMediumToRegistry(pMedium, llRegistriesThatNeedSaving, NULL /* Guid *puuid */ );
3981 }
3982
3983 pAttach->updateMedium(pMedium);
3984 }
3985
3986 setModified(IsModified_Storage);
3987
3988 mediumLock.release();
3989 multiLock.release();
3990 rc = onMediumChange(pAttach, aForce);
3991 multiLock.acquire();
3992 mediumLock.acquire();
3993
3994 /* On error roll back this change only. */
3995 if (FAILED(rc))
3996 {
3997 if (!pMedium.isNull())
3998 pMedium->removeBackReference(mData->mUuid);
3999 pAttach = findAttachment(mMediaData->mAttachments,
4000 aControllerName,
4001 aControllerPort,
4002 aDevice);
4003 /* If the attachment is gone in the meantime, bail out. */
4004 if (pAttach.isNull())
4005 return rc;
4006 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4007 if (!oldmedium.isNull())
4008 oldmedium->addBackReference(mData->mUuid);
4009 pAttach->updateMedium(oldmedium);
4010 }
4011
4012 mediumLock.release();
4013 multiLock.release();
4014
4015 mParent->saveRegistries(llRegistriesThatNeedSaving);
4016
4017 return rc;
4018}
4019
4020STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
4021 LONG aControllerPort,
4022 LONG aDevice,
4023 IMedium **aMedium)
4024{
4025 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
4026 aControllerName, aControllerPort, aDevice));
4027
4028 CheckComArgStrNotEmptyOrNull(aControllerName);
4029 CheckComArgOutPointerValid(aMedium);
4030
4031 AutoCaller autoCaller(this);
4032 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4033
4034 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4035
4036 *aMedium = NULL;
4037
4038 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4039 aControllerName,
4040 aControllerPort,
4041 aDevice);
4042 if (pAttach.isNull())
4043 return setError(VBOX_E_OBJECT_NOT_FOUND,
4044 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4045 aDevice, aControllerPort, aControllerName);
4046
4047 pAttach->getMedium().queryInterfaceTo(aMedium);
4048
4049 return S_OK;
4050}
4051
4052STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
4053{
4054 CheckComArgOutPointerValid(port);
4055 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
4056
4057 AutoCaller autoCaller(this);
4058 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4059
4060 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4061
4062 mSerialPorts[slot].queryInterfaceTo(port);
4063
4064 return S_OK;
4065}
4066
4067STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
4068{
4069 CheckComArgOutPointerValid(port);
4070 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
4071
4072 AutoCaller autoCaller(this);
4073 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4074
4075 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4076
4077 mParallelPorts[slot].queryInterfaceTo(port);
4078
4079 return S_OK;
4080}
4081
4082STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
4083{
4084 CheckComArgOutPointerValid(adapter);
4085 CheckComArgExpr(slot, slot < RT_ELEMENTS(mNetworkAdapters));
4086
4087 AutoCaller autoCaller(this);
4088 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4089
4090 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4091
4092 mNetworkAdapters[slot].queryInterfaceTo(adapter);
4093
4094 return S_OK;
4095}
4096
4097STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
4098{
4099 if (ComSafeArrayOutIsNull(aKeys))
4100 return E_POINTER;
4101
4102 AutoCaller autoCaller(this);
4103 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4104
4105 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4106
4107 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
4108 int i = 0;
4109 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4110 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4111 ++it, ++i)
4112 {
4113 const Utf8Str &strKey = it->first;
4114 strKey.cloneTo(&saKeys[i]);
4115 }
4116 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
4117
4118 return S_OK;
4119 }
4120
4121 /**
4122 * @note Locks this object for reading.
4123 */
4124STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
4125 BSTR *aValue)
4126{
4127 CheckComArgStrNotEmptyOrNull(aKey);
4128 CheckComArgOutPointerValid(aValue);
4129
4130 AutoCaller autoCaller(this);
4131 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4132
4133 /* start with nothing found */
4134 Bstr bstrResult("");
4135
4136 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4137
4138 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
4139 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4140 // found:
4141 bstrResult = it->second; // source is a Utf8Str
4142
4143 /* return the result to caller (may be empty) */
4144 bstrResult.cloneTo(aValue);
4145
4146 return S_OK;
4147}
4148
4149 /**
4150 * @note Locks mParent for writing + this object for writing.
4151 */
4152STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
4153{
4154 CheckComArgStrNotEmptyOrNull(aKey);
4155
4156 AutoCaller autoCaller(this);
4157 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4158
4159 Utf8Str strKey(aKey);
4160 Utf8Str strValue(aValue);
4161 Utf8Str strOldValue; // empty
4162
4163 // locking note: we only hold the read lock briefly to look up the old value,
4164 // then release it and call the onExtraCanChange callbacks. There is a small
4165 // chance of a race insofar as the callback might be called twice if two callers
4166 // change the same key at the same time, but that's a much better solution
4167 // than the deadlock we had here before. The actual changing of the extradata
4168 // is then performed under the write lock and race-free.
4169
4170 // look up the old value first; if nothing has changed then we need not do anything
4171 {
4172 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
4173 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
4174 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4175 strOldValue = it->second;
4176 }
4177
4178 bool fChanged;
4179 if ((fChanged = (strOldValue != strValue)))
4180 {
4181 // ask for permission from all listeners outside the locks;
4182 // onExtraDataCanChange() only briefly requests the VirtualBox
4183 // lock to copy the list of callbacks to invoke
4184 Bstr error;
4185 Bstr bstrValue(aValue);
4186
4187 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue.raw(), error))
4188 {
4189 const char *sep = error.isEmpty() ? "" : ": ";
4190 CBSTR err = error.raw();
4191 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
4192 sep, err));
4193 return setError(E_ACCESSDENIED,
4194 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
4195 aKey,
4196 bstrValue.raw(),
4197 sep,
4198 err);
4199 }
4200
4201 // data is changing and change not vetoed: then write it out under the lock
4202 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4203
4204 if (isSnapshotMachine())
4205 {
4206 HRESULT rc = checkStateDependency(MutableStateDep);
4207 if (FAILED(rc)) return rc;
4208 }
4209
4210 if (strValue.isEmpty())
4211 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
4212 else
4213 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
4214 // creates a new key if needed
4215
4216 bool fNeedsGlobalSaveSettings = false;
4217 saveSettings(&fNeedsGlobalSaveSettings);
4218
4219 if (fNeedsGlobalSaveSettings)
4220 {
4221 // save the global settings; for that we should hold only the VirtualBox lock
4222 alock.release();
4223 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
4224 mParent->saveSettings();
4225 }
4226 }
4227
4228 // fire notification outside the lock
4229 if (fChanged)
4230 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
4231
4232 return S_OK;
4233}
4234
4235STDMETHODIMP Machine::SaveSettings()
4236{
4237 AutoCaller autoCaller(this);
4238 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4239
4240 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
4241
4242 /* when there was auto-conversion, we want to save the file even if
4243 * the VM is saved */
4244 HRESULT rc = checkStateDependency(MutableStateDep);
4245 if (FAILED(rc)) return rc;
4246
4247 /* the settings file path may never be null */
4248 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
4249
4250 /* save all VM data excluding snapshots */
4251 bool fNeedsGlobalSaveSettings = false;
4252 rc = saveSettings(&fNeedsGlobalSaveSettings);
4253 mlock.release();
4254
4255 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
4256 {
4257 // save the global settings; for that we should hold only the VirtualBox lock
4258 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
4259 rc = mParent->saveSettings();
4260 }
4261
4262 return rc;
4263}
4264
4265STDMETHODIMP Machine::DiscardSettings()
4266{
4267 AutoCaller autoCaller(this);
4268 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4269
4270 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4271
4272 HRESULT rc = checkStateDependency(MutableStateDep);
4273 if (FAILED(rc)) return rc;
4274
4275 /*
4276 * during this rollback, the session will be notified if data has
4277 * been actually changed
4278 */
4279 rollback(true /* aNotify */);
4280
4281 return S_OK;
4282}
4283
4284/** @note Locks objects! */
4285STDMETHODIMP Machine::Unregister(CleanupMode_T cleanupMode,
4286 ComSafeArrayOut(IMedium*, aMedia))
4287{
4288 // use AutoLimitedCaller because this call is valid on inaccessible machines as well
4289 AutoLimitedCaller autoCaller(this);
4290 AssertComRCReturnRC(autoCaller.rc());
4291
4292 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4293
4294 Guid id(getId());
4295
4296 if (mData->mSession.mState != SessionState_Unlocked)
4297 return setError(VBOX_E_INVALID_OBJECT_STATE,
4298 tr("Cannot unregister the machine '%s' while it is locked"),
4299 mUserData->s.strName.c_str());
4300
4301 // wait for state dependents to drop to zero
4302 ensureNoStateDependencies();
4303
4304 if (!mData->mAccessible)
4305 {
4306 // inaccessible maschines can only be unregistered; uninitialize ourselves
4307 // here because currently there may be no unregistered that are inaccessible
4308 // (this state combination is not supported). Note releasing the caller and
4309 // leaving the lock before calling uninit()
4310 alock.leave();
4311 autoCaller.release();
4312
4313 uninit();
4314
4315 mParent->unregisterMachine(this, id);
4316 // calls VirtualBox::saveSettings()
4317
4318 return S_OK;
4319 }
4320
4321 HRESULT rc = S_OK;
4322
4323 // discard saved state
4324 if (mData->mMachineState == MachineState_Saved)
4325 {
4326 // add the saved state file to the list of files the caller should delete
4327 Assert(!mSSData->strStateFilePath.isEmpty());
4328 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
4329
4330 mSSData->strStateFilePath.setNull();
4331
4332 // unconditionally set the machine state to powered off, we now
4333 // know no session has locked the machine
4334 mData->mMachineState = MachineState_PoweredOff;
4335 }
4336
4337 size_t cSnapshots = 0;
4338 if (mData->mFirstSnapshot)
4339 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4340 if (cSnapshots && cleanupMode == CleanupMode_UnregisterOnly)
4341 // fail now before we start detaching media
4342 return setError(VBOX_E_INVALID_OBJECT_STATE,
4343 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
4344 mUserData->s.strName.c_str(), cSnapshots);
4345
4346 // This list collects the medium objects from all medium attachments
4347 // which we will detach from the machine and its snapshots, in a specific
4348 // order which allows for closing all media without getting "media in use"
4349 // errors, simply by going through the list from the front to the back:
4350 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
4351 // and must be closed before the parent media from the snapshots, or closing the parents
4352 // will fail because they still have children);
4353 // 2) media from the youngest snapshots followed by those from the parent snapshots until
4354 // the root ("first") snapshot of the machine.
4355 MediaList llMedia;
4356
4357 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4358 && mMediaData->mAttachments.size()
4359 )
4360 {
4361 // we have media attachments: detach them all and add the Medium objects to our list
4362 if (cleanupMode != CleanupMode_UnregisterOnly)
4363 detachAllMedia(alock, NULL /* pSnapshot */, cleanupMode, llMedia);
4364 else
4365 return setError(VBOX_E_INVALID_OBJECT_STATE,
4366 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
4367 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
4368 }
4369
4370 if (cSnapshots)
4371 {
4372 // autoCleanup must be true here, or we would have failed above
4373
4374 // add the media from the medium attachments of the snapshots to llMedia
4375 // as well, after the "main" machine media; Snapshot::uninitRecursively()
4376 // calls Machine::detachAllMedia() for the snapshot machine, recursing
4377 // into the children first
4378
4379 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
4380 MachineState_T oldState = mData->mMachineState;
4381 mData->mMachineState = MachineState_DeletingSnapshot;
4382
4383 // make a copy of the first snapshot so the refcount does not drop to 0
4384 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
4385 // because of the AutoCaller voodoo)
4386 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
4387
4388 // GO!
4389 pFirstSnapshot->uninitRecursively(alock, cleanupMode, llMedia, mData->llFilesToDelete);
4390
4391 mData->mMachineState = oldState;
4392 }
4393
4394 if (FAILED(rc))
4395 {
4396 rollbackMedia();
4397 return rc;
4398 }
4399
4400 // commit all the media changes made above
4401 commitMedia();
4402
4403 mData->mRegistered = false;
4404
4405 // machine lock no longer needed
4406 alock.release();
4407
4408 // return media to caller
4409 SafeIfaceArray<IMedium> sfaMedia(llMedia);
4410 sfaMedia.detachTo(ComSafeArrayOutArg(aMedia));
4411
4412 mParent->unregisterMachine(this, id);
4413 // calls VirtualBox::saveSettings()
4414
4415 return S_OK;
4416}
4417
4418struct Machine::DeleteTask
4419{
4420 ComObjPtr<Machine> pMachine;
4421 std::list<Utf8Str> llFilesToDelete;
4422 ComObjPtr<Progress> pProgress;
4423 GuidList llRegistriesThatNeedSaving;
4424};
4425
4426STDMETHODIMP Machine::Delete(ComSafeArrayIn(IMedium*, aMedia), IProgress **aProgress)
4427{
4428 LogFlowFuncEnter();
4429
4430 AutoCaller autoCaller(this);
4431 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4432
4433 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4434
4435 HRESULT rc = checkStateDependency(MutableStateDep);
4436 if (FAILED(rc)) return rc;
4437
4438 if (mData->mRegistered)
4439 return setError(VBOX_E_INVALID_VM_STATE,
4440 tr("Cannot delete settings of a registered machine"));
4441
4442 DeleteTask *pTask = new DeleteTask;
4443 pTask->pMachine = this;
4444 com::SafeIfaceArray<IMedium> sfaMedia(ComSafeArrayInArg(aMedia));
4445
4446 // collect files to delete
4447 pTask->llFilesToDelete = mData->llFilesToDelete; // saved states pushed here by Unregister()
4448
4449 for (size_t i = 0; i < sfaMedia.size(); ++i)
4450 {
4451 IMedium *pIMedium(sfaMedia[i]);
4452 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
4453 if (pMedium.isNull())
4454 return setError(E_INVALIDARG, "The given medium pointer %d is invalid", i);
4455 AutoCaller mediumAutoCaller(pMedium);
4456 if (FAILED(mediumAutoCaller.rc())) return mediumAutoCaller.rc();
4457
4458 Utf8Str bstrLocation = pMedium->getLocationFull();
4459
4460 bool fDoesMediumNeedFileDeletion = pMedium->isMediumFormatFile();
4461
4462 // close the medium now; if that succeeds, then that means the medium is no longer
4463 // in use and we can add it to the list of files to delete
4464 rc = pMedium->close(&pTask->llRegistriesThatNeedSaving,
4465 mediumAutoCaller);
4466 if (SUCCEEDED(rc) && fDoesMediumNeedFileDeletion)
4467 pTask->llFilesToDelete.push_back(bstrLocation);
4468 }
4469 if (mData->pMachineConfigFile->fileExists())
4470 pTask->llFilesToDelete.push_back(mData->m_strConfigFileFull);
4471
4472 pTask->pProgress.createObject();
4473 pTask->pProgress->init(getVirtualBox(),
4474 static_cast<IMachine*>(this) /* aInitiator */,
4475 Bstr(tr("Deleting files")).raw(),
4476 true /* fCancellable */,
4477 pTask->llFilesToDelete.size() + 1, // cOperations
4478 BstrFmt(tr("Deleting '%s'"), pTask->llFilesToDelete.front().c_str()).raw());
4479
4480 int vrc = RTThreadCreate(NULL,
4481 Machine::deleteThread,
4482 (void*)pTask,
4483 0,
4484 RTTHREADTYPE_MAIN_WORKER,
4485 0,
4486 "MachineDelete");
4487
4488 pTask->pProgress.queryInterfaceTo(aProgress);
4489
4490 if (RT_FAILURE(vrc))
4491 {
4492 delete pTask;
4493 return setError(E_FAIL, "Could not create MachineDelete thread (%Rrc)", vrc);
4494 }
4495
4496 LogFlowFuncLeave();
4497
4498 return S_OK;
4499}
4500
4501/**
4502 * Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
4503 * calls Machine::deleteTaskWorker() on the actual machine object.
4504 * @param Thread
4505 * @param pvUser
4506 * @return
4507 */
4508/*static*/
4509DECLCALLBACK(int) Machine::deleteThread(RTTHREAD Thread, void *pvUser)
4510{
4511 LogFlowFuncEnter();
4512
4513 DeleteTask *pTask = (DeleteTask*)pvUser;
4514 Assert(pTask);
4515 Assert(pTask->pMachine);
4516 Assert(pTask->pProgress);
4517
4518 HRESULT rc = pTask->pMachine->deleteTaskWorker(*pTask);
4519 pTask->pProgress->notifyComplete(rc);
4520
4521 delete pTask;
4522
4523 LogFlowFuncLeave();
4524
4525 NOREF(Thread);
4526
4527 return VINF_SUCCESS;
4528}
4529
4530/**
4531 * Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
4532 * @param task
4533 * @return
4534 */
4535HRESULT Machine::deleteTaskWorker(DeleteTask &task)
4536{
4537 AutoCaller autoCaller(this);
4538 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4539
4540 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4541
4542 ULONG uLogHistoryCount = 3;
4543 ComPtr<ISystemProperties> systemProperties;
4544 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4545 if (!systemProperties.isNull())
4546 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4547
4548 // delete the files pushed on the task list by Machine::Delete()
4549 // (this includes saved states of the machine and snapshots and
4550 // medium storage files from the IMedium list passed in, and the
4551 // machine XML file)
4552 std::list<Utf8Str>::const_iterator it = task.llFilesToDelete.begin();
4553 while (it != task.llFilesToDelete.end())
4554 {
4555 const Utf8Str &strFile = *it;
4556 LogFunc(("Deleting file %s\n", strFile.c_str()));
4557 RTFileDelete(strFile.c_str());
4558
4559 ++it;
4560 if (it == task.llFilesToDelete.end())
4561 {
4562 task.pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
4563 break;
4564 }
4565
4566 task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
4567 }
4568
4569 /* delete the settings only when the file actually exists */
4570 if (mData->pMachineConfigFile->fileExists())
4571 {
4572 /* Delete any backup or uncommitted XML files. Ignore failures.
4573 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4574 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4575 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4576 RTFileDelete(otherXml.c_str());
4577 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4578 RTFileDelete(otherXml.c_str());
4579
4580 /* delete the Logs folder, nothing important should be left
4581 * there (we don't check for errors because the user might have
4582 * some private files there that we don't want to delete) */
4583 Utf8Str logFolder;
4584 getLogFolder(logFolder);
4585 Assert(logFolder.length());
4586 if (RTDirExists(logFolder.c_str()))
4587 {
4588 /* Delete all VBox.log[.N] files from the Logs folder
4589 * (this must be in sync with the rotation logic in
4590 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4591 * files that may have been created by the GUI. */
4592 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4593 logFolder.c_str(), RTPATH_DELIMITER);
4594 RTFileDelete(log.c_str());
4595 log = Utf8StrFmt("%s%cVBox.png",
4596 logFolder.c_str(), RTPATH_DELIMITER);
4597 RTFileDelete(log.c_str());
4598 for (int i = uLogHistoryCount; i > 0; i--)
4599 {
4600 log = Utf8StrFmt("%s%cVBox.log.%d",
4601 logFolder.c_str(), RTPATH_DELIMITER, i);
4602 RTFileDelete(log.c_str());
4603 log = Utf8StrFmt("%s%cVBox.png.%d",
4604 logFolder.c_str(), RTPATH_DELIMITER, i);
4605 RTFileDelete(log.c_str());
4606 }
4607
4608 RTDirRemove(logFolder.c_str());
4609 }
4610
4611 /* delete the Snapshots folder, nothing important should be left
4612 * there (we don't check for errors because the user might have
4613 * some private files there that we don't want to delete) */
4614 Utf8Str strFullSnapshotFolder;
4615 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4616 Assert(!strFullSnapshotFolder.isEmpty());
4617 if (RTDirExists(strFullSnapshotFolder.c_str()))
4618 RTDirRemove(strFullSnapshotFolder.c_str());
4619
4620 // delete the directory that contains the settings file, but only
4621 // if it matches the VM name
4622 Utf8Str settingsDir;
4623 if (isInOwnDir(&settingsDir))
4624 RTDirRemove(settingsDir.c_str());
4625 }
4626
4627 alock.release();
4628
4629 mParent->saveRegistries(task.llRegistriesThatNeedSaving);
4630
4631 return S_OK;
4632}
4633
4634STDMETHODIMP Machine::FindSnapshot(IN_BSTR aNameOrId, ISnapshot **aSnapshot)
4635{
4636 CheckComArgOutPointerValid(aSnapshot);
4637
4638 AutoCaller autoCaller(this);
4639 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4640
4641 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4642
4643 ComObjPtr<Snapshot> pSnapshot;
4644 HRESULT rc;
4645
4646 if (!aNameOrId || !*aNameOrId)
4647 // null case (caller wants root snapshot): findSnapshotById() handles this
4648 rc = findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
4649 else
4650 {
4651 Guid uuid(aNameOrId);
4652 if (!uuid.isEmpty())
4653 rc = findSnapshotById(uuid, pSnapshot, true /* aSetError */);
4654 else
4655 rc = findSnapshotByName(Utf8Str(aNameOrId), pSnapshot, true /* aSetError */);
4656 }
4657 pSnapshot.queryInterfaceTo(aSnapshot);
4658
4659 return rc;
4660}
4661
4662STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4663{
4664 CheckComArgStrNotEmptyOrNull(aName);
4665 CheckComArgStrNotEmptyOrNull(aHostPath);
4666
4667 AutoCaller autoCaller(this);
4668 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4669
4670 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4671
4672 HRESULT rc = checkStateDependency(MutableStateDep);
4673 if (FAILED(rc)) return rc;
4674
4675 Utf8Str strName(aName);
4676
4677 ComObjPtr<SharedFolder> sharedFolder;
4678 rc = findSharedFolder(strName, sharedFolder, false /* aSetError */);
4679 if (SUCCEEDED(rc))
4680 return setError(VBOX_E_OBJECT_IN_USE,
4681 tr("Shared folder named '%s' already exists"),
4682 strName.c_str());
4683
4684 sharedFolder.createObject();
4685 rc = sharedFolder->init(getMachine(),
4686 strName,
4687 aHostPath,
4688 !!aWritable,
4689 !!aAutoMount,
4690 true /* fFailOnError */);
4691 if (FAILED(rc)) return rc;
4692
4693 setModified(IsModified_SharedFolders);
4694 mHWData.backup();
4695 mHWData->mSharedFolders.push_back(sharedFolder);
4696
4697 /* inform the direct session if any */
4698 alock.leave();
4699 onSharedFolderChange();
4700
4701 return S_OK;
4702}
4703
4704STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4705{
4706 CheckComArgStrNotEmptyOrNull(aName);
4707
4708 AutoCaller autoCaller(this);
4709 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4710
4711 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4712
4713 HRESULT rc = checkStateDependency(MutableStateDep);
4714 if (FAILED(rc)) return rc;
4715
4716 ComObjPtr<SharedFolder> sharedFolder;
4717 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4718 if (FAILED(rc)) return rc;
4719
4720 setModified(IsModified_SharedFolders);
4721 mHWData.backup();
4722 mHWData->mSharedFolders.remove(sharedFolder);
4723
4724 /* inform the direct session if any */
4725 alock.leave();
4726 onSharedFolderChange();
4727
4728 return S_OK;
4729}
4730
4731STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4732{
4733 CheckComArgOutPointerValid(aCanShow);
4734
4735 /* start with No */
4736 *aCanShow = FALSE;
4737
4738 AutoCaller autoCaller(this);
4739 AssertComRCReturnRC(autoCaller.rc());
4740
4741 ComPtr<IInternalSessionControl> directControl;
4742 {
4743 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4744
4745 if (mData->mSession.mState != SessionState_Locked)
4746 return setError(VBOX_E_INVALID_VM_STATE,
4747 tr("Machine is not locked for session (session state: %s)"),
4748 Global::stringifySessionState(mData->mSession.mState));
4749
4750 directControl = mData->mSession.mDirectControl;
4751 }
4752
4753 /* ignore calls made after #OnSessionEnd() is called */
4754 if (!directControl)
4755 return S_OK;
4756
4757 LONG64 dummy;
4758 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
4759}
4760
4761STDMETHODIMP Machine::ShowConsoleWindow(LONG64 *aWinId)
4762{
4763 CheckComArgOutPointerValid(aWinId);
4764
4765 AutoCaller autoCaller(this);
4766 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4767
4768 ComPtr<IInternalSessionControl> directControl;
4769 {
4770 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4771
4772 if (mData->mSession.mState != SessionState_Locked)
4773 return setError(E_FAIL,
4774 tr("Machine is not locked for session (session state: %s)"),
4775 Global::stringifySessionState(mData->mSession.mState));
4776
4777 directControl = mData->mSession.mDirectControl;
4778 }
4779
4780 /* ignore calls made after #OnSessionEnd() is called */
4781 if (!directControl)
4782 return S_OK;
4783
4784 BOOL dummy;
4785 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
4786}
4787
4788#ifdef VBOX_WITH_GUEST_PROPS
4789/**
4790 * Look up a guest property in VBoxSVC's internal structures.
4791 */
4792HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4793 BSTR *aValue,
4794 LONG64 *aTimestamp,
4795 BSTR *aFlags) const
4796{
4797 using namespace guestProp;
4798
4799 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4800 Utf8Str strName(aName);
4801 HWData::GuestPropertyList::const_iterator it;
4802
4803 for (it = mHWData->mGuestProperties.begin();
4804 it != mHWData->mGuestProperties.end(); ++it)
4805 {
4806 if (it->strName == strName)
4807 {
4808 char szFlags[MAX_FLAGS_LEN + 1];
4809 it->strValue.cloneTo(aValue);
4810 *aTimestamp = it->mTimestamp;
4811 writeFlags(it->mFlags, szFlags);
4812 Bstr(szFlags).cloneTo(aFlags);
4813 break;
4814 }
4815 }
4816 return S_OK;
4817}
4818
4819/**
4820 * Query the VM that a guest property belongs to for the property.
4821 * @returns E_ACCESSDENIED if the VM process is not available or not
4822 * currently handling queries and the lookup should then be done in
4823 * VBoxSVC.
4824 */
4825HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4826 BSTR *aValue,
4827 LONG64 *aTimestamp,
4828 BSTR *aFlags) const
4829{
4830 HRESULT rc;
4831 ComPtr<IInternalSessionControl> directControl;
4832 directControl = mData->mSession.mDirectControl;
4833
4834 /* fail if we were called after #OnSessionEnd() is called. This is a
4835 * silly race condition. */
4836
4837 if (!directControl)
4838 rc = E_ACCESSDENIED;
4839 else
4840 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4841 false /* isSetter */,
4842 aValue, aTimestamp, aFlags);
4843 return rc;
4844}
4845#endif // VBOX_WITH_GUEST_PROPS
4846
4847STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4848 BSTR *aValue,
4849 LONG64 *aTimestamp,
4850 BSTR *aFlags)
4851{
4852#ifndef VBOX_WITH_GUEST_PROPS
4853 ReturnComNotImplemented();
4854#else // VBOX_WITH_GUEST_PROPS
4855 CheckComArgStrNotEmptyOrNull(aName);
4856 CheckComArgOutPointerValid(aValue);
4857 CheckComArgOutPointerValid(aTimestamp);
4858 CheckComArgOutPointerValid(aFlags);
4859
4860 AutoCaller autoCaller(this);
4861 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4862
4863 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4864 if (rc == E_ACCESSDENIED)
4865 /* The VM is not running or the service is not (yet) accessible */
4866 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4867 return rc;
4868#endif // VBOX_WITH_GUEST_PROPS
4869}
4870
4871STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4872{
4873 LONG64 dummyTimestamp;
4874 Bstr dummyFlags;
4875 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
4876}
4877
4878STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, LONG64 *aTimestamp)
4879{
4880 Bstr dummyValue;
4881 Bstr dummyFlags;
4882 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
4883}
4884
4885#ifdef VBOX_WITH_GUEST_PROPS
4886/**
4887 * Set a guest property in VBoxSVC's internal structures.
4888 */
4889HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4890 IN_BSTR aFlags)
4891{
4892 using namespace guestProp;
4893
4894 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4895 HRESULT rc = S_OK;
4896 HWData::GuestProperty property;
4897 property.mFlags = NILFLAG;
4898 bool found = false;
4899
4900 rc = checkStateDependency(MutableStateDep);
4901 if (FAILED(rc)) return rc;
4902
4903 try
4904 {
4905 Utf8Str utf8Name(aName);
4906 Utf8Str utf8Flags(aFlags);
4907 uint32_t fFlags = NILFLAG;
4908 if ( (aFlags != NULL)
4909 && RT_FAILURE(validateFlags(utf8Flags.c_str(), &fFlags))
4910 )
4911 return setError(E_INVALIDARG,
4912 tr("Invalid flag values: '%ls'"),
4913 aFlags);
4914
4915 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
4916 * know, this is simple and do an OK job atm.) */
4917 HWData::GuestPropertyList::iterator it;
4918 for (it = mHWData->mGuestProperties.begin();
4919 it != mHWData->mGuestProperties.end(); ++it)
4920 if (it->strName == utf8Name)
4921 {
4922 property = *it;
4923 if (it->mFlags & (RDONLYHOST))
4924 rc = setError(E_ACCESSDENIED,
4925 tr("The property '%ls' cannot be changed by the host"),
4926 aName);
4927 else
4928 {
4929 setModified(IsModified_MachineData);
4930 mHWData.backup(); // @todo r=dj backup in a loop?!?
4931
4932 /* The backup() operation invalidates our iterator, so
4933 * get a new one. */
4934 for (it = mHWData->mGuestProperties.begin();
4935 it->strName != utf8Name;
4936 ++it)
4937 ;
4938 mHWData->mGuestProperties.erase(it);
4939 }
4940 found = true;
4941 break;
4942 }
4943 if (found && SUCCEEDED(rc))
4944 {
4945 if (*aValue)
4946 {
4947 RTTIMESPEC time;
4948 property.strValue = aValue;
4949 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4950 if (aFlags != NULL)
4951 property.mFlags = fFlags;
4952 mHWData->mGuestProperties.push_back(property);
4953 }
4954 }
4955 else if (SUCCEEDED(rc) && *aValue)
4956 {
4957 RTTIMESPEC time;
4958 setModified(IsModified_MachineData);
4959 mHWData.backup();
4960 property.strName = aName;
4961 property.strValue = aValue;
4962 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4963 property.mFlags = fFlags;
4964 mHWData->mGuestProperties.push_back(property);
4965 }
4966 if ( SUCCEEDED(rc)
4967 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
4968 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
4969 RTSTR_MAX,
4970 utf8Name.c_str(),
4971 RTSTR_MAX,
4972 NULL)
4973 )
4974 )
4975 {
4976 /** @todo r=bird: Why aren't we leaving the lock here? The
4977 * same code in PushGuestProperty does... */
4978 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
4979 }
4980 }
4981 catch (std::bad_alloc &)
4982 {
4983 rc = E_OUTOFMEMORY;
4984 }
4985
4986 return rc;
4987}
4988
4989/**
4990 * Set a property on the VM that that property belongs to.
4991 * @returns E_ACCESSDENIED if the VM process is not available or not
4992 * currently handling queries and the setting should then be done in
4993 * VBoxSVC.
4994 */
4995HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
4996 IN_BSTR aFlags)
4997{
4998 HRESULT rc;
4999
5000 try
5001 {
5002 ComPtr<IInternalSessionControl> directControl = mData->mSession.mDirectControl;
5003
5004 BSTR dummy = NULL; /* will not be changed (setter) */
5005 LONG64 dummy64;
5006 if (!directControl)
5007 rc = E_ACCESSDENIED;
5008 else
5009 /** @todo Fix when adding DeleteGuestProperty(),
5010 see defect. */
5011 rc = directControl->AccessGuestProperty(aName, aValue, aFlags,
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 CheckComArgMaybeNull(aFlags);
5032 CheckComArgMaybeNull(aValue);
5033
5034 AutoCaller autoCaller(this);
5035 if (FAILED(autoCaller.rc()))
5036 return autoCaller.rc();
5037
5038 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
5039 if (rc == E_ACCESSDENIED)
5040 /* The VM is not running or the service is not (yet) accessible */
5041 rc = setGuestPropertyToService(aName, aValue, aFlags);
5042 return rc;
5043#endif // VBOX_WITH_GUEST_PROPS
5044}
5045
5046STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
5047{
5048 return SetGuestProperty(aName, aValue, NULL);
5049}
5050
5051#ifdef VBOX_WITH_GUEST_PROPS
5052/**
5053 * Enumerate the guest properties in VBoxSVC's internal structures.
5054 */
5055HRESULT Machine::enumerateGuestPropertiesInService
5056 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5057 ComSafeArrayOut(BSTR, aValues),
5058 ComSafeArrayOut(LONG64, aTimestamps),
5059 ComSafeArrayOut(BSTR, aFlags))
5060{
5061 using namespace guestProp;
5062
5063 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5064 Utf8Str strPatterns(aPatterns);
5065
5066 /*
5067 * Look for matching patterns and build up a list.
5068 */
5069 HWData::GuestPropertyList propList;
5070 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
5071 it != mHWData->mGuestProperties.end();
5072 ++it)
5073 if ( strPatterns.isEmpty()
5074 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5075 RTSTR_MAX,
5076 it->strName.c_str(),
5077 RTSTR_MAX,
5078 NULL)
5079 )
5080 propList.push_back(*it);
5081
5082 /*
5083 * And build up the arrays for returning the property information.
5084 */
5085 size_t cEntries = propList.size();
5086 SafeArray<BSTR> names(cEntries);
5087 SafeArray<BSTR> values(cEntries);
5088 SafeArray<LONG64> timestamps(cEntries);
5089 SafeArray<BSTR> flags(cEntries);
5090 size_t iProp = 0;
5091 for (HWData::GuestPropertyList::iterator it = propList.begin();
5092 it != propList.end();
5093 ++it)
5094 {
5095 char szFlags[MAX_FLAGS_LEN + 1];
5096 it->strName.cloneTo(&names[iProp]);
5097 it->strValue.cloneTo(&values[iProp]);
5098 timestamps[iProp] = it->mTimestamp;
5099 writeFlags(it->mFlags, szFlags);
5100 Bstr(szFlags).cloneTo(&flags[iProp]);
5101 ++iProp;
5102 }
5103 names.detachTo(ComSafeArrayOutArg(aNames));
5104 values.detachTo(ComSafeArrayOutArg(aValues));
5105 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
5106 flags.detachTo(ComSafeArrayOutArg(aFlags));
5107 return S_OK;
5108}
5109
5110/**
5111 * Enumerate the properties managed by a VM.
5112 * @returns E_ACCESSDENIED if the VM process is not available or not
5113 * currently handling queries and the setting should then be done in
5114 * VBoxSVC.
5115 */
5116HRESULT Machine::enumerateGuestPropertiesOnVM
5117 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5118 ComSafeArrayOut(BSTR, aValues),
5119 ComSafeArrayOut(LONG64, aTimestamps),
5120 ComSafeArrayOut(BSTR, aFlags))
5121{
5122 HRESULT rc;
5123 ComPtr<IInternalSessionControl> directControl;
5124 directControl = mData->mSession.mDirectControl;
5125
5126 if (!directControl)
5127 rc = E_ACCESSDENIED;
5128 else
5129 rc = directControl->EnumerateGuestProperties
5130 (aPatterns, ComSafeArrayOutArg(aNames),
5131 ComSafeArrayOutArg(aValues),
5132 ComSafeArrayOutArg(aTimestamps),
5133 ComSafeArrayOutArg(aFlags));
5134 return rc;
5135}
5136#endif // VBOX_WITH_GUEST_PROPS
5137
5138STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
5139 ComSafeArrayOut(BSTR, aNames),
5140 ComSafeArrayOut(BSTR, aValues),
5141 ComSafeArrayOut(LONG64, aTimestamps),
5142 ComSafeArrayOut(BSTR, aFlags))
5143{
5144#ifndef VBOX_WITH_GUEST_PROPS
5145 ReturnComNotImplemented();
5146#else // VBOX_WITH_GUEST_PROPS
5147 CheckComArgMaybeNull(aPatterns);
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 fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
5937 tr("No host PCI device %08x attached"),
5938 hostAddress
5939 );
5940}
5941
5942STDMETHODIMP Machine::COMGETTER(PciDeviceAssignments)(ComSafeArrayOut(IPciDeviceAttachment *, aAssignments))
5943{
5944 CheckComArgOutSafeArrayPointerValid(aAssignments);
5945
5946 AutoCaller autoCaller(this);
5947 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5948
5949 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5950
5951 SafeIfaceArray<IPciDeviceAttachment> assignments(mHWData->mPciDeviceAssignments);
5952 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
5953
5954 return S_OK;
5955}
5956
5957STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
5958{
5959 CheckComArgOutPointerValid(aBandwidthControl);
5960
5961 AutoCaller autoCaller(this);
5962 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5963
5964 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
5965
5966 return S_OK;
5967}
5968
5969// public methods for internal purposes
5970/////////////////////////////////////////////////////////////////////////////
5971
5972/**
5973 * Adds the given IsModified_* flag to the dirty flags of the machine.
5974 * This must be called either during loadSettings or under the machine write lock.
5975 * @param fl
5976 */
5977void Machine::setModified(uint32_t fl)
5978{
5979 mData->flModifications |= fl;
5980}
5981
5982/**
5983 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
5984 * care of the write locking.
5985 *
5986 * @param fModifications The flag to add.
5987 */
5988void Machine::setModifiedLock(uint32_t fModification)
5989{
5990 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5991 mData->flModifications |= fModification;
5992}
5993
5994/**
5995 * Saves the registry entry of this machine to the given configuration node.
5996 *
5997 * @param aEntryNode Node to save the registry entry to.
5998 *
5999 * @note locks this object for reading.
6000 */
6001HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
6002{
6003 AutoLimitedCaller autoCaller(this);
6004 AssertComRCReturnRC(autoCaller.rc());
6005
6006 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6007
6008 data.uuid = mData->mUuid;
6009 data.strSettingsFile = mData->m_strConfigFile;
6010
6011 return S_OK;
6012}
6013
6014/**
6015 * Calculates the absolute path of the given path taking the directory of the
6016 * machine settings file as the current directory.
6017 *
6018 * @param aPath Path to calculate the absolute path for.
6019 * @param aResult Where to put the result (used only on success, can be the
6020 * same Utf8Str instance as passed in @a aPath).
6021 * @return IPRT result.
6022 *
6023 * @note Locks this object for reading.
6024 */
6025int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
6026{
6027 AutoCaller autoCaller(this);
6028 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6029
6030 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6031
6032 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
6033
6034 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
6035
6036 strSettingsDir.stripFilename();
6037 char folder[RTPATH_MAX];
6038 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
6039 if (RT_SUCCESS(vrc))
6040 aResult = folder;
6041
6042 return vrc;
6043}
6044
6045/**
6046 * Copies strSource to strTarget, making it relative to the machine folder
6047 * if it is a subdirectory thereof, or simply copying it otherwise.
6048 *
6049 * @param strSource Path to evaluate and copy.
6050 * @param strTarget Buffer to receive target path.
6051 *
6052 * @note Locks this object for reading.
6053 */
6054void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6055 Utf8Str &strTarget)
6056{
6057 AutoCaller autoCaller(this);
6058 AssertComRCReturn(autoCaller.rc(), (void)0);
6059
6060 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6061
6062 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6063 // use strTarget as a temporary buffer to hold the machine settings dir
6064 strTarget = mData->m_strConfigFileFull;
6065 strTarget.stripFilename();
6066 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6067 {
6068 // is relative: then append what's left
6069 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6070 // for empty paths (only possible for subdirs) use "." to avoid
6071 // triggering default settings for not present config attributes.
6072 if (strTarget.isEmpty())
6073 strTarget = ".";
6074 }
6075 else
6076 // is not relative: then overwrite
6077 strTarget = strSource;
6078}
6079
6080/**
6081 * Returns the full path to the machine's log folder in the
6082 * \a aLogFolder argument.
6083 */
6084void Machine::getLogFolder(Utf8Str &aLogFolder)
6085{
6086 AutoCaller autoCaller(this);
6087 AssertComRCReturnVoid(autoCaller.rc());
6088
6089 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6090
6091 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6092 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6093 aLogFolder.append(RTPATH_DELIMITER);
6094 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6095}
6096
6097/**
6098 * Returns the full path to the machine's log file for an given index.
6099 */
6100Utf8Str Machine::queryLogFilename(ULONG idx)
6101{
6102 Utf8Str logFolder;
6103 getLogFolder(logFolder);
6104 Assert(logFolder.length());
6105 Utf8Str log;
6106 if (idx == 0)
6107 log = Utf8StrFmt("%s%cVBox.log",
6108 logFolder.c_str(), RTPATH_DELIMITER);
6109 else
6110 log = Utf8StrFmt("%s%cVBox.log.%d",
6111 logFolder.c_str(), RTPATH_DELIMITER, idx);
6112 return log;
6113}
6114
6115/**
6116 * Composes a unique saved state filename based on the current system time. The filename is
6117 * granular to the second so this will work so long as no more than one snapshot is taken on
6118 * a machine per second.
6119 *
6120 * Before version 4.1, we used this formula for saved state files:
6121 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6122 * which no longer works because saved state files can now be shared between the saved state of the
6123 * "saved" machine and an online snapshot, and the following would cause problems:
6124 * 1) save machine
6125 * 2) create online snapshot from that machine state --> reusing saved state file
6126 * 3) save machine again --> filename would be reused, breaking the online snapshot
6127 *
6128 * So instead we now use a timestamp.
6129 *
6130 * @param str
6131 */
6132void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6133{
6134 AutoCaller autoCaller(this);
6135 AssertComRCReturnVoid(autoCaller.rc());
6136
6137 {
6138 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6139 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6140 }
6141
6142 RTTIMESPEC ts;
6143 RTTimeNow(&ts);
6144 RTTIME time;
6145 RTTimeExplode(&time, &ts);
6146
6147 strStateFilePath += RTPATH_DELIMITER;
6148 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
6149 time.i32Year, time.u8Month, time.u8MonthDay,
6150 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
6151}
6152
6153/**
6154 * @note Locks this object for writing, calls the client process
6155 * (inside the lock).
6156 */
6157HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
6158 IN_BSTR aType,
6159 IN_BSTR aEnvironment,
6160 ProgressProxy *aProgress)
6161{
6162 LogFlowThisFuncEnter();
6163
6164 AssertReturn(aControl, E_FAIL);
6165 AssertReturn(aProgress, E_FAIL);
6166
6167 AutoCaller autoCaller(this);
6168 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6169
6170 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6171
6172 if (!mData->mRegistered)
6173 return setError(E_UNEXPECTED,
6174 tr("The machine '%s' is not registered"),
6175 mUserData->s.strName.c_str());
6176
6177 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6178
6179 if ( mData->mSession.mState == SessionState_Locked
6180 || mData->mSession.mState == SessionState_Spawning
6181 || mData->mSession.mState == SessionState_Unlocking)
6182 return setError(VBOX_E_INVALID_OBJECT_STATE,
6183 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6184 mUserData->s.strName.c_str());
6185
6186 /* may not be busy */
6187 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6188
6189 /* get the path to the executable */
6190 char szPath[RTPATH_MAX];
6191 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6192 size_t sz = strlen(szPath);
6193 szPath[sz++] = RTPATH_DELIMITER;
6194 szPath[sz] = 0;
6195 char *cmd = szPath + sz;
6196 sz = RTPATH_MAX - sz;
6197
6198 int vrc = VINF_SUCCESS;
6199 RTPROCESS pid = NIL_RTPROCESS;
6200
6201 RTENV env = RTENV_DEFAULT;
6202
6203 if (aEnvironment != NULL && *aEnvironment)
6204 {
6205 char *newEnvStr = NULL;
6206
6207 do
6208 {
6209 /* clone the current environment */
6210 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6211 AssertRCBreakStmt(vrc2, vrc = vrc2);
6212
6213 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
6214 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6215
6216 /* put new variables to the environment
6217 * (ignore empty variable names here since RTEnv API
6218 * intentionally doesn't do that) */
6219 char *var = newEnvStr;
6220 for (char *p = newEnvStr; *p; ++p)
6221 {
6222 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6223 {
6224 *p = '\0';
6225 if (*var)
6226 {
6227 char *val = strchr(var, '=');
6228 if (val)
6229 {
6230 *val++ = '\0';
6231 vrc2 = RTEnvSetEx(env, var, val);
6232 }
6233 else
6234 vrc2 = RTEnvUnsetEx(env, var);
6235 if (RT_FAILURE(vrc2))
6236 break;
6237 }
6238 var = p + 1;
6239 }
6240 }
6241 if (RT_SUCCESS(vrc2) && *var)
6242 vrc2 = RTEnvPutEx(env, var);
6243
6244 AssertRCBreakStmt(vrc2, vrc = vrc2);
6245 }
6246 while (0);
6247
6248 if (newEnvStr != NULL)
6249 RTStrFree(newEnvStr);
6250 }
6251
6252 Utf8Str strType(aType);
6253
6254 /* Qt is default */
6255#ifdef VBOX_WITH_QTGUI
6256 if (strType == "gui" || strType == "GUI/Qt")
6257 {
6258# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6259 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6260# else
6261 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6262# endif
6263 Assert(sz >= sizeof(VirtualBox_exe));
6264 strcpy(cmd, VirtualBox_exe);
6265
6266 Utf8Str idStr = mData->mUuid.toString();
6267 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6268 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6269 }
6270#else /* !VBOX_WITH_QTGUI */
6271 if (0)
6272 ;
6273#endif /* VBOX_WITH_QTGUI */
6274
6275 else
6276
6277#ifdef VBOX_WITH_VBOXSDL
6278 if (strType == "sdl" || strType == "GUI/SDL")
6279 {
6280 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6281 Assert(sz >= sizeof(VBoxSDL_exe));
6282 strcpy(cmd, VBoxSDL_exe);
6283
6284 Utf8Str idStr = mData->mUuid.toString();
6285 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6286 fprintf(stderr, "SDL=%s\n", szPath);
6287 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6288 }
6289#else /* !VBOX_WITH_VBOXSDL */
6290 if (0)
6291 ;
6292#endif /* !VBOX_WITH_VBOXSDL */
6293
6294 else
6295
6296#ifdef VBOX_WITH_HEADLESS
6297 if ( strType == "headless"
6298 || strType == "capture"
6299 || strType == "vrdp" /* Deprecated. Same as headless. */
6300 )
6301 {
6302 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6303 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6304 * and a VM works even if the server has not been installed.
6305 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6306 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6307 * differently in 4.0 and 3.x.
6308 */
6309 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6310 Assert(sz >= sizeof(VBoxHeadless_exe));
6311 strcpy(cmd, VBoxHeadless_exe);
6312
6313 Utf8Str idStr = mData->mUuid.toString();
6314 /* Leave space for "--capture" arg. */
6315 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
6316 "--startvm", idStr.c_str(),
6317 "--vrde", "config",
6318 0, /* For "--capture". */
6319 0 };
6320 if (strType == "capture")
6321 {
6322 unsigned pos = RT_ELEMENTS(args) - 2;
6323 args[pos] = "--capture";
6324 }
6325 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6326 }
6327#else /* !VBOX_WITH_HEADLESS */
6328 if (0)
6329 ;
6330#endif /* !VBOX_WITH_HEADLESS */
6331 else
6332 {
6333 RTEnvDestroy(env);
6334 return setError(E_INVALIDARG,
6335 tr("Invalid session type: '%s'"),
6336 strType.c_str());
6337 }
6338
6339 RTEnvDestroy(env);
6340
6341 if (RT_FAILURE(vrc))
6342 return setError(VBOX_E_IPRT_ERROR,
6343 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6344 mUserData->s.strName.c_str(), vrc);
6345
6346 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6347
6348 /*
6349 * Note that we don't leave the lock here before calling the client,
6350 * because it doesn't need to call us back if called with a NULL argument.
6351 * Leaving the lock here is dangerous because we didn't prepare the
6352 * launch data yet, but the client we've just started may happen to be
6353 * too fast and call openSession() that will fail (because of PID, etc.),
6354 * so that the Machine will never get out of the Spawning session state.
6355 */
6356
6357 /* inform the session that it will be a remote one */
6358 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6359 HRESULT rc = aControl->AssignMachine(NULL);
6360 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6361
6362 if (FAILED(rc))
6363 {
6364 /* restore the session state */
6365 mData->mSession.mState = SessionState_Unlocked;
6366 /* The failure may occur w/o any error info (from RPC), so provide one */
6367 return setError(VBOX_E_VM_ERROR,
6368 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6369 }
6370
6371 /* attach launch data to the machine */
6372 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6373 mData->mSession.mRemoteControls.push_back (aControl);
6374 mData->mSession.mProgress = aProgress;
6375 mData->mSession.mPid = pid;
6376 mData->mSession.mState = SessionState_Spawning;
6377 mData->mSession.mType = strType;
6378
6379 LogFlowThisFuncLeave();
6380 return S_OK;
6381}
6382
6383/**
6384 * Returns @c true if the given machine has an open direct session and returns
6385 * the session machine instance and additional session data (on some platforms)
6386 * if so.
6387 *
6388 * Note that when the method returns @c false, the arguments remain unchanged.
6389 *
6390 * @param aMachine Session machine object.
6391 * @param aControl Direct session control object (optional).
6392 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6393 *
6394 * @note locks this object for reading.
6395 */
6396#if defined(RT_OS_WINDOWS)
6397bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6398 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6399 HANDLE *aIPCSem /*= NULL*/,
6400 bool aAllowClosing /*= false*/)
6401#elif defined(RT_OS_OS2)
6402bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6403 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6404 HMTX *aIPCSem /*= NULL*/,
6405 bool aAllowClosing /*= false*/)
6406#else
6407bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6408 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6409 bool aAllowClosing /*= false*/)
6410#endif
6411{
6412 AutoLimitedCaller autoCaller(this);
6413 AssertComRCReturn(autoCaller.rc(), false);
6414
6415 /* just return false for inaccessible machines */
6416 if (autoCaller.state() != Ready)
6417 return false;
6418
6419 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6420
6421 if ( mData->mSession.mState == SessionState_Locked
6422 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6423 )
6424 {
6425 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6426
6427 aMachine = mData->mSession.mMachine;
6428
6429 if (aControl != NULL)
6430 *aControl = mData->mSession.mDirectControl;
6431
6432#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6433 /* Additional session data */
6434 if (aIPCSem != NULL)
6435 *aIPCSem = aMachine->mIPCSem;
6436#endif
6437 return true;
6438 }
6439
6440 return false;
6441}
6442
6443/**
6444 * Returns @c true if the given machine has an spawning direct session and
6445 * returns and additional session data (on some platforms) if so.
6446 *
6447 * Note that when the method returns @c false, the arguments remain unchanged.
6448 *
6449 * @param aPID PID of the spawned direct session process.
6450 *
6451 * @note locks this object for reading.
6452 */
6453#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6454bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6455#else
6456bool Machine::isSessionSpawning()
6457#endif
6458{
6459 AutoLimitedCaller autoCaller(this);
6460 AssertComRCReturn(autoCaller.rc(), false);
6461
6462 /* just return false for inaccessible machines */
6463 if (autoCaller.state() != Ready)
6464 return false;
6465
6466 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6467
6468 if (mData->mSession.mState == SessionState_Spawning)
6469 {
6470#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6471 /* Additional session data */
6472 if (aPID != NULL)
6473 {
6474 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6475 *aPID = mData->mSession.mPid;
6476 }
6477#endif
6478 return true;
6479 }
6480
6481 return false;
6482}
6483
6484/**
6485 * Called from the client watcher thread to check for unexpected client process
6486 * death during Session_Spawning state (e.g. before it successfully opened a
6487 * direct session).
6488 *
6489 * On Win32 and on OS/2, this method is called only when we've got the
6490 * direct client's process termination notification, so it always returns @c
6491 * true.
6492 *
6493 * On other platforms, this method returns @c true if the client process is
6494 * terminated and @c false if it's still alive.
6495 *
6496 * @note Locks this object for writing.
6497 */
6498bool Machine::checkForSpawnFailure()
6499{
6500 AutoCaller autoCaller(this);
6501 if (!autoCaller.isOk())
6502 {
6503 /* nothing to do */
6504 LogFlowThisFunc(("Already uninitialized!\n"));
6505 return true;
6506 }
6507
6508 /* VirtualBox::addProcessToReap() needs a write lock */
6509 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6510
6511 if (mData->mSession.mState != SessionState_Spawning)
6512 {
6513 /* nothing to do */
6514 LogFlowThisFunc(("Not spawning any more!\n"));
6515 return true;
6516 }
6517
6518 HRESULT rc = S_OK;
6519
6520#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6521
6522 /* the process was already unexpectedly terminated, we just need to set an
6523 * error and finalize session spawning */
6524 rc = setError(E_FAIL,
6525 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6526 getName().c_str());
6527#else
6528
6529 /* PID not yet initialized, skip check. */
6530 if (mData->mSession.mPid == NIL_RTPROCESS)
6531 return false;
6532
6533 RTPROCSTATUS status;
6534 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6535 &status);
6536
6537 if (vrc != VERR_PROCESS_RUNNING)
6538 {
6539 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6540 rc = setError(E_FAIL,
6541 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6542 getName().c_str(), status.iStatus);
6543 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6544 rc = setError(E_FAIL,
6545 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6546 getName().c_str(), status.iStatus);
6547 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6548 rc = setError(E_FAIL,
6549 tr("The virtual machine '%s' has terminated abnormally"),
6550 getName().c_str(), status.iStatus);
6551 else
6552 rc = setError(E_FAIL,
6553 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6554 getName().c_str(), rc);
6555 }
6556
6557#endif
6558
6559 if (FAILED(rc))
6560 {
6561 /* Close the remote session, remove the remote control from the list
6562 * and reset session state to Closed (@note keep the code in sync with
6563 * the relevant part in checkForSpawnFailure()). */
6564
6565 Assert(mData->mSession.mRemoteControls.size() == 1);
6566 if (mData->mSession.mRemoteControls.size() == 1)
6567 {
6568 ErrorInfoKeeper eik;
6569 mData->mSession.mRemoteControls.front()->Uninitialize();
6570 }
6571
6572 mData->mSession.mRemoteControls.clear();
6573 mData->mSession.mState = SessionState_Unlocked;
6574
6575 /* finalize the progress after setting the state */
6576 if (!mData->mSession.mProgress.isNull())
6577 {
6578 mData->mSession.mProgress->notifyComplete(rc);
6579 mData->mSession.mProgress.setNull();
6580 }
6581
6582 mParent->addProcessToReap(mData->mSession.mPid);
6583 mData->mSession.mPid = NIL_RTPROCESS;
6584
6585 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6586 return true;
6587 }
6588
6589 return false;
6590}
6591
6592/**
6593 * Checks whether the machine can be registered. If so, commits and saves
6594 * all settings.
6595 *
6596 * @note Must be called from mParent's write lock. Locks this object and
6597 * children for writing.
6598 */
6599HRESULT Machine::prepareRegister()
6600{
6601 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6602
6603 AutoLimitedCaller autoCaller(this);
6604 AssertComRCReturnRC(autoCaller.rc());
6605
6606 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6607
6608 /* wait for state dependents to drop to zero */
6609 ensureNoStateDependencies();
6610
6611 if (!mData->mAccessible)
6612 return setError(VBOX_E_INVALID_OBJECT_STATE,
6613 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6614 mUserData->s.strName.c_str(),
6615 mData->mUuid.toString().c_str());
6616
6617 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6618
6619 if (mData->mRegistered)
6620 return setError(VBOX_E_INVALID_OBJECT_STATE,
6621 tr("The machine '%s' with UUID {%s} is already registered"),
6622 mUserData->s.strName.c_str(),
6623 mData->mUuid.toString().c_str());
6624
6625 HRESULT rc = S_OK;
6626
6627 // Ensure the settings are saved. If we are going to be registered and
6628 // no config file exists yet, create it by calling saveSettings() too.
6629 if ( (mData->flModifications)
6630 || (!mData->pMachineConfigFile->fileExists())
6631 )
6632 {
6633 rc = saveSettings(NULL);
6634 // no need to check whether VirtualBox.xml needs saving too since
6635 // we can't have a machine XML file rename pending
6636 if (FAILED(rc)) return rc;
6637 }
6638
6639 /* more config checking goes here */
6640
6641 if (SUCCEEDED(rc))
6642 {
6643 /* we may have had implicit modifications we want to fix on success */
6644 commit();
6645
6646 mData->mRegistered = true;
6647 }
6648 else
6649 {
6650 /* we may have had implicit modifications we want to cancel on failure*/
6651 rollback(false /* aNotify */);
6652 }
6653
6654 return rc;
6655}
6656
6657/**
6658 * Increases the number of objects dependent on the machine state or on the
6659 * registered state. Guarantees that these two states will not change at least
6660 * until #releaseStateDependency() is called.
6661 *
6662 * Depending on the @a aDepType value, additional state checks may be made.
6663 * These checks will set extended error info on failure. See
6664 * #checkStateDependency() for more info.
6665 *
6666 * If this method returns a failure, the dependency is not added and the caller
6667 * is not allowed to rely on any particular machine state or registration state
6668 * value and may return the failed result code to the upper level.
6669 *
6670 * @param aDepType Dependency type to add.
6671 * @param aState Current machine state (NULL if not interested).
6672 * @param aRegistered Current registered state (NULL if not interested).
6673 *
6674 * @note Locks this object for writing.
6675 */
6676HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6677 MachineState_T *aState /* = NULL */,
6678 BOOL *aRegistered /* = NULL */)
6679{
6680 AutoCaller autoCaller(this);
6681 AssertComRCReturnRC(autoCaller.rc());
6682
6683 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6684
6685 HRESULT rc = checkStateDependency(aDepType);
6686 if (FAILED(rc)) return rc;
6687
6688 {
6689 if (mData->mMachineStateChangePending != 0)
6690 {
6691 /* ensureNoStateDependencies() is waiting for state dependencies to
6692 * drop to zero so don't add more. It may make sense to wait a bit
6693 * and retry before reporting an error (since the pending state
6694 * transition should be really quick) but let's just assert for
6695 * now to see if it ever happens on practice. */
6696
6697 AssertFailed();
6698
6699 return setError(E_ACCESSDENIED,
6700 tr("Machine state change is in progress. Please retry the operation later."));
6701 }
6702
6703 ++mData->mMachineStateDeps;
6704 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6705 }
6706
6707 if (aState)
6708 *aState = mData->mMachineState;
6709 if (aRegistered)
6710 *aRegistered = mData->mRegistered;
6711
6712 return S_OK;
6713}
6714
6715/**
6716 * Decreases the number of objects dependent on the machine state.
6717 * Must always complete the #addStateDependency() call after the state
6718 * dependency is no more necessary.
6719 */
6720void Machine::releaseStateDependency()
6721{
6722 AutoCaller autoCaller(this);
6723 AssertComRCReturnVoid(autoCaller.rc());
6724
6725 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6726
6727 /* releaseStateDependency() w/o addStateDependency()? */
6728 AssertReturnVoid(mData->mMachineStateDeps != 0);
6729 -- mData->mMachineStateDeps;
6730
6731 if (mData->mMachineStateDeps == 0)
6732 {
6733 /* inform ensureNoStateDependencies() that there are no more deps */
6734 if (mData->mMachineStateChangePending != 0)
6735 {
6736 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6737 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6738 }
6739 }
6740}
6741
6742// protected methods
6743/////////////////////////////////////////////////////////////////////////////
6744
6745/**
6746 * Performs machine state checks based on the @a aDepType value. If a check
6747 * fails, this method will set extended error info, otherwise it will return
6748 * S_OK. It is supposed, that on failure, the caller will immediately return
6749 * the return value of this method to the upper level.
6750 *
6751 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6752 *
6753 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6754 * current state of this machine object allows to change settings of the
6755 * machine (i.e. the machine is not registered, or registered but not running
6756 * and not saved). It is useful to call this method from Machine setters
6757 * before performing any change.
6758 *
6759 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6760 * as for MutableStateDep except that if the machine is saved, S_OK is also
6761 * returned. This is useful in setters which allow changing machine
6762 * properties when it is in the saved state.
6763 *
6764 * @param aDepType Dependency type to check.
6765 *
6766 * @note Non Machine based classes should use #addStateDependency() and
6767 * #releaseStateDependency() methods or the smart AutoStateDependency
6768 * template.
6769 *
6770 * @note This method must be called from under this object's read or write
6771 * lock.
6772 */
6773HRESULT Machine::checkStateDependency(StateDependency aDepType)
6774{
6775 switch (aDepType)
6776 {
6777 case AnyStateDep:
6778 {
6779 break;
6780 }
6781 case MutableStateDep:
6782 {
6783 if ( mData->mRegistered
6784 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6785 || ( mData->mMachineState != MachineState_Paused
6786 && mData->mMachineState != MachineState_Running
6787 && mData->mMachineState != MachineState_Aborted
6788 && mData->mMachineState != MachineState_Teleported
6789 && mData->mMachineState != MachineState_PoweredOff
6790 )
6791 )
6792 )
6793 return setError(VBOX_E_INVALID_VM_STATE,
6794 tr("The machine is not mutable (state is %s)"),
6795 Global::stringifyMachineState(mData->mMachineState));
6796 break;
6797 }
6798 case MutableOrSavedStateDep:
6799 {
6800 if ( mData->mRegistered
6801 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6802 || ( mData->mMachineState != MachineState_Paused
6803 && mData->mMachineState != MachineState_Running
6804 && mData->mMachineState != MachineState_Aborted
6805 && mData->mMachineState != MachineState_Teleported
6806 && mData->mMachineState != MachineState_Saved
6807 && mData->mMachineState != MachineState_PoweredOff
6808 )
6809 )
6810 )
6811 return setError(VBOX_E_INVALID_VM_STATE,
6812 tr("The machine is not mutable (state is %s)"),
6813 Global::stringifyMachineState(mData->mMachineState));
6814 break;
6815 }
6816 }
6817
6818 return S_OK;
6819}
6820
6821/**
6822 * Helper to initialize all associated child objects and allocate data
6823 * structures.
6824 *
6825 * This method must be called as a part of the object's initialization procedure
6826 * (usually done in the #init() method).
6827 *
6828 * @note Must be called only from #init() or from #registeredInit().
6829 */
6830HRESULT Machine::initDataAndChildObjects()
6831{
6832 AutoCaller autoCaller(this);
6833 AssertComRCReturnRC(autoCaller.rc());
6834 AssertComRCReturn(autoCaller.state() == InInit ||
6835 autoCaller.state() == Limited, E_FAIL);
6836
6837 AssertReturn(!mData->mAccessible, E_FAIL);
6838
6839 /* allocate data structures */
6840 mSSData.allocate();
6841 mUserData.allocate();
6842 mHWData.allocate();
6843 mMediaData.allocate();
6844 mStorageControllers.allocate();
6845
6846 /* initialize mOSTypeId */
6847 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6848
6849 /* create associated BIOS settings object */
6850 unconst(mBIOSSettings).createObject();
6851 mBIOSSettings->init(this);
6852
6853 /* create an associated VRDE object (default is disabled) */
6854 unconst(mVRDEServer).createObject();
6855 mVRDEServer->init(this);
6856
6857 /* create associated serial port objects */
6858 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6859 {
6860 unconst(mSerialPorts[slot]).createObject();
6861 mSerialPorts[slot]->init(this, slot);
6862 }
6863
6864 /* create associated parallel port objects */
6865 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6866 {
6867 unconst(mParallelPorts[slot]).createObject();
6868 mParallelPorts[slot]->init(this, slot);
6869 }
6870
6871 /* create the audio adapter object (always present, default is disabled) */
6872 unconst(mAudioAdapter).createObject();
6873 mAudioAdapter->init(this);
6874
6875 /* create the USB controller object (always present, default is disabled) */
6876 unconst(mUSBController).createObject();
6877 mUSBController->init(this);
6878
6879 /* create associated network adapter objects */
6880 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6881 {
6882 unconst(mNetworkAdapters[slot]).createObject();
6883 mNetworkAdapters[slot]->init(this, slot);
6884 }
6885
6886 /* create the bandwidth control */
6887 unconst(mBandwidthControl).createObject();
6888 mBandwidthControl->init(this);
6889
6890 return S_OK;
6891}
6892
6893/**
6894 * Helper to uninitialize all associated child objects and to free all data
6895 * structures.
6896 *
6897 * This method must be called as a part of the object's uninitialization
6898 * procedure (usually done in the #uninit() method).
6899 *
6900 * @note Must be called only from #uninit() or from #registeredInit().
6901 */
6902void Machine::uninitDataAndChildObjects()
6903{
6904 AutoCaller autoCaller(this);
6905 AssertComRCReturnVoid(autoCaller.rc());
6906 AssertComRCReturnVoid( autoCaller.state() == InUninit
6907 || autoCaller.state() == Limited);
6908
6909 /* tell all our other child objects we've been uninitialized */
6910 if (mBandwidthControl)
6911 {
6912 mBandwidthControl->uninit();
6913 unconst(mBandwidthControl).setNull();
6914 }
6915
6916 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6917 {
6918 if (mNetworkAdapters[slot])
6919 {
6920 mNetworkAdapters[slot]->uninit();
6921 unconst(mNetworkAdapters[slot]).setNull();
6922 }
6923 }
6924
6925 if (mUSBController)
6926 {
6927 mUSBController->uninit();
6928 unconst(mUSBController).setNull();
6929 }
6930
6931 if (mAudioAdapter)
6932 {
6933 mAudioAdapter->uninit();
6934 unconst(mAudioAdapter).setNull();
6935 }
6936
6937 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6938 {
6939 if (mParallelPorts[slot])
6940 {
6941 mParallelPorts[slot]->uninit();
6942 unconst(mParallelPorts[slot]).setNull();
6943 }
6944 }
6945
6946 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6947 {
6948 if (mSerialPorts[slot])
6949 {
6950 mSerialPorts[slot]->uninit();
6951 unconst(mSerialPorts[slot]).setNull();
6952 }
6953 }
6954
6955 if (mVRDEServer)
6956 {
6957 mVRDEServer->uninit();
6958 unconst(mVRDEServer).setNull();
6959 }
6960
6961 if (mBIOSSettings)
6962 {
6963 mBIOSSettings->uninit();
6964 unconst(mBIOSSettings).setNull();
6965 }
6966
6967 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6968 * instance is uninitialized; SessionMachine instances refer to real
6969 * Machine hard disks). This is necessary for a clean re-initialization of
6970 * the VM after successfully re-checking the accessibility state. Note
6971 * that in case of normal Machine or SnapshotMachine uninitialization (as
6972 * a result of unregistering or deleting the snapshot), outdated hard
6973 * disk attachments will already be uninitialized and deleted, so this
6974 * code will not affect them. */
6975 if ( !!mMediaData
6976 && (!isSessionMachine())
6977 )
6978 {
6979 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6980 it != mMediaData->mAttachments.end();
6981 ++it)
6982 {
6983 ComObjPtr<Medium> hd = (*it)->getMedium();
6984 if (hd.isNull())
6985 continue;
6986 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6987 AssertComRC(rc);
6988 }
6989 }
6990
6991 if (!isSessionMachine() && !isSnapshotMachine())
6992 {
6993 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6994 if (mData->mFirstSnapshot)
6995 {
6996 // snapshots tree is protected by media write lock; strictly
6997 // this isn't necessary here since we're deleting the entire
6998 // machine, but otherwise we assert in Snapshot::uninit()
6999 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7000 mData->mFirstSnapshot->uninit();
7001 mData->mFirstSnapshot.setNull();
7002 }
7003
7004 mData->mCurrentSnapshot.setNull();
7005 }
7006
7007 /* free data structures (the essential mData structure is not freed here
7008 * since it may be still in use) */
7009 mMediaData.free();
7010 mStorageControllers.free();
7011 mHWData.free();
7012 mUserData.free();
7013 mSSData.free();
7014}
7015
7016/**
7017 * Returns a pointer to the Machine object for this machine that acts like a
7018 * parent for complex machine data objects such as shared folders, etc.
7019 *
7020 * For primary Machine objects and for SnapshotMachine objects, returns this
7021 * object's pointer itself. For SessionMachine objects, returns the peer
7022 * (primary) machine pointer.
7023 */
7024Machine* Machine::getMachine()
7025{
7026 if (isSessionMachine())
7027 return (Machine*)mPeer;
7028 return this;
7029}
7030
7031/**
7032 * Makes sure that there are no machine state dependents. If necessary, waits
7033 * for the number of dependents to drop to zero.
7034 *
7035 * Make sure this method is called from under this object's write lock to
7036 * guarantee that no new dependents may be added when this method returns
7037 * control to the caller.
7038 *
7039 * @note Locks this object for writing. The lock will be released while waiting
7040 * (if necessary).
7041 *
7042 * @warning To be used only in methods that change the machine state!
7043 */
7044void Machine::ensureNoStateDependencies()
7045{
7046 AssertReturnVoid(isWriteLockOnCurrentThread());
7047
7048 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7049
7050 /* Wait for all state dependents if necessary */
7051 if (mData->mMachineStateDeps != 0)
7052 {
7053 /* lazy semaphore creation */
7054 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
7055 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
7056
7057 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
7058 mData->mMachineStateDeps));
7059
7060 ++mData->mMachineStateChangePending;
7061
7062 /* reset the semaphore before waiting, the last dependent will signal
7063 * it */
7064 RTSemEventMultiReset(mData->mMachineStateDepsSem);
7065
7066 alock.leave();
7067
7068 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
7069
7070 alock.enter();
7071
7072 -- mData->mMachineStateChangePending;
7073 }
7074}
7075
7076/**
7077 * Changes the machine state and informs callbacks.
7078 *
7079 * This method is not intended to fail so it either returns S_OK or asserts (and
7080 * returns a failure).
7081 *
7082 * @note Locks this object for writing.
7083 */
7084HRESULT Machine::setMachineState(MachineState_T aMachineState)
7085{
7086 LogFlowThisFuncEnter();
7087 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
7088
7089 AutoCaller autoCaller(this);
7090 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7091
7092 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7093
7094 /* wait for state dependents to drop to zero */
7095 ensureNoStateDependencies();
7096
7097 if (mData->mMachineState != aMachineState)
7098 {
7099 mData->mMachineState = aMachineState;
7100
7101 RTTimeNow(&mData->mLastStateChange);
7102
7103 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7104 }
7105
7106 LogFlowThisFuncLeave();
7107 return S_OK;
7108}
7109
7110/**
7111 * Searches for a shared folder with the given logical name
7112 * in the collection of shared folders.
7113 *
7114 * @param aName logical name of the shared folder
7115 * @param aSharedFolder where to return the found object
7116 * @param aSetError whether to set the error info if the folder is
7117 * not found
7118 * @return
7119 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7120 *
7121 * @note
7122 * must be called from under the object's lock!
7123 */
7124HRESULT Machine::findSharedFolder(const Utf8Str &aName,
7125 ComObjPtr<SharedFolder> &aSharedFolder,
7126 bool aSetError /* = false */)
7127{
7128 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
7129 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7130 it != mHWData->mSharedFolders.end();
7131 ++it)
7132 {
7133 SharedFolder *pSF = *it;
7134 AutoCaller autoCaller(pSF);
7135 if (pSF->getName() == aName)
7136 {
7137 aSharedFolder = pSF;
7138 rc = S_OK;
7139 break;
7140 }
7141 }
7142
7143 if (aSetError && FAILED(rc))
7144 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
7145
7146 return rc;
7147}
7148
7149/**
7150 * Initializes all machine instance data from the given settings structures
7151 * from XML. The exception is the machine UUID which needs special handling
7152 * depending on the caller's use case, so the caller needs to set that herself.
7153 *
7154 * This gets called in several contexts during machine initialization:
7155 *
7156 * -- When machine XML exists on disk already and needs to be loaded into memory,
7157 * for example, from registeredInit() to load all registered machines on
7158 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7159 * attached to the machine should be part of some media registry already.
7160 *
7161 * -- During OVF import, when a machine config has been constructed from an
7162 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7163 * ensure that the media listed as attachments in the config (which have
7164 * been imported from the OVF) receive the correct registry ID.
7165 *
7166 * @param config Machine settings from XML.
7167 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7168 * @return
7169 */
7170HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7171 const Guid *puuidRegistry)
7172{
7173 // copy name, description, OS type, teleporter, UTC etc.
7174 mUserData->s = config.machineUserData;
7175
7176 // look up the object by Id to check it is valid
7177 ComPtr<IGuestOSType> guestOSType;
7178 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7179 guestOSType.asOutParam());
7180 if (FAILED(rc)) return rc;
7181
7182 // stateFile (optional)
7183 if (config.strStateFile.isEmpty())
7184 mSSData->strStateFilePath.setNull();
7185 else
7186 {
7187 Utf8Str stateFilePathFull(config.strStateFile);
7188 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7189 if (RT_FAILURE(vrc))
7190 return setError(E_FAIL,
7191 tr("Invalid saved state file path '%s' (%Rrc)"),
7192 config.strStateFile.c_str(),
7193 vrc);
7194 mSSData->strStateFilePath = stateFilePathFull;
7195 }
7196
7197 // snapshot folder needs special processing so set it again
7198 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7199 if (FAILED(rc)) return rc;
7200
7201 /* currentStateModified (optional, default is true) */
7202 mData->mCurrentStateModified = config.fCurrentStateModified;
7203
7204 mData->mLastStateChange = config.timeLastStateChange;
7205
7206 /*
7207 * note: all mUserData members must be assigned prior this point because
7208 * we need to commit changes in order to let mUserData be shared by all
7209 * snapshot machine instances.
7210 */
7211 mUserData.commitCopy();
7212
7213 // machine registry, if present (must be loaded before snapshots)
7214 if (config.canHaveOwnMediaRegistry())
7215 {
7216 // determine machine folder
7217 Utf8Str strMachineFolder = getSettingsFileFull();
7218 strMachineFolder.stripFilename();
7219 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7220 config.mediaRegistry,
7221 strMachineFolder);
7222 if (FAILED(rc)) return rc;
7223 }
7224
7225 /* Snapshot node (optional) */
7226 size_t cRootSnapshots;
7227 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7228 {
7229 // there must be only one root snapshot
7230 Assert(cRootSnapshots == 1);
7231
7232 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7233
7234 rc = loadSnapshot(snap,
7235 config.uuidCurrentSnapshot,
7236 NULL); // no parent == first snapshot
7237 if (FAILED(rc)) return rc;
7238 }
7239
7240 // hardware data
7241 rc = loadHardware(config.hardwareMachine);
7242 if (FAILED(rc)) return rc;
7243
7244 // load storage controllers
7245 rc = loadStorageControllers(config.storageMachine,
7246 puuidRegistry,
7247 NULL /* puuidSnapshot */);
7248 if (FAILED(rc)) return rc;
7249
7250 /*
7251 * NOTE: the assignment below must be the last thing to do,
7252 * otherwise it will be not possible to change the settings
7253 * somewhere in the code above because all setters will be
7254 * blocked by checkStateDependency(MutableStateDep).
7255 */
7256
7257 /* set the machine state to Aborted or Saved when appropriate */
7258 if (config.fAborted)
7259 {
7260 Assert(!mSSData->strStateFilePath.isEmpty());
7261 mSSData->strStateFilePath.setNull();
7262
7263 /* no need to use setMachineState() during init() */
7264 mData->mMachineState = MachineState_Aborted;
7265 }
7266 else if (!mSSData->strStateFilePath.isEmpty())
7267 {
7268 /* no need to use setMachineState() during init() */
7269 mData->mMachineState = MachineState_Saved;
7270 }
7271
7272 // after loading settings, we are no longer different from the XML on disk
7273 mData->flModifications = 0;
7274
7275 return S_OK;
7276}
7277
7278/**
7279 * Recursively loads all snapshots starting from the given.
7280 *
7281 * @param aNode <Snapshot> node.
7282 * @param aCurSnapshotId Current snapshot ID from the settings file.
7283 * @param aParentSnapshot Parent snapshot.
7284 */
7285HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7286 const Guid &aCurSnapshotId,
7287 Snapshot *aParentSnapshot)
7288{
7289 AssertReturn(!isSnapshotMachine(), E_FAIL);
7290 AssertReturn(!isSessionMachine(), E_FAIL);
7291
7292 HRESULT rc = S_OK;
7293
7294 Utf8Str strStateFile;
7295 if (!data.strStateFile.isEmpty())
7296 {
7297 /* optional */
7298 strStateFile = data.strStateFile;
7299 int vrc = calculateFullPath(strStateFile, strStateFile);
7300 if (RT_FAILURE(vrc))
7301 return setError(E_FAIL,
7302 tr("Invalid saved state file path '%s' (%Rrc)"),
7303 strStateFile.c_str(),
7304 vrc);
7305 }
7306
7307 /* create a snapshot machine object */
7308 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7309 pSnapshotMachine.createObject();
7310 rc = pSnapshotMachine->init(this,
7311 data.hardware,
7312 data.storage,
7313 data.uuid.ref(),
7314 strStateFile);
7315 if (FAILED(rc)) return rc;
7316
7317 /* create a snapshot object */
7318 ComObjPtr<Snapshot> pSnapshot;
7319 pSnapshot.createObject();
7320 /* initialize the snapshot */
7321 rc = pSnapshot->init(mParent, // VirtualBox object
7322 data.uuid,
7323 data.strName,
7324 data.strDescription,
7325 data.timestamp,
7326 pSnapshotMachine,
7327 aParentSnapshot);
7328 if (FAILED(rc)) return rc;
7329
7330 /* memorize the first snapshot if necessary */
7331 if (!mData->mFirstSnapshot)
7332 mData->mFirstSnapshot = pSnapshot;
7333
7334 /* memorize the current snapshot when appropriate */
7335 if ( !mData->mCurrentSnapshot
7336 && pSnapshot->getId() == aCurSnapshotId
7337 )
7338 mData->mCurrentSnapshot = pSnapshot;
7339
7340 // now create the children
7341 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7342 it != data.llChildSnapshots.end();
7343 ++it)
7344 {
7345 const settings::Snapshot &childData = *it;
7346 // recurse
7347 rc = loadSnapshot(childData,
7348 aCurSnapshotId,
7349 pSnapshot); // parent = the one we created above
7350 if (FAILED(rc)) return rc;
7351 }
7352
7353 return rc;
7354}
7355
7356/**
7357 * @param aNode <Hardware> node.
7358 */
7359HRESULT Machine::loadHardware(const settings::Hardware &data)
7360{
7361 AssertReturn(!isSessionMachine(), E_FAIL);
7362
7363 HRESULT rc = S_OK;
7364
7365 try
7366 {
7367 /* The hardware version attribute (optional). */
7368 mHWData->mHWVersion = data.strVersion;
7369 mHWData->mHardwareUUID = data.uuid;
7370
7371 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7372 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7373 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7374 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7375 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7376 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7377 mHWData->mPAEEnabled = data.fPAE;
7378 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7379
7380 mHWData->mCPUCount = data.cCPUs;
7381 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7382 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7383
7384 // cpu
7385 if (mHWData->mCPUHotPlugEnabled)
7386 {
7387 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7388 it != data.llCpus.end();
7389 ++it)
7390 {
7391 const settings::Cpu &cpu = *it;
7392
7393 mHWData->mCPUAttached[cpu.ulId] = true;
7394 }
7395 }
7396
7397 // cpuid leafs
7398 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7399 it != data.llCpuIdLeafs.end();
7400 ++it)
7401 {
7402 const settings::CpuIdLeaf &leaf = *it;
7403
7404 switch (leaf.ulId)
7405 {
7406 case 0x0:
7407 case 0x1:
7408 case 0x2:
7409 case 0x3:
7410 case 0x4:
7411 case 0x5:
7412 case 0x6:
7413 case 0x7:
7414 case 0x8:
7415 case 0x9:
7416 case 0xA:
7417 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7418 break;
7419
7420 case 0x80000000:
7421 case 0x80000001:
7422 case 0x80000002:
7423 case 0x80000003:
7424 case 0x80000004:
7425 case 0x80000005:
7426 case 0x80000006:
7427 case 0x80000007:
7428 case 0x80000008:
7429 case 0x80000009:
7430 case 0x8000000A:
7431 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7432 break;
7433
7434 default:
7435 /* just ignore */
7436 break;
7437 }
7438 }
7439
7440 mHWData->mMemorySize = data.ulMemorySizeMB;
7441 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7442
7443 // boot order
7444 for (size_t i = 0;
7445 i < RT_ELEMENTS(mHWData->mBootOrder);
7446 i++)
7447 {
7448 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7449 if (it == data.mapBootOrder.end())
7450 mHWData->mBootOrder[i] = DeviceType_Null;
7451 else
7452 mHWData->mBootOrder[i] = it->second;
7453 }
7454
7455 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7456 mHWData->mMonitorCount = data.cMonitors;
7457 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7458 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7459 mHWData->mFirmwareType = data.firmwareType;
7460 mHWData->mPointingHidType = data.pointingHidType;
7461 mHWData->mKeyboardHidType = data.keyboardHidType;
7462 mHWData->mChipsetType = data.chipsetType;
7463 mHWData->mHpetEnabled = data.fHpetEnabled;
7464
7465 /* VRDEServer */
7466 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7467 if (FAILED(rc)) return rc;
7468
7469 /* BIOS */
7470 rc = mBIOSSettings->loadSettings(data.biosSettings);
7471 if (FAILED(rc)) return rc;
7472
7473 // Bandwidth control (must come before network adapters)
7474 rc = mBandwidthControl->loadSettings(data.ioSettings);
7475 if (FAILED(rc)) return rc;
7476
7477 /* USB Controller */
7478 rc = mUSBController->loadSettings(data.usbController);
7479 if (FAILED(rc)) return rc;
7480
7481 // network adapters
7482 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7483 it != data.llNetworkAdapters.end();
7484 ++it)
7485 {
7486 const settings::NetworkAdapter &nic = *it;
7487
7488 /* slot unicity is guaranteed by XML Schema */
7489 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7490 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
7491 if (FAILED(rc)) return rc;
7492 }
7493
7494 // serial ports
7495 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7496 it != data.llSerialPorts.end();
7497 ++it)
7498 {
7499 const settings::SerialPort &s = *it;
7500
7501 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7502 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7503 if (FAILED(rc)) return rc;
7504 }
7505
7506 // parallel ports (optional)
7507 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7508 it != data.llParallelPorts.end();
7509 ++it)
7510 {
7511 const settings::ParallelPort &p = *it;
7512
7513 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7514 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7515 if (FAILED(rc)) return rc;
7516 }
7517
7518 /* AudioAdapter */
7519 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7520 if (FAILED(rc)) return rc;
7521
7522 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7523 it != data.llSharedFolders.end();
7524 ++it)
7525 {
7526 const settings::SharedFolder &sf = *it;
7527 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7528 Bstr(sf.strHostPath).raw(),
7529 sf.fWritable, sf.fAutoMount);
7530 if (FAILED(rc)) return rc;
7531 }
7532
7533 // Clipboard
7534 mHWData->mClipboardMode = data.clipboardMode;
7535
7536 // guest settings
7537 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7538
7539 // IO settings
7540 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7541 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7542
7543 // Host PCI devices
7544 for (settings::HostPciDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
7545 it != data.pciAttachments.end();
7546 ++it)
7547 {
7548 const settings::HostPciDeviceAttachment &hpda = *it;
7549 ComObjPtr<PciDeviceAttachment> pda;
7550
7551 pda.createObject();
7552 pda->loadSettings(this, hpda);
7553 mHWData->mPciDeviceAssignments.push_back(pda);
7554 }
7555
7556#ifdef VBOX_WITH_GUEST_PROPS
7557 /* Guest properties (optional) */
7558 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7559 it != data.llGuestProperties.end();
7560 ++it)
7561 {
7562 const settings::GuestProperty &prop = *it;
7563 uint32_t fFlags = guestProp::NILFLAG;
7564 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7565 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7566 mHWData->mGuestProperties.push_back(property);
7567 }
7568
7569 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7570#endif /* VBOX_WITH_GUEST_PROPS defined */
7571 }
7572 catch(std::bad_alloc &)
7573 {
7574 return E_OUTOFMEMORY;
7575 }
7576
7577 AssertComRC(rc);
7578 return rc;
7579}
7580
7581/**
7582 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7583 *
7584 * @param data
7585 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7586 * @param puuidSnapshot
7587 * @return
7588 */
7589HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7590 const Guid *puuidRegistry,
7591 const Guid *puuidSnapshot)
7592{
7593 AssertReturn(!isSessionMachine(), E_FAIL);
7594
7595 HRESULT rc = S_OK;
7596
7597 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7598 it != data.llStorageControllers.end();
7599 ++it)
7600 {
7601 const settings::StorageController &ctlData = *it;
7602
7603 ComObjPtr<StorageController> pCtl;
7604 /* Try to find one with the name first. */
7605 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7606 if (SUCCEEDED(rc))
7607 return setError(VBOX_E_OBJECT_IN_USE,
7608 tr("Storage controller named '%s' already exists"),
7609 ctlData.strName.c_str());
7610
7611 pCtl.createObject();
7612 rc = pCtl->init(this,
7613 ctlData.strName,
7614 ctlData.storageBus,
7615 ctlData.ulInstance,
7616 ctlData.fBootable);
7617 if (FAILED(rc)) return rc;
7618
7619 mStorageControllers->push_back(pCtl);
7620
7621 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7622 if (FAILED(rc)) return rc;
7623
7624 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7625 if (FAILED(rc)) return rc;
7626
7627 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7628 if (FAILED(rc)) return rc;
7629
7630 /* Set IDE emulation settings (only for AHCI controller). */
7631 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7632 {
7633 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7634 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7635 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7636 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7637 )
7638 return rc;
7639 }
7640
7641 /* Load the attached devices now. */
7642 rc = loadStorageDevices(pCtl,
7643 ctlData,
7644 puuidRegistry,
7645 puuidSnapshot);
7646 if (FAILED(rc)) return rc;
7647 }
7648
7649 return S_OK;
7650}
7651
7652/**
7653 * Called from loadStorageControllers for a controller's devices.
7654 *
7655 * @param aStorageController
7656 * @param data
7657 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7658 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7659 * @return
7660 */
7661HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7662 const settings::StorageController &data,
7663 const Guid *puuidRegistry,
7664 const Guid *puuidSnapshot)
7665{
7666 HRESULT rc = S_OK;
7667
7668 /* paranoia: detect duplicate attachments */
7669 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7670 it != data.llAttachedDevices.end();
7671 ++it)
7672 {
7673 const settings::AttachedDevice &ad = *it;
7674
7675 for (settings::AttachedDevicesList::const_iterator it2 = it;
7676 it2 != data.llAttachedDevices.end();
7677 ++it2)
7678 {
7679 if (it == it2)
7680 continue;
7681
7682 const settings::AttachedDevice &ad2 = *it2;
7683
7684 if ( ad.lPort == ad2.lPort
7685 && ad.lDevice == ad2.lDevice)
7686 {
7687 return setError(E_FAIL,
7688 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7689 aStorageController->getName().c_str(),
7690 ad.lPort,
7691 ad.lDevice,
7692 mUserData->s.strName.c_str());
7693 }
7694 }
7695 }
7696
7697 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7698 it != data.llAttachedDevices.end();
7699 ++it)
7700 {
7701 const settings::AttachedDevice &dev = *it;
7702 ComObjPtr<Medium> medium;
7703
7704 switch (dev.deviceType)
7705 {
7706 case DeviceType_Floppy:
7707 case DeviceType_DVD:
7708 if (dev.strHostDriveSrc.isNotEmpty())
7709 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
7710 else
7711 rc = mParent->findRemoveableMedium(dev.deviceType,
7712 dev.uuid,
7713 false /* fRefresh */,
7714 false /* aSetError */,
7715 medium);
7716 if (rc == VBOX_E_OBJECT_NOT_FOUND)
7717 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
7718 rc = S_OK;
7719 break;
7720
7721 case DeviceType_HardDisk:
7722 {
7723 /* find a hard disk by UUID */
7724 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7725 if (FAILED(rc))
7726 {
7727 if (isSnapshotMachine())
7728 {
7729 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7730 // so the user knows that the bad disk is in a snapshot somewhere
7731 com::ErrorInfo info;
7732 return setError(E_FAIL,
7733 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7734 puuidSnapshot->raw(),
7735 info.getText().raw());
7736 }
7737 else
7738 return rc;
7739 }
7740
7741 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7742
7743 if (medium->getType() == MediumType_Immutable)
7744 {
7745 if (isSnapshotMachine())
7746 return setError(E_FAIL,
7747 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7748 "of the virtual machine '%s' ('%s')"),
7749 medium->getLocationFull().c_str(),
7750 dev.uuid.raw(),
7751 puuidSnapshot->raw(),
7752 mUserData->s.strName.c_str(),
7753 mData->m_strConfigFileFull.c_str());
7754
7755 return setError(E_FAIL,
7756 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7757 medium->getLocationFull().c_str(),
7758 dev.uuid.raw(),
7759 mUserData->s.strName.c_str(),
7760 mData->m_strConfigFileFull.c_str());
7761 }
7762
7763 if (medium->getType() == MediumType_MultiAttach)
7764 {
7765 if (isSnapshotMachine())
7766 return setError(E_FAIL,
7767 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7768 "of the virtual machine '%s' ('%s')"),
7769 medium->getLocationFull().c_str(),
7770 dev.uuid.raw(),
7771 puuidSnapshot->raw(),
7772 mUserData->s.strName.c_str(),
7773 mData->m_strConfigFileFull.c_str());
7774
7775 return setError(E_FAIL,
7776 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7777 medium->getLocationFull().c_str(),
7778 dev.uuid.raw(),
7779 mUserData->s.strName.c_str(),
7780 mData->m_strConfigFileFull.c_str());
7781 }
7782
7783 if ( !isSnapshotMachine()
7784 && medium->getChildren().size() != 0
7785 )
7786 return setError(E_FAIL,
7787 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7788 "because it has %d differencing child hard disks"),
7789 medium->getLocationFull().c_str(),
7790 dev.uuid.raw(),
7791 mUserData->s.strName.c_str(),
7792 mData->m_strConfigFileFull.c_str(),
7793 medium->getChildren().size());
7794
7795 if (findAttachment(mMediaData->mAttachments,
7796 medium))
7797 return setError(E_FAIL,
7798 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7799 medium->getLocationFull().c_str(),
7800 dev.uuid.raw(),
7801 mUserData->s.strName.c_str(),
7802 mData->m_strConfigFileFull.c_str());
7803
7804 break;
7805 }
7806
7807 default:
7808 return setError(E_FAIL,
7809 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7810 medium->getLocationFull().c_str(),
7811 mUserData->s.strName.c_str(),
7812 mData->m_strConfigFileFull.c_str());
7813 }
7814
7815 if (FAILED(rc))
7816 break;
7817
7818 /* Bandwidth groups are loaded at this point. */
7819 ComObjPtr<BandwidthGroup> pBwGroup;
7820
7821 if (!dev.strBwGroup.isEmpty())
7822 {
7823 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
7824 if (FAILED(rc))
7825 return setError(E_FAIL,
7826 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
7827 medium->getLocationFull().c_str(),
7828 dev.strBwGroup.c_str(),
7829 mUserData->s.strName.c_str(),
7830 mData->m_strConfigFileFull.c_str());
7831 pBwGroup->reference();
7832 }
7833
7834 const Bstr controllerName = aStorageController->getName();
7835 ComObjPtr<MediumAttachment> pAttachment;
7836 pAttachment.createObject();
7837 rc = pAttachment->init(this,
7838 medium,
7839 controllerName,
7840 dev.lPort,
7841 dev.lDevice,
7842 dev.deviceType,
7843 dev.fPassThrough,
7844 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
7845 if (FAILED(rc)) break;
7846
7847 /* associate the medium with this machine and snapshot */
7848 if (!medium.isNull())
7849 {
7850 AutoCaller medCaller(medium);
7851 if (FAILED(medCaller.rc())) return medCaller.rc();
7852 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
7853
7854 if (isSnapshotMachine())
7855 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7856 else
7857 rc = medium->addBackReference(mData->mUuid);
7858
7859 if (puuidRegistry)
7860 // caller wants registry ID to be set on all attached media (OVF import case)
7861 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
7862 }
7863
7864 if (FAILED(rc))
7865 break;
7866
7867 /* back up mMediaData to let registeredInit() properly rollback on failure
7868 * (= limited accessibility) */
7869 setModified(IsModified_Storage);
7870 mMediaData.backup();
7871 mMediaData->mAttachments.push_back(pAttachment);
7872 }
7873
7874 return rc;
7875}
7876
7877/**
7878 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7879 *
7880 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7881 * @param aSnapshot where to return the found snapshot
7882 * @param aSetError true to set extended error info on failure
7883 */
7884HRESULT Machine::findSnapshotById(const Guid &aId,
7885 ComObjPtr<Snapshot> &aSnapshot,
7886 bool aSetError /* = false */)
7887{
7888 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7889
7890 if (!mData->mFirstSnapshot)
7891 {
7892 if (aSetError)
7893 return setError(E_FAIL, tr("This machine does not have any snapshots"));
7894 return E_FAIL;
7895 }
7896
7897 if (aId.isEmpty())
7898 aSnapshot = mData->mFirstSnapshot;
7899 else
7900 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
7901
7902 if (!aSnapshot)
7903 {
7904 if (aSetError)
7905 return setError(E_FAIL,
7906 tr("Could not find a snapshot with UUID {%s}"),
7907 aId.toString().c_str());
7908 return E_FAIL;
7909 }
7910
7911 return S_OK;
7912}
7913
7914/**
7915 * Returns the snapshot with the given name or fails of no such snapshot.
7916 *
7917 * @param aName snapshot name to find
7918 * @param aSnapshot where to return the found snapshot
7919 * @param aSetError true to set extended error info on failure
7920 */
7921HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
7922 ComObjPtr<Snapshot> &aSnapshot,
7923 bool aSetError /* = false */)
7924{
7925 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
7926
7927 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7928
7929 if (!mData->mFirstSnapshot)
7930 {
7931 if (aSetError)
7932 return setError(VBOX_E_OBJECT_NOT_FOUND,
7933 tr("This machine does not have any snapshots"));
7934 return VBOX_E_OBJECT_NOT_FOUND;
7935 }
7936
7937 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
7938
7939 if (!aSnapshot)
7940 {
7941 if (aSetError)
7942 return setError(VBOX_E_OBJECT_NOT_FOUND,
7943 tr("Could not find a snapshot named '%s'"), strName.c_str());
7944 return VBOX_E_OBJECT_NOT_FOUND;
7945 }
7946
7947 return S_OK;
7948}
7949
7950/**
7951 * Returns a storage controller object with the given name.
7952 *
7953 * @param aName storage controller name to find
7954 * @param aStorageController where to return the found storage controller
7955 * @param aSetError true to set extended error info on failure
7956 */
7957HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7958 ComObjPtr<StorageController> &aStorageController,
7959 bool aSetError /* = false */)
7960{
7961 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7962
7963 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7964 it != mStorageControllers->end();
7965 ++it)
7966 {
7967 if ((*it)->getName() == aName)
7968 {
7969 aStorageController = (*it);
7970 return S_OK;
7971 }
7972 }
7973
7974 if (aSetError)
7975 return setError(VBOX_E_OBJECT_NOT_FOUND,
7976 tr("Could not find a storage controller named '%s'"),
7977 aName.c_str());
7978 return VBOX_E_OBJECT_NOT_FOUND;
7979}
7980
7981HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7982 MediaData::AttachmentList &atts)
7983{
7984 AutoCaller autoCaller(this);
7985 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7986
7987 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7988
7989 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7990 it != mMediaData->mAttachments.end();
7991 ++it)
7992 {
7993 const ComObjPtr<MediumAttachment> &pAtt = *it;
7994
7995 // should never happen, but deal with NULL pointers in the list.
7996 AssertStmt(!pAtt.isNull(), continue);
7997
7998 // getControllerName() needs caller+read lock
7999 AutoCaller autoAttCaller(pAtt);
8000 if (FAILED(autoAttCaller.rc()))
8001 {
8002 atts.clear();
8003 return autoAttCaller.rc();
8004 }
8005 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
8006
8007 if (pAtt->getControllerName() == aName)
8008 atts.push_back(pAtt);
8009 }
8010
8011 return S_OK;
8012}
8013
8014/**
8015 * Helper for #saveSettings. Cares about renaming the settings directory and
8016 * file if the machine name was changed and about creating a new settings file
8017 * if this is a new machine.
8018 *
8019 * @note Must be never called directly but only from #saveSettings().
8020 */
8021HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
8022{
8023 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8024
8025 HRESULT rc = S_OK;
8026
8027 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
8028
8029 /* attempt to rename the settings file if machine name is changed */
8030 if ( mUserData->s.fNameSync
8031 && mUserData.isBackedUp()
8032 && mUserData.backedUpData()->s.strName != mUserData->s.strName
8033 )
8034 {
8035 bool dirRenamed = false;
8036 bool fileRenamed = false;
8037
8038 Utf8Str configFile, newConfigFile;
8039 Utf8Str configFilePrev, newConfigFilePrev;
8040 Utf8Str configDir, newConfigDir;
8041
8042 do
8043 {
8044 int vrc = VINF_SUCCESS;
8045
8046 Utf8Str name = mUserData.backedUpData()->s.strName;
8047 Utf8Str newName = mUserData->s.strName;
8048
8049 configFile = mData->m_strConfigFileFull;
8050
8051 /* first, rename the directory if it matches the machine name */
8052 configDir = configFile;
8053 configDir.stripFilename();
8054 newConfigDir = configDir;
8055 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8056 {
8057 newConfigDir.stripFilename();
8058 newConfigDir.append(RTPATH_DELIMITER);
8059 newConfigDir.append(newName);
8060 /* new dir and old dir cannot be equal here because of 'if'
8061 * above and because name != newName */
8062 Assert(configDir != newConfigDir);
8063 if (!fSettingsFileIsNew)
8064 {
8065 /* perform real rename only if the machine is not new */
8066 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8067 if (RT_FAILURE(vrc))
8068 {
8069 rc = setError(E_FAIL,
8070 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8071 configDir.c_str(),
8072 newConfigDir.c_str(),
8073 vrc);
8074 break;
8075 }
8076 dirRenamed = true;
8077 }
8078 }
8079
8080 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8081 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8082
8083 /* then try to rename the settings file itself */
8084 if (newConfigFile != configFile)
8085 {
8086 /* get the path to old settings file in renamed directory */
8087 configFile = Utf8StrFmt("%s%c%s",
8088 newConfigDir.c_str(),
8089 RTPATH_DELIMITER,
8090 RTPathFilename(configFile.c_str()));
8091 if (!fSettingsFileIsNew)
8092 {
8093 /* perform real rename only if the machine is not new */
8094 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8095 if (RT_FAILURE(vrc))
8096 {
8097 rc = setError(E_FAIL,
8098 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8099 configFile.c_str(),
8100 newConfigFile.c_str(),
8101 vrc);
8102 break;
8103 }
8104 fileRenamed = true;
8105 configFilePrev = configFile;
8106 configFilePrev += "-prev";
8107 newConfigFilePrev = newConfigFile;
8108 newConfigFilePrev += "-prev";
8109 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
8110 }
8111 }
8112
8113 // update m_strConfigFileFull amd mConfigFile
8114 mData->m_strConfigFileFull = newConfigFile;
8115 // compute the relative path too
8116 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8117
8118 // store the old and new so that VirtualBox::saveSettings() can update
8119 // the media registry
8120 if ( mData->mRegistered
8121 && configDir != newConfigDir)
8122 {
8123 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8124
8125 if (pfNeedsGlobalSaveSettings)
8126 *pfNeedsGlobalSaveSettings = true;
8127 }
8128
8129 // in the saved state file path, replace the old directory with the new directory
8130 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8131 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8132
8133 // and do the same thing for the saved state file paths of all the online snapshots
8134 if (mData->mFirstSnapshot)
8135 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8136 newConfigDir.c_str());
8137 }
8138 while (0);
8139
8140 if (FAILED(rc))
8141 {
8142 /* silently try to rename everything back */
8143 if (fileRenamed)
8144 {
8145 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
8146 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8147 }
8148 if (dirRenamed)
8149 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8150 }
8151
8152 if (FAILED(rc)) return rc;
8153 }
8154
8155 if (fSettingsFileIsNew)
8156 {
8157 /* create a virgin config file */
8158 int vrc = VINF_SUCCESS;
8159
8160 /* ensure the settings directory exists */
8161 Utf8Str path(mData->m_strConfigFileFull);
8162 path.stripFilename();
8163 if (!RTDirExists(path.c_str()))
8164 {
8165 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8166 if (RT_FAILURE(vrc))
8167 {
8168 return setError(E_FAIL,
8169 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8170 path.c_str(),
8171 vrc);
8172 }
8173 }
8174
8175 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8176 path = Utf8Str(mData->m_strConfigFileFull);
8177 RTFILE f = NIL_RTFILE;
8178 vrc = RTFileOpen(&f, path.c_str(),
8179 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8180 if (RT_FAILURE(vrc))
8181 return setError(E_FAIL,
8182 tr("Could not create the settings file '%s' (%Rrc)"),
8183 path.c_str(),
8184 vrc);
8185 RTFileClose(f);
8186 }
8187
8188 return rc;
8189}
8190
8191/**
8192 * Saves and commits machine data, user data and hardware data.
8193 *
8194 * Note that on failure, the data remains uncommitted.
8195 *
8196 * @a aFlags may combine the following flags:
8197 *
8198 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8199 * Used when saving settings after an operation that makes them 100%
8200 * correspond to the settings from the current snapshot.
8201 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8202 * #isReallyModified() returns false. This is necessary for cases when we
8203 * change machine data directly, not through the backup()/commit() mechanism.
8204 * - SaveS_Force: settings will be saved without doing a deep compare of the
8205 * settings structures. This is used when this is called because snapshots
8206 * have changed to avoid the overhead of the deep compare.
8207 *
8208 * @note Must be called from under this object's write lock. Locks children for
8209 * writing.
8210 *
8211 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8212 * initialized to false and that will be set to true by this function if
8213 * the caller must invoke VirtualBox::saveSettings() because the global
8214 * settings have changed. This will happen if a machine rename has been
8215 * saved and the global machine and media registries will therefore need
8216 * updating.
8217 */
8218HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8219 int aFlags /*= 0*/)
8220{
8221 LogFlowThisFuncEnter();
8222
8223 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8224
8225 /* make sure child objects are unable to modify the settings while we are
8226 * saving them */
8227 ensureNoStateDependencies();
8228
8229 AssertReturn(!isSnapshotMachine(),
8230 E_FAIL);
8231
8232 HRESULT rc = S_OK;
8233 bool fNeedsWrite = false;
8234
8235 /* First, prepare to save settings. It will care about renaming the
8236 * settings directory and file if the machine name was changed and about
8237 * creating a new settings file if this is a new machine. */
8238 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8239 if (FAILED(rc)) return rc;
8240
8241 // keep a pointer to the current settings structures
8242 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8243 settings::MachineConfigFile *pNewConfig = NULL;
8244
8245 try
8246 {
8247 // make a fresh one to have everyone write stuff into
8248 pNewConfig = new settings::MachineConfigFile(NULL);
8249 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8250
8251 // now go and copy all the settings data from COM to the settings structures
8252 // (this calles saveSettings() on all the COM objects in the machine)
8253 copyMachineDataToSettings(*pNewConfig);
8254
8255 if (aFlags & SaveS_ResetCurStateModified)
8256 {
8257 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8258 mData->mCurrentStateModified = FALSE;
8259 fNeedsWrite = true; // always, no need to compare
8260 }
8261 else if (aFlags & SaveS_Force)
8262 {
8263 fNeedsWrite = true; // always, no need to compare
8264 }
8265 else
8266 {
8267 if (!mData->mCurrentStateModified)
8268 {
8269 // do a deep compare of the settings that we just saved with the settings
8270 // previously stored in the config file; this invokes MachineConfigFile::operator==
8271 // which does a deep compare of all the settings, which is expensive but less expensive
8272 // than writing out XML in vain
8273 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8274
8275 // could still be modified if any settings changed
8276 mData->mCurrentStateModified = fAnySettingsChanged;
8277
8278 fNeedsWrite = fAnySettingsChanged;
8279 }
8280 else
8281 fNeedsWrite = true;
8282 }
8283
8284 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8285
8286 if (fNeedsWrite)
8287 // now spit it all out!
8288 pNewConfig->write(mData->m_strConfigFileFull);
8289
8290 mData->pMachineConfigFile = pNewConfig;
8291 delete pOldConfig;
8292 commit();
8293
8294 // after saving settings, we are no longer different from the XML on disk
8295 mData->flModifications = 0;
8296 }
8297 catch (HRESULT err)
8298 {
8299 // we assume that error info is set by the thrower
8300 rc = err;
8301
8302 // restore old config
8303 delete pNewConfig;
8304 mData->pMachineConfigFile = pOldConfig;
8305 }
8306 catch (...)
8307 {
8308 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8309 }
8310
8311 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8312 {
8313 /* Fire the data change event, even on failure (since we've already
8314 * committed all data). This is done only for SessionMachines because
8315 * mutable Machine instances are always not registered (i.e. private
8316 * to the client process that creates them) and thus don't need to
8317 * inform callbacks. */
8318 if (isSessionMachine())
8319 mParent->onMachineDataChange(mData->mUuid);
8320 }
8321
8322 LogFlowThisFunc(("rc=%08X\n", rc));
8323 LogFlowThisFuncLeave();
8324 return rc;
8325}
8326
8327/**
8328 * Implementation for saving the machine settings into the given
8329 * settings::MachineConfigFile instance. This copies machine extradata
8330 * from the previous machine config file in the instance data, if any.
8331 *
8332 * This gets called from two locations:
8333 *
8334 * -- Machine::saveSettings(), during the regular XML writing;
8335 *
8336 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8337 * exported to OVF and we write the VirtualBox proprietary XML
8338 * into a <vbox:Machine> tag.
8339 *
8340 * This routine fills all the fields in there, including snapshots, *except*
8341 * for the following:
8342 *
8343 * -- fCurrentStateModified. There is some special logic associated with that.
8344 *
8345 * The caller can then call MachineConfigFile::write() or do something else
8346 * with it.
8347 *
8348 * Caller must hold the machine lock!
8349 *
8350 * This throws XML errors and HRESULT, so the caller must have a catch block!
8351 */
8352void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8353{
8354 // deep copy extradata
8355 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8356
8357 config.uuid = mData->mUuid;
8358
8359 // copy name, description, OS type, teleport, UTC etc.
8360 config.machineUserData = mUserData->s;
8361
8362 if ( mData->mMachineState == MachineState_Saved
8363 || mData->mMachineState == MachineState_Restoring
8364 // when deleting a snapshot we may or may not have a saved state in the current state,
8365 // so let's not assert here please
8366 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8367 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8368 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8369 && (!mSSData->strStateFilePath.isEmpty())
8370 )
8371 )
8372 {
8373 Assert(!mSSData->strStateFilePath.isEmpty());
8374 /* try to make the file name relative to the settings file dir */
8375 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
8376 }
8377 else
8378 {
8379 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
8380 config.strStateFile.setNull();
8381 }
8382
8383 if (mData->mCurrentSnapshot)
8384 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8385 else
8386 config.uuidCurrentSnapshot.clear();
8387
8388 config.timeLastStateChange = mData->mLastStateChange;
8389 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8390 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8391
8392 HRESULT rc = saveHardware(config.hardwareMachine);
8393 if (FAILED(rc)) throw rc;
8394
8395 rc = saveStorageControllers(config.storageMachine);
8396 if (FAILED(rc)) throw rc;
8397
8398 // save machine's media registry if this is VirtualBox 4.0 or later
8399 if (config.canHaveOwnMediaRegistry())
8400 {
8401 // determine machine folder
8402 Utf8Str strMachineFolder = getSettingsFileFull();
8403 strMachineFolder.stripFilename();
8404 mParent->saveMediaRegistry(config.mediaRegistry,
8405 getId(), // only media with registry ID == machine UUID
8406 strMachineFolder);
8407 // this throws HRESULT
8408 }
8409
8410 // save snapshots
8411 rc = saveAllSnapshots(config);
8412 if (FAILED(rc)) throw rc;
8413}
8414
8415/**
8416 * Saves all snapshots of the machine into the given machine config file. Called
8417 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8418 * @param config
8419 * @return
8420 */
8421HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8422{
8423 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8424
8425 HRESULT rc = S_OK;
8426
8427 try
8428 {
8429 config.llFirstSnapshot.clear();
8430
8431 if (mData->mFirstSnapshot)
8432 {
8433 settings::Snapshot snapNew;
8434 config.llFirstSnapshot.push_back(snapNew);
8435
8436 // get reference to the fresh copy of the snapshot on the list and
8437 // work on that copy directly to avoid excessive copying later
8438 settings::Snapshot &snap = config.llFirstSnapshot.front();
8439
8440 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8441 if (FAILED(rc)) throw rc;
8442 }
8443
8444// if (mType == IsSessionMachine)
8445// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8446
8447 }
8448 catch (HRESULT err)
8449 {
8450 /* we assume that error info is set by the thrower */
8451 rc = err;
8452 }
8453 catch (...)
8454 {
8455 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8456 }
8457
8458 return rc;
8459}
8460
8461/**
8462 * Saves the VM hardware configuration. It is assumed that the
8463 * given node is empty.
8464 *
8465 * @param aNode <Hardware> node to save the VM hardware configuration to.
8466 */
8467HRESULT Machine::saveHardware(settings::Hardware &data)
8468{
8469 HRESULT rc = S_OK;
8470
8471 try
8472 {
8473 /* The hardware version attribute (optional).
8474 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8475 if ( mHWData->mHWVersion == "1"
8476 && mSSData->strStateFilePath.isEmpty()
8477 )
8478 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. */
8479
8480 data.strVersion = mHWData->mHWVersion;
8481 data.uuid = mHWData->mHardwareUUID;
8482
8483 // CPU
8484 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8485 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8486 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8487 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8488 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8489 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8490 data.fPAE = !!mHWData->mPAEEnabled;
8491 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8492
8493 /* Standard and Extended CPUID leafs. */
8494 data.llCpuIdLeafs.clear();
8495 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8496 {
8497 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8498 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8499 }
8500 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8501 {
8502 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8503 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8504 }
8505
8506 data.cCPUs = mHWData->mCPUCount;
8507 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8508 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8509
8510 data.llCpus.clear();
8511 if (data.fCpuHotPlug)
8512 {
8513 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8514 {
8515 if (mHWData->mCPUAttached[idx])
8516 {
8517 settings::Cpu cpu;
8518 cpu.ulId = idx;
8519 data.llCpus.push_back(cpu);
8520 }
8521 }
8522 }
8523
8524 // memory
8525 data.ulMemorySizeMB = mHWData->mMemorySize;
8526 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8527
8528 // firmware
8529 data.firmwareType = mHWData->mFirmwareType;
8530
8531 // HID
8532 data.pointingHidType = mHWData->mPointingHidType;
8533 data.keyboardHidType = mHWData->mKeyboardHidType;
8534
8535 // chipset
8536 data.chipsetType = mHWData->mChipsetType;
8537
8538 // HPET
8539 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8540
8541 // boot order
8542 data.mapBootOrder.clear();
8543 for (size_t i = 0;
8544 i < RT_ELEMENTS(mHWData->mBootOrder);
8545 ++i)
8546 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8547
8548 // display
8549 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8550 data.cMonitors = mHWData->mMonitorCount;
8551 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8552 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8553
8554 /* VRDEServer settings (optional) */
8555 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8556 if (FAILED(rc)) throw rc;
8557
8558 /* BIOS (required) */
8559 rc = mBIOSSettings->saveSettings(data.biosSettings);
8560 if (FAILED(rc)) throw rc;
8561
8562 /* USB Controller (required) */
8563 rc = mUSBController->saveSettings(data.usbController);
8564 if (FAILED(rc)) throw rc;
8565
8566 /* Network adapters (required) */
8567 data.llNetworkAdapters.clear();
8568 for (ULONG slot = 0;
8569 slot < RT_ELEMENTS(mNetworkAdapters);
8570 ++slot)
8571 {
8572 settings::NetworkAdapter nic;
8573 nic.ulSlot = slot;
8574 rc = mNetworkAdapters[slot]->saveSettings(nic);
8575 if (FAILED(rc)) throw rc;
8576
8577 data.llNetworkAdapters.push_back(nic);
8578 }
8579
8580 /* Serial ports */
8581 data.llSerialPorts.clear();
8582 for (ULONG slot = 0;
8583 slot < RT_ELEMENTS(mSerialPorts);
8584 ++slot)
8585 {
8586 settings::SerialPort s;
8587 s.ulSlot = slot;
8588 rc = mSerialPorts[slot]->saveSettings(s);
8589 if (FAILED(rc)) return rc;
8590
8591 data.llSerialPorts.push_back(s);
8592 }
8593
8594 /* Parallel ports */
8595 data.llParallelPorts.clear();
8596 for (ULONG slot = 0;
8597 slot < RT_ELEMENTS(mParallelPorts);
8598 ++slot)
8599 {
8600 settings::ParallelPort p;
8601 p.ulSlot = slot;
8602 rc = mParallelPorts[slot]->saveSettings(p);
8603 if (FAILED(rc)) return rc;
8604
8605 data.llParallelPorts.push_back(p);
8606 }
8607
8608 /* Audio adapter */
8609 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8610 if (FAILED(rc)) return rc;
8611
8612 /* Shared folders */
8613 data.llSharedFolders.clear();
8614 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8615 it != mHWData->mSharedFolders.end();
8616 ++it)
8617 {
8618 SharedFolder *pSF = *it;
8619 AutoCaller sfCaller(pSF);
8620 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8621 settings::SharedFolder sf;
8622 sf.strName = pSF->getName();
8623 sf.strHostPath = pSF->getHostPath();
8624 sf.fWritable = !!pSF->isWritable();
8625 sf.fAutoMount = !!pSF->isAutoMounted();
8626
8627 data.llSharedFolders.push_back(sf);
8628 }
8629
8630 // clipboard
8631 data.clipboardMode = mHWData->mClipboardMode;
8632
8633 /* Guest */
8634 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8635
8636 // IO settings
8637 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8638 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8639
8640 /* BandwidthControl (required) */
8641 rc = mBandwidthControl->saveSettings(data.ioSettings);
8642 if (FAILED(rc)) throw rc;
8643
8644 /* Host PCI devices */
8645 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
8646 it != mHWData->mPciDeviceAssignments.end();
8647 ++it)
8648 {
8649 ComObjPtr<PciDeviceAttachment> pda = *it;
8650 settings::HostPciDeviceAttachment hpda;
8651
8652 rc = pda->saveSettings(hpda);
8653 if (FAILED(rc)) throw rc;
8654
8655 data.pciAttachments.push_back(hpda);
8656 }
8657
8658
8659 // guest properties
8660 data.llGuestProperties.clear();
8661#ifdef VBOX_WITH_GUEST_PROPS
8662 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8663 it != mHWData->mGuestProperties.end();
8664 ++it)
8665 {
8666 HWData::GuestProperty property = *it;
8667
8668 /* Remove transient guest properties at shutdown unless we
8669 * are saving state */
8670 if ( ( mData->mMachineState == MachineState_PoweredOff
8671 || mData->mMachineState == MachineState_Aborted
8672 || mData->mMachineState == MachineState_Teleported)
8673 && ( property.mFlags & guestProp::TRANSIENT
8674 || property.mFlags & guestProp::TRANSRESET))
8675 continue;
8676 settings::GuestProperty prop;
8677 prop.strName = property.strName;
8678 prop.strValue = property.strValue;
8679 prop.timestamp = property.mTimestamp;
8680 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8681 guestProp::writeFlags(property.mFlags, szFlags);
8682 prop.strFlags = szFlags;
8683
8684 data.llGuestProperties.push_back(prop);
8685 }
8686
8687 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8688 /* I presume this doesn't require a backup(). */
8689 mData->mGuestPropertiesModified = FALSE;
8690#endif /* VBOX_WITH_GUEST_PROPS defined */
8691 }
8692 catch(std::bad_alloc &)
8693 {
8694 return E_OUTOFMEMORY;
8695 }
8696
8697 AssertComRC(rc);
8698 return rc;
8699}
8700
8701/**
8702 * Saves the storage controller configuration.
8703 *
8704 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8705 */
8706HRESULT Machine::saveStorageControllers(settings::Storage &data)
8707{
8708 data.llStorageControllers.clear();
8709
8710 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8711 it != mStorageControllers->end();
8712 ++it)
8713 {
8714 HRESULT rc;
8715 ComObjPtr<StorageController> pCtl = *it;
8716
8717 settings::StorageController ctl;
8718 ctl.strName = pCtl->getName();
8719 ctl.controllerType = pCtl->getControllerType();
8720 ctl.storageBus = pCtl->getStorageBus();
8721 ctl.ulInstance = pCtl->getInstance();
8722 ctl.fBootable = pCtl->getBootable();
8723
8724 /* Save the port count. */
8725 ULONG portCount;
8726 rc = pCtl->COMGETTER(PortCount)(&portCount);
8727 ComAssertComRCRet(rc, rc);
8728 ctl.ulPortCount = portCount;
8729
8730 /* Save fUseHostIOCache */
8731 BOOL fUseHostIOCache;
8732 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8733 ComAssertComRCRet(rc, rc);
8734 ctl.fUseHostIOCache = !!fUseHostIOCache;
8735
8736 /* Save IDE emulation settings. */
8737 if (ctl.controllerType == StorageControllerType_IntelAhci)
8738 {
8739 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8740 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8741 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8742 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8743 )
8744 ComAssertComRCRet(rc, rc);
8745 }
8746
8747 /* save the devices now. */
8748 rc = saveStorageDevices(pCtl, ctl);
8749 ComAssertComRCRet(rc, rc);
8750
8751 data.llStorageControllers.push_back(ctl);
8752 }
8753
8754 return S_OK;
8755}
8756
8757/**
8758 * Saves the hard disk configuration.
8759 */
8760HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8761 settings::StorageController &data)
8762{
8763 MediaData::AttachmentList atts;
8764
8765 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8766 if (FAILED(rc)) return rc;
8767
8768 data.llAttachedDevices.clear();
8769 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8770 it != atts.end();
8771 ++it)
8772 {
8773 settings::AttachedDevice dev;
8774
8775 MediumAttachment *pAttach = *it;
8776 Medium *pMedium = pAttach->getMedium();
8777
8778 dev.deviceType = pAttach->getType();
8779 dev.lPort = pAttach->getPort();
8780 dev.lDevice = pAttach->getDevice();
8781 if (pMedium)
8782 {
8783 if (pMedium->isHostDrive())
8784 dev.strHostDriveSrc = pMedium->getLocationFull();
8785 else
8786 dev.uuid = pMedium->getId();
8787 dev.fPassThrough = pAttach->getPassthrough();
8788 }
8789
8790 dev.strBwGroup = pAttach->getBandwidthGroup();
8791
8792 data.llAttachedDevices.push_back(dev);
8793 }
8794
8795 return S_OK;
8796}
8797
8798/**
8799 * Saves machine state settings as defined by aFlags
8800 * (SaveSTS_* values).
8801 *
8802 * @param aFlags Combination of SaveSTS_* flags.
8803 *
8804 * @note Locks objects for writing.
8805 */
8806HRESULT Machine::saveStateSettings(int aFlags)
8807{
8808 if (aFlags == 0)
8809 return S_OK;
8810
8811 AutoCaller autoCaller(this);
8812 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8813
8814 /* This object's write lock is also necessary to serialize file access
8815 * (prevent concurrent reads and writes) */
8816 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8817
8818 HRESULT rc = S_OK;
8819
8820 Assert(mData->pMachineConfigFile);
8821
8822 try
8823 {
8824 if (aFlags & SaveSTS_CurStateModified)
8825 mData->pMachineConfigFile->fCurrentStateModified = true;
8826
8827 if (aFlags & SaveSTS_StateFilePath)
8828 {
8829 if (!mSSData->strStateFilePath.isEmpty())
8830 /* try to make the file name relative to the settings file dir */
8831 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
8832 else
8833 mData->pMachineConfigFile->strStateFile.setNull();
8834 }
8835
8836 if (aFlags & SaveSTS_StateTimeStamp)
8837 {
8838 Assert( mData->mMachineState != MachineState_Aborted
8839 || mSSData->strStateFilePath.isEmpty());
8840
8841 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8842
8843 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8844//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8845 }
8846
8847 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8848 }
8849 catch (...)
8850 {
8851 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8852 }
8853
8854 return rc;
8855}
8856
8857/**
8858 * Ensures that the given medium is added to a media registry. If this machine
8859 * was created with 4.0 or later, then the machine registry is used. Otherwise
8860 * the global VirtualBox media registry is used. If the medium was actually
8861 * added to a registry (because it wasn't in the registry yet), the UUID of
8862 * that registry is added to the given list so that the caller can save the
8863 * registry.
8864 *
8865 * Caller must hold machine read lock!
8866 *
8867 * @param pMedium
8868 * @param llRegistriesThatNeedSaving
8869 * @param puuid Optional buffer that receives the registry UUID that was used.
8870 */
8871void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
8872 GuidList &llRegistriesThatNeedSaving,
8873 Guid *puuid)
8874{
8875 // decide which medium registry to use now that the medium is attached:
8876 Guid uuid;
8877 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
8878 // machine XML is VirtualBox 4.0 or higher:
8879 uuid = getId(); // machine UUID
8880 else
8881 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
8882
8883 AutoCaller autoCaller(pMedium);
8884 if (FAILED(autoCaller.rc())) return;
8885 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8886
8887 if (pMedium->addRegistry(uuid, false /* fRecurse */))
8888 // registry actually changed:
8889 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
8890
8891 if (puuid)
8892 *puuid = uuid;
8893}
8894
8895/**
8896 * Creates differencing hard disks for all normal hard disks attached to this
8897 * machine and a new set of attachments to refer to created disks.
8898 *
8899 * Used when taking a snapshot or when deleting the current state. Gets called
8900 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8901 *
8902 * This method assumes that mMediaData contains the original hard disk attachments
8903 * it needs to create diffs for. On success, these attachments will be replaced
8904 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8905 * called to delete created diffs which will also rollback mMediaData and restore
8906 * whatever was backed up before calling this method.
8907 *
8908 * Attachments with non-normal hard disks are left as is.
8909 *
8910 * If @a aOnline is @c false then the original hard disks that require implicit
8911 * diffs will be locked for reading. Otherwise it is assumed that they are
8912 * already locked for writing (when the VM was started). Note that in the latter
8913 * case it is responsibility of the caller to lock the newly created diffs for
8914 * writing if this method succeeds.
8915 *
8916 * @param aProgress Progress object to run (must contain at least as
8917 * many operations left as the number of hard disks
8918 * attached).
8919 * @param aOnline Whether the VM was online prior to this operation.
8920 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
8921 *
8922 * @note The progress object is not marked as completed, neither on success nor
8923 * on failure. This is a responsibility of the caller.
8924 *
8925 * @note Locks this object for writing.
8926 */
8927HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8928 ULONG aWeight,
8929 bool aOnline,
8930 GuidList *pllRegistriesThatNeedSaving)
8931{
8932 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8933
8934 AutoCaller autoCaller(this);
8935 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8936
8937 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8938
8939 /* must be in a protective state because we leave the lock below */
8940 AssertReturn( mData->mMachineState == MachineState_Saving
8941 || mData->mMachineState == MachineState_LiveSnapshotting
8942 || mData->mMachineState == MachineState_RestoringSnapshot
8943 || mData->mMachineState == MachineState_DeletingSnapshot
8944 , E_FAIL);
8945
8946 HRESULT rc = S_OK;
8947
8948 MediumLockListMap lockedMediaOffline;
8949 MediumLockListMap *lockedMediaMap;
8950 if (aOnline)
8951 lockedMediaMap = &mData->mSession.mLockedMedia;
8952 else
8953 lockedMediaMap = &lockedMediaOffline;
8954
8955 try
8956 {
8957 if (!aOnline)
8958 {
8959 /* lock all attached hard disks early to detect "in use"
8960 * situations before creating actual diffs */
8961 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8962 it != mMediaData->mAttachments.end();
8963 ++it)
8964 {
8965 MediumAttachment* pAtt = *it;
8966 if (pAtt->getType() == DeviceType_HardDisk)
8967 {
8968 Medium* pMedium = pAtt->getMedium();
8969 Assert(pMedium);
8970
8971 MediumLockList *pMediumLockList(new MediumLockList());
8972 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8973 false /* fMediumLockWrite */,
8974 NULL,
8975 *pMediumLockList);
8976 if (FAILED(rc))
8977 {
8978 delete pMediumLockList;
8979 throw rc;
8980 }
8981 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8982 if (FAILED(rc))
8983 {
8984 throw setError(rc,
8985 tr("Collecting locking information for all attached media failed"));
8986 }
8987 }
8988 }
8989
8990 /* Now lock all media. If this fails, nothing is locked. */
8991 rc = lockedMediaMap->Lock();
8992 if (FAILED(rc))
8993 {
8994 throw setError(rc,
8995 tr("Locking of attached media failed"));
8996 }
8997 }
8998
8999 /* remember the current list (note that we don't use backup() since
9000 * mMediaData may be already backed up) */
9001 MediaData::AttachmentList atts = mMediaData->mAttachments;
9002
9003 /* start from scratch */
9004 mMediaData->mAttachments.clear();
9005
9006 /* go through remembered attachments and create diffs for normal hard
9007 * disks and attach them */
9008 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9009 it != atts.end();
9010 ++it)
9011 {
9012 MediumAttachment* pAtt = *it;
9013
9014 DeviceType_T devType = pAtt->getType();
9015 Medium* pMedium = pAtt->getMedium();
9016
9017 if ( devType != DeviceType_HardDisk
9018 || pMedium == NULL
9019 || pMedium->getType() != MediumType_Normal)
9020 {
9021 /* copy the attachment as is */
9022
9023 /** @todo the progress object created in Console::TakeSnaphot
9024 * only expects operations for hard disks. Later other
9025 * device types need to show up in the progress as well. */
9026 if (devType == DeviceType_HardDisk)
9027 {
9028 if (pMedium == NULL)
9029 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9030 aWeight); // weight
9031 else
9032 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9033 pMedium->getBase()->getName().c_str()).raw(),
9034 aWeight); // weight
9035 }
9036
9037 mMediaData->mAttachments.push_back(pAtt);
9038 continue;
9039 }
9040
9041 /* need a diff */
9042 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9043 pMedium->getBase()->getName().c_str()).raw(),
9044 aWeight); // weight
9045
9046 Utf8Str strFullSnapshotFolder;
9047 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9048
9049 ComObjPtr<Medium> diff;
9050 diff.createObject();
9051 // store the diff in the same registry as the parent
9052 // (this cannot fail here because we can't create implicit diffs for
9053 // unregistered images)
9054 Guid uuidRegistryParent;
9055 Assert(pMedium->getFirstRegistryMachineId(uuidRegistryParent));
9056 rc = diff->init(mParent,
9057 pMedium->getPreferredDiffFormat(),
9058 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9059 uuidRegistryParent,
9060 pllRegistriesThatNeedSaving);
9061 if (FAILED(rc)) throw rc;
9062
9063 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9064 * the push_back? Looks like we're going to leave medium with the
9065 * wrong kind of lock (general issue with if we fail anywhere at all)
9066 * and an orphaned VDI in the snapshots folder. */
9067
9068 /* update the appropriate lock list */
9069 MediumLockList *pMediumLockList;
9070 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9071 AssertComRCThrowRC(rc);
9072 if (aOnline)
9073 {
9074 rc = pMediumLockList->Update(pMedium, false);
9075 AssertComRCThrowRC(rc);
9076 }
9077
9078 /* leave the lock before the potentially lengthy operation */
9079 alock.leave();
9080 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9081 pMediumLockList,
9082 NULL /* aProgress */,
9083 true /* aWait */,
9084 pllRegistriesThatNeedSaving);
9085 alock.enter();
9086 if (FAILED(rc)) throw rc;
9087
9088 rc = lockedMediaMap->Unlock();
9089 AssertComRCThrowRC(rc);
9090 rc = pMediumLockList->Append(diff, true);
9091 AssertComRCThrowRC(rc);
9092 rc = lockedMediaMap->Lock();
9093 AssertComRCThrowRC(rc);
9094
9095 rc = diff->addBackReference(mData->mUuid);
9096 AssertComRCThrowRC(rc);
9097
9098 /* add a new attachment */
9099 ComObjPtr<MediumAttachment> attachment;
9100 attachment.createObject();
9101 rc = attachment->init(this,
9102 diff,
9103 pAtt->getControllerName(),
9104 pAtt->getPort(),
9105 pAtt->getDevice(),
9106 DeviceType_HardDisk,
9107 true /* aImplicit */,
9108 pAtt->getBandwidthGroup());
9109 if (FAILED(rc)) throw rc;
9110
9111 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9112 AssertComRCThrowRC(rc);
9113 mMediaData->mAttachments.push_back(attachment);
9114 }
9115 }
9116 catch (HRESULT aRC) { rc = aRC; }
9117
9118 /* unlock all hard disks we locked */
9119 if (!aOnline)
9120 {
9121 ErrorInfoKeeper eik;
9122
9123 rc = lockedMediaMap->Clear();
9124 AssertComRC(rc);
9125 }
9126
9127 if (FAILED(rc))
9128 {
9129 MultiResult mrc = rc;
9130
9131 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9132 }
9133
9134 return rc;
9135}
9136
9137/**
9138 * Deletes implicit differencing hard disks created either by
9139 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
9140 *
9141 * Note that to delete hard disks created by #AttachMedium() this method is
9142 * called from #fixupMedia() when the changes are rolled back.
9143 *
9144 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9145 *
9146 * @note Locks this object for writing.
9147 */
9148HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9149{
9150 AutoCaller autoCaller(this);
9151 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9152
9153 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9154 LogFlowThisFuncEnter();
9155
9156 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9157
9158 HRESULT rc = S_OK;
9159
9160 MediaData::AttachmentList implicitAtts;
9161
9162 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9163
9164 /* enumerate new attachments */
9165 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9166 it != mMediaData->mAttachments.end();
9167 ++it)
9168 {
9169 ComObjPtr<Medium> hd = (*it)->getMedium();
9170 if (hd.isNull())
9171 continue;
9172
9173 if ((*it)->isImplicit())
9174 {
9175 /* deassociate and mark for deletion */
9176 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
9177 rc = hd->removeBackReference(mData->mUuid);
9178 AssertComRC(rc);
9179 implicitAtts.push_back(*it);
9180 continue;
9181 }
9182
9183 /* was this hard disk attached before? */
9184 if (!findAttachment(oldAtts, hd))
9185 {
9186 /* no: de-associate */
9187 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9188 rc = hd->removeBackReference(mData->mUuid);
9189 AssertComRC(rc);
9190 continue;
9191 }
9192 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9193 }
9194
9195 /* rollback hard disk changes */
9196 mMediaData.rollback();
9197
9198 MultiResult mrc(S_OK);
9199
9200 /* delete unused implicit diffs */
9201 if (implicitAtts.size() != 0)
9202 {
9203 /* will leave the lock before the potentially lengthy
9204 * operation, so protect with the special state (unless already
9205 * protected) */
9206 MachineState_T oldState = mData->mMachineState;
9207 if ( oldState != MachineState_Saving
9208 && oldState != MachineState_LiveSnapshotting
9209 && oldState != MachineState_RestoringSnapshot
9210 && oldState != MachineState_DeletingSnapshot
9211 && oldState != MachineState_DeletingSnapshotOnline
9212 && oldState != MachineState_DeletingSnapshotPaused
9213 )
9214 setMachineState(MachineState_SettingUp);
9215
9216 alock.leave();
9217
9218 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9219 it != implicitAtts.end();
9220 ++it)
9221 {
9222 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9223 ComObjPtr<Medium> hd = (*it)->getMedium();
9224
9225 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9226 pllRegistriesThatNeedSaving);
9227 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9228 mrc = rc;
9229 }
9230
9231 alock.enter();
9232
9233 if (mData->mMachineState == MachineState_SettingUp)
9234 setMachineState(oldState);
9235 }
9236
9237 return mrc;
9238}
9239
9240/**
9241 * Looks through the given list of media attachments for one with the given parameters
9242 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9243 * can be searched as well if needed.
9244 *
9245 * @param list
9246 * @param aControllerName
9247 * @param aControllerPort
9248 * @param aDevice
9249 * @return
9250 */
9251MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9252 IN_BSTR aControllerName,
9253 LONG aControllerPort,
9254 LONG aDevice)
9255{
9256 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9257 it != ll.end();
9258 ++it)
9259 {
9260 MediumAttachment *pAttach = *it;
9261 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9262 return pAttach;
9263 }
9264
9265 return NULL;
9266}
9267
9268/**
9269 * Looks through the given list of media attachments for one with the given parameters
9270 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9271 * can be searched as well if needed.
9272 *
9273 * @param list
9274 * @param aControllerName
9275 * @param aControllerPort
9276 * @param aDevice
9277 * @return
9278 */
9279MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9280 ComObjPtr<Medium> pMedium)
9281{
9282 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9283 it != ll.end();
9284 ++it)
9285 {
9286 MediumAttachment *pAttach = *it;
9287 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9288 if (pMediumThis == pMedium)
9289 return pAttach;
9290 }
9291
9292 return NULL;
9293}
9294
9295/**
9296 * Looks through the given list of media attachments for one with the given parameters
9297 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9298 * can be searched as well if needed.
9299 *
9300 * @param list
9301 * @param aControllerName
9302 * @param aControllerPort
9303 * @param aDevice
9304 * @return
9305 */
9306MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9307 Guid &id)
9308{
9309 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9310 it != ll.end();
9311 ++it)
9312 {
9313 MediumAttachment *pAttach = *it;
9314 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9315 if (pMediumThis->getId() == id)
9316 return pAttach;
9317 }
9318
9319 return NULL;
9320}
9321
9322/**
9323 * Main implementation for Machine::DetachDevice. This also gets called
9324 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9325 *
9326 * @param pAttach Medium attachment to detach.
9327 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9328 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9329 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9330 * @return
9331 */
9332HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9333 AutoWriteLock &writeLock,
9334 Snapshot *pSnapshot,
9335 GuidList *pllRegistriesThatNeedSaving)
9336{
9337 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9338 DeviceType_T mediumType = pAttach->getType();
9339
9340 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9341
9342 if (pAttach->isImplicit())
9343 {
9344 /* attempt to implicitly delete the implicitly created diff */
9345
9346 /// @todo move the implicit flag from MediumAttachment to Medium
9347 /// and forbid any hard disk operation when it is implicit. Or maybe
9348 /// a special media state for it to make it even more simple.
9349
9350 Assert(mMediaData.isBackedUp());
9351
9352 /* will leave the lock before the potentially lengthy operation, so
9353 * protect with the special state */
9354 MachineState_T oldState = mData->mMachineState;
9355 setMachineState(MachineState_SettingUp);
9356
9357 writeLock.release();
9358
9359 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
9360 true /*aWait*/,
9361 pllRegistriesThatNeedSaving);
9362
9363 writeLock.acquire();
9364
9365 setMachineState(oldState);
9366
9367 if (FAILED(rc)) return rc;
9368 }
9369
9370 setModified(IsModified_Storage);
9371 mMediaData.backup();
9372
9373 // we cannot use erase (it) below because backup() above will create
9374 // a copy of the list and make this copy active, but the iterator
9375 // still refers to the original and is not valid for the copy
9376 mMediaData->mAttachments.remove(pAttach);
9377
9378 if (!oldmedium.isNull())
9379 {
9380 // if this is from a snapshot, do not defer detachment to commitMedia()
9381 if (pSnapshot)
9382 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9383 // else if non-hard disk media, do not defer detachment to commitMedia() either
9384 else if (mediumType != DeviceType_HardDisk)
9385 oldmedium->removeBackReference(mData->mUuid);
9386 }
9387
9388 return S_OK;
9389}
9390
9391/**
9392 * Goes thru all media of the given list and
9393 *
9394 * 1) calls detachDevice() on each of them for this machine and
9395 * 2) adds all Medium objects found in the process to the given list,
9396 * depending on cleanupMode.
9397 *
9398 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
9399 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
9400 * media to the list.
9401 *
9402 * This gets called from Machine::Unregister, both for the actual Machine and
9403 * the SnapshotMachine objects that might be found in the snapshots.
9404 *
9405 * Requires caller and locking. The machine lock must be passed in because it
9406 * will be passed on to detachDevice which needs it for temporary unlocking.
9407 *
9408 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9409 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9410 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9411 * otherwise no media get added.
9412 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9413 * @return
9414 */
9415HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9416 Snapshot *pSnapshot,
9417 CleanupMode_T cleanupMode,
9418 MediaList &llMedia)
9419{
9420 Assert(isWriteLockOnCurrentThread());
9421
9422 HRESULT rc;
9423
9424 // make a temporary list because detachDevice invalidates iterators into
9425 // mMediaData->mAttachments
9426 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9427
9428 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9429 it != llAttachments2.end();
9430 ++it)
9431 {
9432 ComObjPtr<MediumAttachment> &pAttach = *it;
9433 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9434
9435 if (!pMedium.isNull())
9436 {
9437 DeviceType_T devType = pMedium->getDeviceType();
9438 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9439 && devType == DeviceType_HardDisk)
9440 || (cleanupMode == CleanupMode_Full)
9441 )
9442 llMedia.push_back(pMedium);
9443 }
9444
9445 // real machine: then we need to use the proper method
9446 rc = detachDevice(pAttach,
9447 writeLock,
9448 pSnapshot,
9449 NULL /* pfNeedsSaveSettings */);
9450
9451 if (FAILED(rc))
9452 return rc;
9453 }
9454
9455 return S_OK;
9456}
9457
9458/**
9459 * Perform deferred hard disk detachments.
9460 *
9461 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9462 * backed up).
9463 *
9464 * If @a aOnline is @c true then this method will also unlock the old hard disks
9465 * for which the new implicit diffs were created and will lock these new diffs for
9466 * writing.
9467 *
9468 * @param aOnline Whether the VM was online prior to this operation.
9469 *
9470 * @note Locks this object for writing!
9471 */
9472void Machine::commitMedia(bool aOnline /*= false*/)
9473{
9474 AutoCaller autoCaller(this);
9475 AssertComRCReturnVoid(autoCaller.rc());
9476
9477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9478
9479 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9480
9481 HRESULT rc = S_OK;
9482
9483 /* no attach/detach operations -- nothing to do */
9484 if (!mMediaData.isBackedUp())
9485 return;
9486
9487 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9488 bool fMediaNeedsLocking = false;
9489
9490 /* enumerate new attachments */
9491 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9492 it != mMediaData->mAttachments.end();
9493 ++it)
9494 {
9495 MediumAttachment *pAttach = *it;
9496
9497 pAttach->commit();
9498
9499 Medium* pMedium = pAttach->getMedium();
9500 bool fImplicit = pAttach->isImplicit();
9501
9502 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9503 (pMedium) ? pMedium->getName().c_str() : "NULL",
9504 fImplicit));
9505
9506 /** @todo convert all this Machine-based voodoo to MediumAttachment
9507 * based commit logic. */
9508 if (fImplicit)
9509 {
9510 /* convert implicit attachment to normal */
9511 pAttach->setImplicit(false);
9512
9513 if ( aOnline
9514 && pMedium
9515 && pAttach->getType() == DeviceType_HardDisk
9516 )
9517 {
9518 ComObjPtr<Medium> parent = pMedium->getParent();
9519 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9520
9521 /* update the appropriate lock list */
9522 MediumLockList *pMediumLockList;
9523 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9524 AssertComRC(rc);
9525 if (pMediumLockList)
9526 {
9527 /* unlock if there's a need to change the locking */
9528 if (!fMediaNeedsLocking)
9529 {
9530 rc = mData->mSession.mLockedMedia.Unlock();
9531 AssertComRC(rc);
9532 fMediaNeedsLocking = true;
9533 }
9534 rc = pMediumLockList->Update(parent, false);
9535 AssertComRC(rc);
9536 rc = pMediumLockList->Append(pMedium, true);
9537 AssertComRC(rc);
9538 }
9539 }
9540
9541 continue;
9542 }
9543
9544 if (pMedium)
9545 {
9546 /* was this medium attached before? */
9547 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9548 oldIt != oldAtts.end();
9549 ++oldIt)
9550 {
9551 MediumAttachment *pOldAttach = *oldIt;
9552 if (pOldAttach->getMedium() == pMedium)
9553 {
9554 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9555
9556 /* yes: remove from old to avoid de-association */
9557 oldAtts.erase(oldIt);
9558 break;
9559 }
9560 }
9561 }
9562 }
9563
9564 /* enumerate remaining old attachments and de-associate from the
9565 * current machine state */
9566 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9567 it != oldAtts.end();
9568 ++it)
9569 {
9570 MediumAttachment *pAttach = *it;
9571 Medium* pMedium = pAttach->getMedium();
9572
9573 /* Detach only hard disks, since DVD/floppy media is detached
9574 * instantly in MountMedium. */
9575 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9576 {
9577 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9578
9579 /* now de-associate from the current machine state */
9580 rc = pMedium->removeBackReference(mData->mUuid);
9581 AssertComRC(rc);
9582
9583 if (aOnline)
9584 {
9585 /* unlock since medium is not used anymore */
9586 MediumLockList *pMediumLockList;
9587 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9588 AssertComRC(rc);
9589 if (pMediumLockList)
9590 {
9591 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9592 AssertComRC(rc);
9593 }
9594 }
9595 }
9596 }
9597
9598 /* take media locks again so that the locking state is consistent */
9599 if (fMediaNeedsLocking)
9600 {
9601 Assert(aOnline);
9602 rc = mData->mSession.mLockedMedia.Lock();
9603 AssertComRC(rc);
9604 }
9605
9606 /* commit the hard disk changes */
9607 mMediaData.commit();
9608
9609 if (isSessionMachine())
9610 {
9611 /*
9612 * Update the parent machine to point to the new owner.
9613 * This is necessary because the stored parent will point to the
9614 * session machine otherwise and cause crashes or errors later
9615 * when the session machine gets invalid.
9616 */
9617 /** @todo Change the MediumAttachment class to behave like any other
9618 * class in this regard by creating peer MediumAttachment
9619 * objects for session machines and share the data with the peer
9620 * machine.
9621 */
9622 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9623 it != mMediaData->mAttachments.end();
9624 ++it)
9625 {
9626 (*it)->updateParentMachine(mPeer);
9627 }
9628
9629 /* attach new data to the primary machine and reshare it */
9630 mPeer->mMediaData.attach(mMediaData);
9631 }
9632
9633 return;
9634}
9635
9636/**
9637 * Perform deferred deletion of implicitly created diffs.
9638 *
9639 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9640 * backed up).
9641 *
9642 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9643 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9644 *
9645 * @note Locks this object for writing!
9646 *
9647 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
9648 */
9649void Machine::rollbackMedia()
9650{
9651 AutoCaller autoCaller(this);
9652 AssertComRCReturnVoid (autoCaller.rc());
9653
9654 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9655
9656 LogFlowThisFunc(("Entering\n"));
9657
9658 HRESULT rc = S_OK;
9659
9660 /* no attach/detach operations -- nothing to do */
9661 if (!mMediaData.isBackedUp())
9662 return;
9663
9664 /* enumerate new attachments */
9665 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9666 it != mMediaData->mAttachments.end();
9667 ++it)
9668 {
9669 MediumAttachment *pAttach = *it;
9670 /* Fix up the backrefs for DVD/floppy media. */
9671 if (pAttach->getType() != DeviceType_HardDisk)
9672 {
9673 Medium* pMedium = pAttach->getMedium();
9674 if (pMedium)
9675 {
9676 rc = pMedium->removeBackReference(mData->mUuid);
9677 AssertComRC(rc);
9678 }
9679 }
9680
9681 (*it)->rollback();
9682
9683 pAttach = *it;
9684 /* Fix up the backrefs for DVD/floppy media. */
9685 if (pAttach->getType() != DeviceType_HardDisk)
9686 {
9687 Medium* pMedium = pAttach->getMedium();
9688 if (pMedium)
9689 {
9690 rc = pMedium->addBackReference(mData->mUuid);
9691 AssertComRC(rc);
9692 }
9693 }
9694 }
9695
9696 /** @todo convert all this Machine-based voodoo to MediumAttachment
9697 * based rollback logic. */
9698 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9699 // which gets called if Machine::registeredInit() fails...
9700 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9701
9702 return;
9703}
9704
9705/**
9706 * Returns true if the settings file is located in the directory named exactly
9707 * as the machine; this means, among other things, that the machine directory
9708 * should be auto-renamed.
9709 *
9710 * @param aSettingsDir if not NULL, the full machine settings file directory
9711 * name will be assigned there.
9712 *
9713 * @note Doesn't lock anything.
9714 * @note Not thread safe (must be called from this object's lock).
9715 */
9716bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9717{
9718 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9719 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9720 if (aSettingsDir)
9721 *aSettingsDir = strMachineDirName;
9722 strMachineDirName.stripPath(); // vmname
9723 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9724 strConfigFileOnly.stripPath() // vmname.vbox
9725 .stripExt(); // vmname
9726
9727 AssertReturn(!strMachineDirName.isEmpty(), false);
9728 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9729
9730 return strMachineDirName == strConfigFileOnly;
9731}
9732
9733/**
9734 * Discards all changes to machine settings.
9735 *
9736 * @param aNotify Whether to notify the direct session about changes or not.
9737 *
9738 * @note Locks objects for writing!
9739 */
9740void Machine::rollback(bool aNotify)
9741{
9742 AutoCaller autoCaller(this);
9743 AssertComRCReturn(autoCaller.rc(), (void)0);
9744
9745 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9746
9747 if (!mStorageControllers.isNull())
9748 {
9749 if (mStorageControllers.isBackedUp())
9750 {
9751 /* unitialize all new devices (absent in the backed up list). */
9752 StorageControllerList::const_iterator it = mStorageControllers->begin();
9753 StorageControllerList *backedList = mStorageControllers.backedUpData();
9754 while (it != mStorageControllers->end())
9755 {
9756 if ( std::find(backedList->begin(), backedList->end(), *it)
9757 == backedList->end()
9758 )
9759 {
9760 (*it)->uninit();
9761 }
9762 ++it;
9763 }
9764
9765 /* restore the list */
9766 mStorageControllers.rollback();
9767 }
9768
9769 /* rollback any changes to devices after restoring the list */
9770 if (mData->flModifications & IsModified_Storage)
9771 {
9772 StorageControllerList::const_iterator it = mStorageControllers->begin();
9773 while (it != mStorageControllers->end())
9774 {
9775 (*it)->rollback();
9776 ++it;
9777 }
9778 }
9779 }
9780
9781 mUserData.rollback();
9782
9783 mHWData.rollback();
9784
9785 if (mData->flModifications & IsModified_Storage)
9786 rollbackMedia();
9787
9788 if (mBIOSSettings)
9789 mBIOSSettings->rollback();
9790
9791 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9792 mVRDEServer->rollback();
9793
9794 if (mAudioAdapter)
9795 mAudioAdapter->rollback();
9796
9797 if (mUSBController && (mData->flModifications & IsModified_USB))
9798 mUSBController->rollback();
9799
9800 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
9801 mBandwidthControl->rollback();
9802
9803 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9804 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9805 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9806
9807 if (mData->flModifications & IsModified_NetworkAdapters)
9808 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9809 if ( mNetworkAdapters[slot]
9810 && mNetworkAdapters[slot]->isModified())
9811 {
9812 mNetworkAdapters[slot]->rollback();
9813 networkAdapters[slot] = mNetworkAdapters[slot];
9814 }
9815
9816 if (mData->flModifications & IsModified_SerialPorts)
9817 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9818 if ( mSerialPorts[slot]
9819 && mSerialPorts[slot]->isModified())
9820 {
9821 mSerialPorts[slot]->rollback();
9822 serialPorts[slot] = mSerialPorts[slot];
9823 }
9824
9825 if (mData->flModifications & IsModified_ParallelPorts)
9826 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9827 if ( mParallelPorts[slot]
9828 && mParallelPorts[slot]->isModified())
9829 {
9830 mParallelPorts[slot]->rollback();
9831 parallelPorts[slot] = mParallelPorts[slot];
9832 }
9833
9834 if (aNotify)
9835 {
9836 /* inform the direct session about changes */
9837
9838 ComObjPtr<Machine> that = this;
9839 uint32_t flModifications = mData->flModifications;
9840 alock.leave();
9841
9842 if (flModifications & IsModified_SharedFolders)
9843 that->onSharedFolderChange();
9844
9845 if (flModifications & IsModified_VRDEServer)
9846 that->onVRDEServerChange(/* aRestart */ TRUE);
9847 if (flModifications & IsModified_USB)
9848 that->onUSBControllerChange();
9849
9850 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9851 if (networkAdapters[slot])
9852 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9853 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9854 if (serialPorts[slot])
9855 that->onSerialPortChange(serialPorts[slot]);
9856 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9857 if (parallelPorts[slot])
9858 that->onParallelPortChange(parallelPorts[slot]);
9859
9860 if (flModifications & IsModified_Storage)
9861 that->onStorageControllerChange();
9862
9863#if 0
9864 if (flModifications & IsModified_BandwidthControl)
9865 that->onBandwidthControlChange();
9866#endif
9867 }
9868}
9869
9870/**
9871 * Commits all the changes to machine settings.
9872 *
9873 * Note that this operation is supposed to never fail.
9874 *
9875 * @note Locks this object and children for writing.
9876 */
9877void Machine::commit()
9878{
9879 AutoCaller autoCaller(this);
9880 AssertComRCReturnVoid(autoCaller.rc());
9881
9882 AutoCaller peerCaller(mPeer);
9883 AssertComRCReturnVoid(peerCaller.rc());
9884
9885 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9886
9887 /*
9888 * use safe commit to ensure Snapshot machines (that share mUserData)
9889 * will still refer to a valid memory location
9890 */
9891 mUserData.commitCopy();
9892
9893 mHWData.commit();
9894
9895 if (mMediaData.isBackedUp())
9896 commitMedia();
9897
9898 mBIOSSettings->commit();
9899 mVRDEServer->commit();
9900 mAudioAdapter->commit();
9901 mUSBController->commit();
9902 mBandwidthControl->commit();
9903
9904 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9905 mNetworkAdapters[slot]->commit();
9906 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9907 mSerialPorts[slot]->commit();
9908 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9909 mParallelPorts[slot]->commit();
9910
9911 bool commitStorageControllers = false;
9912
9913 if (mStorageControllers.isBackedUp())
9914 {
9915 mStorageControllers.commit();
9916
9917 if (mPeer)
9918 {
9919 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9920
9921 /* Commit all changes to new controllers (this will reshare data with
9922 * peers for those who have peers) */
9923 StorageControllerList *newList = new StorageControllerList();
9924 StorageControllerList::const_iterator it = mStorageControllers->begin();
9925 while (it != mStorageControllers->end())
9926 {
9927 (*it)->commit();
9928
9929 /* look if this controller has a peer device */
9930 ComObjPtr<StorageController> peer = (*it)->getPeer();
9931 if (!peer)
9932 {
9933 /* no peer means the device is a newly created one;
9934 * create a peer owning data this device share it with */
9935 peer.createObject();
9936 peer->init(mPeer, *it, true /* aReshare */);
9937 }
9938 else
9939 {
9940 /* remove peer from the old list */
9941 mPeer->mStorageControllers->remove(peer);
9942 }
9943 /* and add it to the new list */
9944 newList->push_back(peer);
9945
9946 ++it;
9947 }
9948
9949 /* uninit old peer's controllers that are left */
9950 it = mPeer->mStorageControllers->begin();
9951 while (it != mPeer->mStorageControllers->end())
9952 {
9953 (*it)->uninit();
9954 ++it;
9955 }
9956
9957 /* attach new list of controllers to our peer */
9958 mPeer->mStorageControllers.attach(newList);
9959 }
9960 else
9961 {
9962 /* we have no peer (our parent is the newly created machine);
9963 * just commit changes to devices */
9964 commitStorageControllers = true;
9965 }
9966 }
9967 else
9968 {
9969 /* the list of controllers itself is not changed,
9970 * just commit changes to controllers themselves */
9971 commitStorageControllers = true;
9972 }
9973
9974 if (commitStorageControllers)
9975 {
9976 StorageControllerList::const_iterator it = mStorageControllers->begin();
9977 while (it != mStorageControllers->end())
9978 {
9979 (*it)->commit();
9980 ++it;
9981 }
9982 }
9983
9984 if (isSessionMachine())
9985 {
9986 /* attach new data to the primary machine and reshare it */
9987 mPeer->mUserData.attach(mUserData);
9988 mPeer->mHWData.attach(mHWData);
9989 /* mMediaData is reshared by fixupMedia */
9990 // mPeer->mMediaData.attach(mMediaData);
9991 Assert(mPeer->mMediaData.data() == mMediaData.data());
9992 }
9993}
9994
9995/**
9996 * Copies all the hardware data from the given machine.
9997 *
9998 * Currently, only called when the VM is being restored from a snapshot. In
9999 * particular, this implies that the VM is not running during this method's
10000 * call.
10001 *
10002 * @note This method must be called from under this object's lock.
10003 *
10004 * @note This method doesn't call #commit(), so all data remains backed up and
10005 * unsaved.
10006 */
10007void Machine::copyFrom(Machine *aThat)
10008{
10009 AssertReturnVoid(!isSnapshotMachine());
10010 AssertReturnVoid(aThat->isSnapshotMachine());
10011
10012 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
10013
10014 mHWData.assignCopy(aThat->mHWData);
10015
10016 // create copies of all shared folders (mHWData after attaching a copy
10017 // contains just references to original objects)
10018 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10019 it != mHWData->mSharedFolders.end();
10020 ++it)
10021 {
10022 ComObjPtr<SharedFolder> folder;
10023 folder.createObject();
10024 HRESULT rc = folder->initCopy(getMachine(), *it);
10025 AssertComRC(rc);
10026 *it = folder;
10027 }
10028
10029 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
10030 mVRDEServer->copyFrom(aThat->mVRDEServer);
10031 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
10032 mUSBController->copyFrom(aThat->mUSBController);
10033 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10034
10035 /* create private copies of all controllers */
10036 mStorageControllers.backup();
10037 mStorageControllers->clear();
10038 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10039 it != aThat->mStorageControllers->end();
10040 ++it)
10041 {
10042 ComObjPtr<StorageController> ctrl;
10043 ctrl.createObject();
10044 ctrl->initCopy(this, *it);
10045 mStorageControllers->push_back(ctrl);
10046 }
10047
10048 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10049 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10050 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10051 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10052 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10053 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10054}
10055
10056#ifdef VBOX_WITH_RESOURCE_USAGE_API
10057
10058void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10059{
10060 AssertReturnVoid(isWriteLockOnCurrentThread());
10061 AssertPtrReturnVoid(aCollector);
10062
10063 pm::CollectorHAL *hal = aCollector->getHAL();
10064 /* Create sub metrics */
10065 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10066 "Percentage of processor time spent in user mode by the VM process.");
10067 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10068 "Percentage of processor time spent in kernel mode by the VM process.");
10069 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10070 "Size of resident portion of VM process in memory.");
10071 /* Create and register base metrics */
10072 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10073 cpuLoadUser, cpuLoadKernel);
10074 aCollector->registerBaseMetric(cpuLoad);
10075 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10076 ramUsageUsed);
10077 aCollector->registerBaseMetric(ramUsage);
10078
10079 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10080 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10081 new pm::AggregateAvg()));
10082 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10083 new pm::AggregateMin()));
10084 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10085 new pm::AggregateMax()));
10086 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10087 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10088 new pm::AggregateAvg()));
10089 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10090 new pm::AggregateMin()));
10091 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10092 new pm::AggregateMax()));
10093
10094 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10095 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10096 new pm::AggregateAvg()));
10097 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10098 new pm::AggregateMin()));
10099 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10100 new pm::AggregateMax()));
10101
10102
10103 /* Guest metrics collector */
10104 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10105 aCollector->registerGuest(mCollectorGuest);
10106 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10107 this, __PRETTY_FUNCTION__, mCollectorGuest));
10108
10109 /* Create sub metrics */
10110 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10111 "Percentage of processor time spent in user mode as seen by the guest.");
10112 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10113 "Percentage of processor time spent in kernel mode as seen by the guest.");
10114 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10115 "Percentage of processor time spent idling as seen by the guest.");
10116
10117 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10118 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10119 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10120 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10121 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10122 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10123
10124 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10125
10126 /* Create and register base metrics */
10127 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10128 guestLoadUser, guestLoadKernel, guestLoadIdle);
10129 aCollector->registerBaseMetric(guestCpuLoad);
10130
10131 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10132 guestMemTotal, guestMemFree,
10133 guestMemBalloon, guestMemShared,
10134 guestMemCache, guestPagedTotal);
10135 aCollector->registerBaseMetric(guestCpuMem);
10136
10137 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10138 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10139 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10140 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
10141
10142 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
10143 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
10144 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
10145 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
10146
10147 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
10148 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
10149 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
10150 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
10151
10152 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
10153 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
10154 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
10155 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
10156
10157 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
10158 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
10159 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
10160 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
10161
10162 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
10163 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
10164 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
10165 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
10166
10167 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
10168 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
10169 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
10170 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
10171
10172 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
10173 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
10174 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
10175 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
10176
10177 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
10178 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
10179 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
10180 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
10181}
10182
10183void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
10184{
10185 AssertReturnVoid(isWriteLockOnCurrentThread());
10186
10187 if (aCollector)
10188 {
10189 aCollector->unregisterMetricsFor(aMachine);
10190 aCollector->unregisterBaseMetricsFor(aMachine);
10191 }
10192}
10193
10194#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10195
10196
10197////////////////////////////////////////////////////////////////////////////////
10198
10199DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
10200
10201HRESULT SessionMachine::FinalConstruct()
10202{
10203 LogFlowThisFunc(("\n"));
10204
10205#if defined(RT_OS_WINDOWS)
10206 mIPCSem = NULL;
10207#elif defined(RT_OS_OS2)
10208 mIPCSem = NULLHANDLE;
10209#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10210 mIPCSem = -1;
10211#else
10212# error "Port me!"
10213#endif
10214
10215 return BaseFinalConstruct();
10216}
10217
10218void SessionMachine::FinalRelease()
10219{
10220 LogFlowThisFunc(("\n"));
10221
10222 uninit(Uninit::Unexpected);
10223
10224 BaseFinalRelease();
10225}
10226
10227/**
10228 * @note Must be called only by Machine::openSession() from its own write lock.
10229 */
10230HRESULT SessionMachine::init(Machine *aMachine)
10231{
10232 LogFlowThisFuncEnter();
10233 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10234
10235 AssertReturn(aMachine, E_INVALIDARG);
10236
10237 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10238
10239 /* Enclose the state transition NotReady->InInit->Ready */
10240 AutoInitSpan autoInitSpan(this);
10241 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10242
10243 /* create the interprocess semaphore */
10244#if defined(RT_OS_WINDOWS)
10245 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10246 for (size_t i = 0; i < mIPCSemName.length(); i++)
10247 if (mIPCSemName.raw()[i] == '\\')
10248 mIPCSemName.raw()[i] = '/';
10249 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10250 ComAssertMsgRet(mIPCSem,
10251 ("Cannot create IPC mutex '%ls', err=%d",
10252 mIPCSemName.raw(), ::GetLastError()),
10253 E_FAIL);
10254#elif defined(RT_OS_OS2)
10255 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10256 aMachine->mData->mUuid.raw());
10257 mIPCSemName = ipcSem;
10258 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10259 ComAssertMsgRet(arc == NO_ERROR,
10260 ("Cannot create IPC mutex '%s', arc=%ld",
10261 ipcSem.c_str(), arc),
10262 E_FAIL);
10263#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10264# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10265# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10266 /** @todo Check that this still works correctly. */
10267 AssertCompileSize(key_t, 8);
10268# else
10269 AssertCompileSize(key_t, 4);
10270# endif
10271 key_t key;
10272 mIPCSem = -1;
10273 mIPCKey = "0";
10274 for (uint32_t i = 0; i < 1 << 24; i++)
10275 {
10276 key = ((uint32_t)'V' << 24) | i;
10277 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10278 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10279 {
10280 mIPCSem = sem;
10281 if (sem >= 0)
10282 mIPCKey = BstrFmt("%u", key);
10283 break;
10284 }
10285 }
10286# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10287 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10288 char *pszSemName = NULL;
10289 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10290 key_t key = ::ftok(pszSemName, 'V');
10291 RTStrFree(pszSemName);
10292
10293 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10294# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10295
10296 int errnoSave = errno;
10297 if (mIPCSem < 0 && errnoSave == ENOSYS)
10298 {
10299 setError(E_FAIL,
10300 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10301 "support for SysV IPC. Check the host kernel configuration for "
10302 "CONFIG_SYSVIPC=y"));
10303 return E_FAIL;
10304 }
10305 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10306 * the IPC semaphores */
10307 if (mIPCSem < 0 && errnoSave == ENOSPC)
10308 {
10309#ifdef RT_OS_LINUX
10310 setError(E_FAIL,
10311 tr("Cannot create IPC semaphore because the system limit for the "
10312 "maximum number of semaphore sets (SEMMNI), or the system wide "
10313 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10314 "current set of SysV IPC semaphores can be determined from "
10315 "the file /proc/sysvipc/sem"));
10316#else
10317 setError(E_FAIL,
10318 tr("Cannot create IPC semaphore because the system-imposed limit "
10319 "on the maximum number of allowed semaphores or semaphore "
10320 "identifiers system-wide would be exceeded"));
10321#endif
10322 return E_FAIL;
10323 }
10324 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10325 E_FAIL);
10326 /* set the initial value to 1 */
10327 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10328 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10329 E_FAIL);
10330#else
10331# error "Port me!"
10332#endif
10333
10334 /* memorize the peer Machine */
10335 unconst(mPeer) = aMachine;
10336 /* share the parent pointer */
10337 unconst(mParent) = aMachine->mParent;
10338
10339 /* take the pointers to data to share */
10340 mData.share(aMachine->mData);
10341 mSSData.share(aMachine->mSSData);
10342
10343 mUserData.share(aMachine->mUserData);
10344 mHWData.share(aMachine->mHWData);
10345 mMediaData.share(aMachine->mMediaData);
10346
10347 mStorageControllers.allocate();
10348 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10349 it != aMachine->mStorageControllers->end();
10350 ++it)
10351 {
10352 ComObjPtr<StorageController> ctl;
10353 ctl.createObject();
10354 ctl->init(this, *it);
10355 mStorageControllers->push_back(ctl);
10356 }
10357
10358 unconst(mBIOSSettings).createObject();
10359 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10360 /* create another VRDEServer object that will be mutable */
10361 unconst(mVRDEServer).createObject();
10362 mVRDEServer->init(this, aMachine->mVRDEServer);
10363 /* create another audio adapter object that will be mutable */
10364 unconst(mAudioAdapter).createObject();
10365 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10366 /* create a list of serial ports that will be mutable */
10367 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10368 {
10369 unconst(mSerialPorts[slot]).createObject();
10370 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10371 }
10372 /* create a list of parallel ports that will be mutable */
10373 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10374 {
10375 unconst(mParallelPorts[slot]).createObject();
10376 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10377 }
10378 /* create another USB controller object that will be mutable */
10379 unconst(mUSBController).createObject();
10380 mUSBController->init(this, aMachine->mUSBController);
10381
10382 /* create a list of network adapters that will be mutable */
10383 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10384 {
10385 unconst(mNetworkAdapters[slot]).createObject();
10386 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10387 }
10388
10389 /* create another bandwidth control object that will be mutable */
10390 unconst(mBandwidthControl).createObject();
10391 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10392
10393 /* default is to delete saved state on Saved -> PoweredOff transition */
10394 mRemoveSavedState = true;
10395
10396 /* Confirm a successful initialization when it's the case */
10397 autoInitSpan.setSucceeded();
10398
10399 LogFlowThisFuncLeave();
10400 return S_OK;
10401}
10402
10403/**
10404 * Uninitializes this session object. If the reason is other than
10405 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10406 *
10407 * @param aReason uninitialization reason
10408 *
10409 * @note Locks mParent + this object for writing.
10410 */
10411void SessionMachine::uninit(Uninit::Reason aReason)
10412{
10413 LogFlowThisFuncEnter();
10414 LogFlowThisFunc(("reason=%d\n", aReason));
10415
10416 /*
10417 * Strongly reference ourselves to prevent this object deletion after
10418 * mData->mSession.mMachine.setNull() below (which can release the last
10419 * reference and call the destructor). Important: this must be done before
10420 * accessing any members (and before AutoUninitSpan that does it as well).
10421 * This self reference will be released as the very last step on return.
10422 */
10423 ComObjPtr<SessionMachine> selfRef = this;
10424
10425 /* Enclose the state transition Ready->InUninit->NotReady */
10426 AutoUninitSpan autoUninitSpan(this);
10427 if (autoUninitSpan.uninitDone())
10428 {
10429 LogFlowThisFunc(("Already uninitialized\n"));
10430 LogFlowThisFuncLeave();
10431 return;
10432 }
10433
10434 if (autoUninitSpan.initFailed())
10435 {
10436 /* We've been called by init() because it's failed. It's not really
10437 * necessary (nor it's safe) to perform the regular uninit sequence
10438 * below, the following is enough.
10439 */
10440 LogFlowThisFunc(("Initialization failed.\n"));
10441#if defined(RT_OS_WINDOWS)
10442 if (mIPCSem)
10443 ::CloseHandle(mIPCSem);
10444 mIPCSem = NULL;
10445#elif defined(RT_OS_OS2)
10446 if (mIPCSem != NULLHANDLE)
10447 ::DosCloseMutexSem(mIPCSem);
10448 mIPCSem = NULLHANDLE;
10449#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10450 if (mIPCSem >= 0)
10451 ::semctl(mIPCSem, 0, IPC_RMID);
10452 mIPCSem = -1;
10453# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10454 mIPCKey = "0";
10455# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10456#else
10457# error "Port me!"
10458#endif
10459 uninitDataAndChildObjects();
10460 mData.free();
10461 unconst(mParent) = NULL;
10462 unconst(mPeer) = NULL;
10463 LogFlowThisFuncLeave();
10464 return;
10465 }
10466
10467 MachineState_T lastState;
10468 {
10469 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10470 lastState = mData->mMachineState;
10471 }
10472 NOREF(lastState);
10473
10474#ifdef VBOX_WITH_USB
10475 // release all captured USB devices, but do this before requesting the locks below
10476 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10477 {
10478 /* Console::captureUSBDevices() is called in the VM process only after
10479 * setting the machine state to Starting or Restoring.
10480 * Console::detachAllUSBDevices() will be called upon successful
10481 * termination. So, we need to release USB devices only if there was
10482 * an abnormal termination of a running VM.
10483 *
10484 * This is identical to SessionMachine::DetachAllUSBDevices except
10485 * for the aAbnormal argument. */
10486 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10487 AssertComRC(rc);
10488 NOREF(rc);
10489
10490 USBProxyService *service = mParent->host()->usbProxyService();
10491 if (service)
10492 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10493 }
10494#endif /* VBOX_WITH_USB */
10495
10496 // we need to lock this object in uninit() because the lock is shared
10497 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10498 // and others need mParent lock, and USB needs host lock.
10499 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10500
10501 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10502 this, __PRETTY_FUNCTION__, mCollectorGuest));
10503 if (mCollectorGuest)
10504 {
10505 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
10506 delete mCollectorGuest;
10507 mCollectorGuest = NULL;
10508 }
10509 // Trigger async cleanup tasks, avoid doing things here which are not
10510 // vital to be done immediately and maybe need more locks. This calls
10511 // Machine::unregisterMetrics().
10512 mParent->onMachineUninit(mPeer);
10513
10514 if (aReason == Uninit::Abnormal)
10515 {
10516 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10517 Global::IsOnlineOrTransient(lastState)));
10518
10519 /* reset the state to Aborted */
10520 if (mData->mMachineState != MachineState_Aborted)
10521 setMachineState(MachineState_Aborted);
10522 }
10523
10524 // any machine settings modified?
10525 if (mData->flModifications)
10526 {
10527 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10528 rollback(false /* aNotify */);
10529 }
10530
10531 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
10532 || !mConsoleTaskData.mSnapshot);
10533 if (!mConsoleTaskData.strStateFilePath.isEmpty())
10534 {
10535 LogWarningThisFunc(("canceling failed save state request!\n"));
10536 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10537 }
10538 else if (!mConsoleTaskData.mSnapshot.isNull())
10539 {
10540 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10541
10542 /* delete all differencing hard disks created (this will also attach
10543 * their parents back by rolling back mMediaData) */
10544 rollbackMedia();
10545
10546 // delete the saved state file (it might have been already created)
10547 // AFTER killing the snapshot so that releaseSavedStateFile() won't
10548 // think it's still in use
10549 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
10550 mConsoleTaskData.mSnapshot->uninit();
10551 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
10552 }
10553
10554 if (!mData->mSession.mType.isEmpty())
10555 {
10556 /* mType is not null when this machine's process has been started by
10557 * Machine::launchVMProcess(), therefore it is our child. We
10558 * need to queue the PID to reap the process (and avoid zombies on
10559 * Linux). */
10560 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10561 mParent->addProcessToReap(mData->mSession.mPid);
10562 }
10563
10564 mData->mSession.mPid = NIL_RTPROCESS;
10565
10566 if (aReason == Uninit::Unexpected)
10567 {
10568 /* Uninitialization didn't come from #checkForDeath(), so tell the
10569 * client watcher thread to update the set of machines that have open
10570 * sessions. */
10571 mParent->updateClientWatcher();
10572 }
10573
10574 /* uninitialize all remote controls */
10575 if (mData->mSession.mRemoteControls.size())
10576 {
10577 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10578 mData->mSession.mRemoteControls.size()));
10579
10580 Data::Session::RemoteControlList::iterator it =
10581 mData->mSession.mRemoteControls.begin();
10582 while (it != mData->mSession.mRemoteControls.end())
10583 {
10584 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10585 HRESULT rc = (*it)->Uninitialize();
10586 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10587 if (FAILED(rc))
10588 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10589 ++it;
10590 }
10591 mData->mSession.mRemoteControls.clear();
10592 }
10593
10594 /*
10595 * An expected uninitialization can come only from #checkForDeath().
10596 * Otherwise it means that something's gone really wrong (for example,
10597 * the Session implementation has released the VirtualBox reference
10598 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10599 * etc). However, it's also possible, that the client releases the IPC
10600 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10601 * but the VirtualBox release event comes first to the server process.
10602 * This case is practically possible, so we should not assert on an
10603 * unexpected uninit, just log a warning.
10604 */
10605
10606 if ((aReason == Uninit::Unexpected))
10607 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10608
10609 if (aReason != Uninit::Normal)
10610 {
10611 mData->mSession.mDirectControl.setNull();
10612 }
10613 else
10614 {
10615 /* this must be null here (see #OnSessionEnd()) */
10616 Assert(mData->mSession.mDirectControl.isNull());
10617 Assert(mData->mSession.mState == SessionState_Unlocking);
10618 Assert(!mData->mSession.mProgress.isNull());
10619 }
10620 if (mData->mSession.mProgress)
10621 {
10622 if (aReason == Uninit::Normal)
10623 mData->mSession.mProgress->notifyComplete(S_OK);
10624 else
10625 mData->mSession.mProgress->notifyComplete(E_FAIL,
10626 COM_IIDOF(ISession),
10627 getComponentName(),
10628 tr("The VM session was aborted"));
10629 mData->mSession.mProgress.setNull();
10630 }
10631
10632 /* remove the association between the peer machine and this session machine */
10633 Assert( (SessionMachine*)mData->mSession.mMachine == this
10634 || aReason == Uninit::Unexpected);
10635
10636 /* reset the rest of session data */
10637 mData->mSession.mMachine.setNull();
10638 mData->mSession.mState = SessionState_Unlocked;
10639 mData->mSession.mType.setNull();
10640
10641 /* close the interprocess semaphore before leaving the exclusive lock */
10642#if defined(RT_OS_WINDOWS)
10643 if (mIPCSem)
10644 ::CloseHandle(mIPCSem);
10645 mIPCSem = NULL;
10646#elif defined(RT_OS_OS2)
10647 if (mIPCSem != NULLHANDLE)
10648 ::DosCloseMutexSem(mIPCSem);
10649 mIPCSem = NULLHANDLE;
10650#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10651 if (mIPCSem >= 0)
10652 ::semctl(mIPCSem, 0, IPC_RMID);
10653 mIPCSem = -1;
10654# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10655 mIPCKey = "0";
10656# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10657#else
10658# error "Port me!"
10659#endif
10660
10661 /* fire an event */
10662 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10663
10664 uninitDataAndChildObjects();
10665
10666 /* free the essential data structure last */
10667 mData.free();
10668
10669#if 1 /** @todo Please review this change! (bird) */
10670 /* drop the exclusive lock before setting the below two to NULL */
10671 multilock.release();
10672#else
10673 /* leave the exclusive lock before setting the below two to NULL */
10674 multilock.leave();
10675#endif
10676
10677 unconst(mParent) = NULL;
10678 unconst(mPeer) = NULL;
10679
10680 LogFlowThisFuncLeave();
10681}
10682
10683// util::Lockable interface
10684////////////////////////////////////////////////////////////////////////////////
10685
10686/**
10687 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10688 * with the primary Machine instance (mPeer).
10689 */
10690RWLockHandle *SessionMachine::lockHandle() const
10691{
10692 AssertReturn(mPeer != NULL, NULL);
10693 return mPeer->lockHandle();
10694}
10695
10696// IInternalMachineControl methods
10697////////////////////////////////////////////////////////////////////////////////
10698
10699/**
10700 * @note Locks this object for writing.
10701 */
10702STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10703{
10704 AutoCaller autoCaller(this);
10705 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10706
10707 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10708
10709 mRemoveSavedState = aRemove;
10710
10711 return S_OK;
10712}
10713
10714/**
10715 * @note Locks the same as #setMachineState() does.
10716 */
10717STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10718{
10719 return setMachineState(aMachineState);
10720}
10721
10722/**
10723 * @note Locks this object for reading.
10724 */
10725STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10726{
10727 AutoCaller autoCaller(this);
10728 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10729
10730 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10731
10732#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10733 mIPCSemName.cloneTo(aId);
10734 return S_OK;
10735#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10736# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10737 mIPCKey.cloneTo(aId);
10738# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10739 mData->m_strConfigFileFull.cloneTo(aId);
10740# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10741 return S_OK;
10742#else
10743# error "Port me!"
10744#endif
10745}
10746
10747/**
10748 * @note Locks this object for writing.
10749 */
10750STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10751{
10752 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10753 AutoCaller autoCaller(this);
10754 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10755
10756 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10757
10758 if (mData->mSession.mState != SessionState_Locked)
10759 return VBOX_E_INVALID_OBJECT_STATE;
10760
10761 if (!mData->mSession.mProgress.isNull())
10762 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10763
10764 LogFlowThisFunc(("returns S_OK.\n"));
10765 return S_OK;
10766}
10767
10768/**
10769 * @note Locks this object for writing.
10770 */
10771STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10772{
10773 AutoCaller autoCaller(this);
10774 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10775
10776 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10777
10778 if (mData->mSession.mState != SessionState_Locked)
10779 return VBOX_E_INVALID_OBJECT_STATE;
10780
10781 /* Finalize the openRemoteSession progress object. */
10782 if (mData->mSession.mProgress)
10783 {
10784 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10785 mData->mSession.mProgress.setNull();
10786 }
10787
10788 if (SUCCEEDED((HRESULT)iResult))
10789 {
10790#ifdef VBOX_WITH_RESOURCE_USAGE_API
10791 /* The VM has been powered up successfully, so it makes sense
10792 * now to offer the performance metrics for a running machine
10793 * object. Doing it earlier wouldn't be safe. */
10794 registerMetrics(mParent->performanceCollector(), mPeer,
10795 mData->mSession.mPid);
10796#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10797 }
10798
10799 return S_OK;
10800}
10801
10802/**
10803 * @note Locks this object for writing.
10804 */
10805STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
10806{
10807 LogFlowThisFuncEnter();
10808
10809 CheckComArgOutPointerValid(aProgress);
10810
10811 AutoCaller autoCaller(this);
10812 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10813
10814 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10815
10816 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
10817 E_FAIL);
10818
10819 /* create a progress object to track operation completion */
10820 ComObjPtr<Progress> pProgress;
10821 pProgress.createObject();
10822 pProgress->init(getVirtualBox(),
10823 static_cast<IMachine *>(this) /* aInitiator */,
10824 Bstr(tr("Stopping the virtual machine")).raw(),
10825 FALSE /* aCancelable */);
10826
10827 /* fill in the console task data */
10828 mConsoleTaskData.mLastState = mData->mMachineState;
10829 mConsoleTaskData.mProgress = pProgress;
10830
10831 /* set the state to Stopping (this is expected by Console::PowerDown()) */
10832 setMachineState(MachineState_Stopping);
10833
10834 pProgress.queryInterfaceTo(aProgress);
10835
10836 return S_OK;
10837}
10838
10839/**
10840 * @note Locks this object for writing.
10841 */
10842STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
10843{
10844 LogFlowThisFuncEnter();
10845
10846 AutoCaller autoCaller(this);
10847 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10848
10849 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10850
10851 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
10852 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
10853 && mConsoleTaskData.mLastState != MachineState_Null,
10854 E_FAIL);
10855
10856 /*
10857 * On failure, set the state to the state we had when BeginPoweringDown()
10858 * was called (this is expected by Console::PowerDown() and the associated
10859 * task). On success the VM process already changed the state to
10860 * MachineState_PoweredOff, so no need to do anything.
10861 */
10862 if (FAILED(iResult))
10863 setMachineState(mConsoleTaskData.mLastState);
10864
10865 /* notify the progress object about operation completion */
10866 Assert(mConsoleTaskData.mProgress);
10867 if (SUCCEEDED(iResult))
10868 mConsoleTaskData.mProgress->notifyComplete(S_OK);
10869 else
10870 {
10871 Utf8Str strErrMsg(aErrMsg);
10872 if (strErrMsg.length())
10873 mConsoleTaskData.mProgress->notifyComplete(iResult,
10874 COM_IIDOF(ISession),
10875 getComponentName(),
10876 strErrMsg.c_str());
10877 else
10878 mConsoleTaskData.mProgress->notifyComplete(iResult);
10879 }
10880
10881 /* clear out the temporary saved state data */
10882 mConsoleTaskData.mLastState = MachineState_Null;
10883 mConsoleTaskData.mProgress.setNull();
10884
10885 LogFlowThisFuncLeave();
10886 return S_OK;
10887}
10888
10889
10890/**
10891 * Goes through the USB filters of the given machine to see if the given
10892 * device matches any filter or not.
10893 *
10894 * @note Locks the same as USBController::hasMatchingFilter() does.
10895 */
10896STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10897 BOOL *aMatched,
10898 ULONG *aMaskedIfs)
10899{
10900 LogFlowThisFunc(("\n"));
10901
10902 CheckComArgNotNull(aUSBDevice);
10903 CheckComArgOutPointerValid(aMatched);
10904
10905 AutoCaller autoCaller(this);
10906 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10907
10908#ifdef VBOX_WITH_USB
10909 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10910#else
10911 NOREF(aUSBDevice);
10912 NOREF(aMaskedIfs);
10913 *aMatched = FALSE;
10914#endif
10915
10916 return S_OK;
10917}
10918
10919/**
10920 * @note Locks the same as Host::captureUSBDevice() does.
10921 */
10922STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10923{
10924 LogFlowThisFunc(("\n"));
10925
10926 AutoCaller autoCaller(this);
10927 AssertComRCReturnRC(autoCaller.rc());
10928
10929#ifdef VBOX_WITH_USB
10930 /* if captureDeviceForVM() fails, it must have set extended error info */
10931 clearError();
10932 MultiResult rc = mParent->host()->checkUSBProxyService();
10933 if (FAILED(rc)) return rc;
10934
10935 USBProxyService *service = mParent->host()->usbProxyService();
10936 AssertReturn(service, E_FAIL);
10937 return service->captureDeviceForVM(this, Guid(aId).ref());
10938#else
10939 NOREF(aId);
10940 return E_NOTIMPL;
10941#endif
10942}
10943
10944/**
10945 * @note Locks the same as Host::detachUSBDevice() does.
10946 */
10947STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10948{
10949 LogFlowThisFunc(("\n"));
10950
10951 AutoCaller autoCaller(this);
10952 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10953
10954#ifdef VBOX_WITH_USB
10955 USBProxyService *service = mParent->host()->usbProxyService();
10956 AssertReturn(service, E_FAIL);
10957 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10958#else
10959 NOREF(aId);
10960 NOREF(aDone);
10961 return E_NOTIMPL;
10962#endif
10963}
10964
10965/**
10966 * Inserts all machine filters to the USB proxy service and then calls
10967 * Host::autoCaptureUSBDevices().
10968 *
10969 * Called by Console from the VM process upon VM startup.
10970 *
10971 * @note Locks what called methods lock.
10972 */
10973STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10974{
10975 LogFlowThisFunc(("\n"));
10976
10977 AutoCaller autoCaller(this);
10978 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10979
10980#ifdef VBOX_WITH_USB
10981 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10982 AssertComRC(rc);
10983 NOREF(rc);
10984
10985 USBProxyService *service = mParent->host()->usbProxyService();
10986 AssertReturn(service, E_FAIL);
10987 return service->autoCaptureDevicesForVM(this);
10988#else
10989 return S_OK;
10990#endif
10991}
10992
10993/**
10994 * Removes all machine filters from the USB proxy service and then calls
10995 * Host::detachAllUSBDevices().
10996 *
10997 * Called by Console from the VM process upon normal VM termination or by
10998 * SessionMachine::uninit() upon abnormal VM termination (from under the
10999 * Machine/SessionMachine lock).
11000 *
11001 * @note Locks what called methods lock.
11002 */
11003STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
11004{
11005 LogFlowThisFunc(("\n"));
11006
11007 AutoCaller autoCaller(this);
11008 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11009
11010#ifdef VBOX_WITH_USB
11011 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11012 AssertComRC(rc);
11013 NOREF(rc);
11014
11015 USBProxyService *service = mParent->host()->usbProxyService();
11016 AssertReturn(service, E_FAIL);
11017 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
11018#else
11019 NOREF(aDone);
11020 return S_OK;
11021#endif
11022}
11023
11024/**
11025 * @note Locks this object for writing.
11026 */
11027STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
11028 IProgress **aProgress)
11029{
11030 LogFlowThisFuncEnter();
11031
11032 AssertReturn(aSession, E_INVALIDARG);
11033 AssertReturn(aProgress, E_INVALIDARG);
11034
11035 AutoCaller autoCaller(this);
11036
11037 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11038 /*
11039 * We don't assert below because it might happen that a non-direct session
11040 * informs us it is closed right after we've been uninitialized -- it's ok.
11041 */
11042 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11043
11044 /* get IInternalSessionControl interface */
11045 ComPtr<IInternalSessionControl> control(aSession);
11046
11047 ComAssertRet(!control.isNull(), E_INVALIDARG);
11048
11049 /* Creating a Progress object requires the VirtualBox lock, and
11050 * thus locking it here is required by the lock order rules. */
11051 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
11052
11053 if (control == mData->mSession.mDirectControl)
11054 {
11055 ComAssertRet(aProgress, E_POINTER);
11056
11057 /* The direct session is being normally closed by the client process
11058 * ----------------------------------------------------------------- */
11059
11060 /* go to the closing state (essential for all open*Session() calls and
11061 * for #checkForDeath()) */
11062 Assert(mData->mSession.mState == SessionState_Locked);
11063 mData->mSession.mState = SessionState_Unlocking;
11064
11065 /* set direct control to NULL to release the remote instance */
11066 mData->mSession.mDirectControl.setNull();
11067 LogFlowThisFunc(("Direct control is set to NULL\n"));
11068
11069 if (mData->mSession.mProgress)
11070 {
11071 /* finalize the progress, someone might wait if a frontend
11072 * closes the session before powering on the VM. */
11073 mData->mSession.mProgress->notifyComplete(E_FAIL,
11074 COM_IIDOF(ISession),
11075 getComponentName(),
11076 tr("The VM session was closed before any attempt to power it on"));
11077 mData->mSession.mProgress.setNull();
11078 }
11079
11080 /* Create the progress object the client will use to wait until
11081 * #checkForDeath() is called to uninitialize this session object after
11082 * it releases the IPC semaphore.
11083 * Note! Because we're "reusing" mProgress here, this must be a proxy
11084 * object just like for openRemoteSession. */
11085 Assert(mData->mSession.mProgress.isNull());
11086 ComObjPtr<ProgressProxy> progress;
11087 progress.createObject();
11088 ComPtr<IUnknown> pPeer(mPeer);
11089 progress->init(mParent, pPeer,
11090 Bstr(tr("Closing session")).raw(),
11091 FALSE /* aCancelable */);
11092 progress.queryInterfaceTo(aProgress);
11093 mData->mSession.mProgress = progress;
11094 }
11095 else
11096 {
11097 /* the remote session is being normally closed */
11098 Data::Session::RemoteControlList::iterator it =
11099 mData->mSession.mRemoteControls.begin();
11100 while (it != mData->mSession.mRemoteControls.end())
11101 {
11102 if (control == *it)
11103 break;
11104 ++it;
11105 }
11106 BOOL found = it != mData->mSession.mRemoteControls.end();
11107 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11108 E_INVALIDARG);
11109 mData->mSession.mRemoteControls.remove(*it);
11110 }
11111
11112 LogFlowThisFuncLeave();
11113 return S_OK;
11114}
11115
11116/**
11117 * @note Locks this object for writing.
11118 */
11119STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11120{
11121 LogFlowThisFuncEnter();
11122
11123 CheckComArgOutPointerValid(aProgress);
11124 CheckComArgOutPointerValid(aStateFilePath);
11125
11126 AutoCaller autoCaller(this);
11127 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11128
11129 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11130
11131 AssertReturn( mData->mMachineState == MachineState_Paused
11132 && mConsoleTaskData.mLastState == MachineState_Null
11133 && mConsoleTaskData.strStateFilePath.isEmpty(),
11134 E_FAIL);
11135
11136 /* create a progress object to track operation completion */
11137 ComObjPtr<Progress> pProgress;
11138 pProgress.createObject();
11139 pProgress->init(getVirtualBox(),
11140 static_cast<IMachine *>(this) /* aInitiator */,
11141 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
11142 FALSE /* aCancelable */);
11143
11144 Utf8Str strStateFilePath;
11145 /* stateFilePath is null when the machine is not running */
11146 if (mData->mMachineState == MachineState_Paused)
11147 composeSavedStateFilename(strStateFilePath);
11148
11149 /* fill in the console task data */
11150 mConsoleTaskData.mLastState = mData->mMachineState;
11151 mConsoleTaskData.strStateFilePath = strStateFilePath;
11152 mConsoleTaskData.mProgress = pProgress;
11153
11154 /* set the state to Saving (this is expected by Console::SaveState()) */
11155 setMachineState(MachineState_Saving);
11156
11157 strStateFilePath.cloneTo(aStateFilePath);
11158 pProgress.queryInterfaceTo(aProgress);
11159
11160 return S_OK;
11161}
11162
11163/**
11164 * @note Locks mParent + this object for writing.
11165 */
11166STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
11167{
11168 LogFlowThisFunc(("\n"));
11169
11170 AutoCaller autoCaller(this);
11171 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11172
11173 /* endSavingState() need mParent lock */
11174 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11175
11176 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
11177 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
11178 && mConsoleTaskData.mLastState != MachineState_Null
11179 && !mConsoleTaskData.strStateFilePath.isEmpty(),
11180 E_FAIL);
11181
11182 /*
11183 * On failure, set the state to the state we had when BeginSavingState()
11184 * was called (this is expected by Console::SaveState() and the associated
11185 * task). On success the VM process already changed the state to
11186 * MachineState_Saved, so no need to do anything.
11187 */
11188 if (FAILED(iResult))
11189 setMachineState(mConsoleTaskData.mLastState);
11190
11191 return endSavingState(iResult, aErrMsg);
11192}
11193
11194/**
11195 * @note Locks this object for writing.
11196 */
11197STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
11198{
11199 LogFlowThisFunc(("\n"));
11200
11201 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
11202
11203 AutoCaller autoCaller(this);
11204 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11205
11206 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11207
11208 AssertReturn( mData->mMachineState == MachineState_PoweredOff
11209 || mData->mMachineState == MachineState_Teleported
11210 || mData->mMachineState == MachineState_Aborted
11211 , E_FAIL); /** @todo setError. */
11212
11213 Utf8Str stateFilePathFull = aSavedStateFile;
11214 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
11215 if (RT_FAILURE(vrc))
11216 return setError(VBOX_E_FILE_ERROR,
11217 tr("Invalid saved state file path '%ls' (%Rrc)"),
11218 aSavedStateFile,
11219 vrc);
11220
11221 mSSData->strStateFilePath = stateFilePathFull;
11222
11223 /* The below setMachineState() will detect the state transition and will
11224 * update the settings file */
11225
11226 return setMachineState(MachineState_Saved);
11227}
11228
11229STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
11230 ComSafeArrayOut(BSTR, aValues),
11231 ComSafeArrayOut(LONG64, aTimestamps),
11232 ComSafeArrayOut(BSTR, aFlags))
11233{
11234 LogFlowThisFunc(("\n"));
11235
11236#ifdef VBOX_WITH_GUEST_PROPS
11237 using namespace guestProp;
11238
11239 AutoCaller autoCaller(this);
11240 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11241
11242 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11243
11244 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
11245 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
11246 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
11247 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
11248
11249 size_t cEntries = mHWData->mGuestProperties.size();
11250 com::SafeArray<BSTR> names(cEntries);
11251 com::SafeArray<BSTR> values(cEntries);
11252 com::SafeArray<LONG64> timestamps(cEntries);
11253 com::SafeArray<BSTR> flags(cEntries);
11254 unsigned i = 0;
11255 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
11256 it != mHWData->mGuestProperties.end();
11257 ++it)
11258 {
11259 char szFlags[MAX_FLAGS_LEN + 1];
11260 it->strName.cloneTo(&names[i]);
11261 it->strValue.cloneTo(&values[i]);
11262 timestamps[i] = it->mTimestamp;
11263 /* If it is NULL, keep it NULL. */
11264 if (it->mFlags)
11265 {
11266 writeFlags(it->mFlags, szFlags);
11267 Bstr(szFlags).cloneTo(&flags[i]);
11268 }
11269 else
11270 flags[i] = NULL;
11271 ++i;
11272 }
11273 names.detachTo(ComSafeArrayOutArg(aNames));
11274 values.detachTo(ComSafeArrayOutArg(aValues));
11275 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11276 flags.detachTo(ComSafeArrayOutArg(aFlags));
11277 return S_OK;
11278#else
11279 ReturnComNotImplemented();
11280#endif
11281}
11282
11283STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11284 IN_BSTR aValue,
11285 LONG64 aTimestamp,
11286 IN_BSTR aFlags)
11287{
11288 LogFlowThisFunc(("\n"));
11289
11290#ifdef VBOX_WITH_GUEST_PROPS
11291 using namespace guestProp;
11292
11293 CheckComArgStrNotEmptyOrNull(aName);
11294 CheckComArgMaybeNull(aValue);
11295 CheckComArgMaybeNull(aFlags);
11296
11297 try
11298 {
11299 /*
11300 * Convert input up front.
11301 */
11302 Utf8Str utf8Name(aName);
11303 uint32_t fFlags = NILFLAG;
11304 if (aFlags)
11305 {
11306 Utf8Str utf8Flags(aFlags);
11307 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11308 AssertRCReturn(vrc, E_INVALIDARG);
11309 }
11310
11311 /*
11312 * Now grab the object lock, validate the state and do the update.
11313 */
11314 AutoCaller autoCaller(this);
11315 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11316
11317 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11318
11319 switch (mData->mMachineState)
11320 {
11321 case MachineState_Paused:
11322 case MachineState_Running:
11323 case MachineState_Teleporting:
11324 case MachineState_TeleportingPausedVM:
11325 case MachineState_LiveSnapshotting:
11326 case MachineState_DeletingSnapshotOnline:
11327 case MachineState_DeletingSnapshotPaused:
11328 case MachineState_Saving:
11329 break;
11330
11331 default:
11332#ifndef DEBUG_sunlover
11333 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11334 VBOX_E_INVALID_VM_STATE);
11335#else
11336 return VBOX_E_INVALID_VM_STATE;
11337#endif
11338 }
11339
11340 setModified(IsModified_MachineData);
11341 mHWData.backup();
11342
11343 /** @todo r=bird: The careful memory handling doesn't work out here because
11344 * the catch block won't undo any damage we've done. So, if push_back throws
11345 * bad_alloc then you've lost the value.
11346 *
11347 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11348 * since values that changes actually bubbles to the end of the list. Using
11349 * something that has an efficient lookup and can tolerate a bit of updates
11350 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11351 * combination of RTStrCache (for sharing names and getting uniqueness into
11352 * the bargain) and hash/tree is another. */
11353 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11354 iter != mHWData->mGuestProperties.end();
11355 ++iter)
11356 if (utf8Name == iter->strName)
11357 {
11358 mHWData->mGuestProperties.erase(iter);
11359 mData->mGuestPropertiesModified = TRUE;
11360 break;
11361 }
11362 if (aValue != NULL)
11363 {
11364 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11365 mHWData->mGuestProperties.push_back(property);
11366 mData->mGuestPropertiesModified = TRUE;
11367 }
11368
11369 /*
11370 * Send a callback notification if appropriate
11371 */
11372 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11373 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11374 RTSTR_MAX,
11375 utf8Name.c_str(),
11376 RTSTR_MAX, NULL)
11377 )
11378 {
11379 alock.leave();
11380
11381 mParent->onGuestPropertyChange(mData->mUuid,
11382 aName,
11383 aValue,
11384 aFlags);
11385 }
11386 }
11387 catch (...)
11388 {
11389 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11390 }
11391 return S_OK;
11392#else
11393 ReturnComNotImplemented();
11394#endif
11395}
11396
11397// public methods only for internal purposes
11398/////////////////////////////////////////////////////////////////////////////
11399
11400/**
11401 * Called from the client watcher thread to check for expected or unexpected
11402 * death of the client process that has a direct session to this machine.
11403 *
11404 * On Win32 and on OS/2, this method is called only when we've got the
11405 * mutex (i.e. the client has either died or terminated normally) so it always
11406 * returns @c true (the client is terminated, the session machine is
11407 * uninitialized).
11408 *
11409 * On other platforms, the method returns @c true if the client process has
11410 * terminated normally or abnormally and the session machine was uninitialized,
11411 * and @c false if the client process is still alive.
11412 *
11413 * @note Locks this object for writing.
11414 */
11415bool SessionMachine::checkForDeath()
11416{
11417 Uninit::Reason reason;
11418 bool terminated = false;
11419
11420 /* Enclose autoCaller with a block because calling uninit() from under it
11421 * will deadlock. */
11422 {
11423 AutoCaller autoCaller(this);
11424 if (!autoCaller.isOk())
11425 {
11426 /* return true if not ready, to cause the client watcher to exclude
11427 * the corresponding session from watching */
11428 LogFlowThisFunc(("Already uninitialized!\n"));
11429 return true;
11430 }
11431
11432 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11433
11434 /* Determine the reason of death: if the session state is Closing here,
11435 * everything is fine. Otherwise it means that the client did not call
11436 * OnSessionEnd() before it released the IPC semaphore. This may happen
11437 * either because the client process has abnormally terminated, or
11438 * because it simply forgot to call ISession::Close() before exiting. We
11439 * threat the latter also as an abnormal termination (see
11440 * Session::uninit() for details). */
11441 reason = mData->mSession.mState == SessionState_Unlocking ?
11442 Uninit::Normal :
11443 Uninit::Abnormal;
11444
11445#if defined(RT_OS_WINDOWS)
11446
11447 AssertMsg(mIPCSem, ("semaphore must be created"));
11448
11449 /* release the IPC mutex */
11450 ::ReleaseMutex(mIPCSem);
11451
11452 terminated = true;
11453
11454#elif defined(RT_OS_OS2)
11455
11456 AssertMsg(mIPCSem, ("semaphore must be created"));
11457
11458 /* release the IPC mutex */
11459 ::DosReleaseMutexSem(mIPCSem);
11460
11461 terminated = true;
11462
11463#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11464
11465 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11466
11467 int val = ::semctl(mIPCSem, 0, GETVAL);
11468 if (val > 0)
11469 {
11470 /* the semaphore is signaled, meaning the session is terminated */
11471 terminated = true;
11472 }
11473
11474#else
11475# error "Port me!"
11476#endif
11477
11478 } /* AutoCaller block */
11479
11480 if (terminated)
11481 uninit(reason);
11482
11483 return terminated;
11484}
11485
11486/**
11487 * @note Locks this object for reading.
11488 */
11489HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11490{
11491 LogFlowThisFunc(("\n"));
11492
11493 AutoCaller autoCaller(this);
11494 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11495
11496 ComPtr<IInternalSessionControl> directControl;
11497 {
11498 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11499 directControl = mData->mSession.mDirectControl;
11500 }
11501
11502 /* ignore notifications sent after #OnSessionEnd() is called */
11503 if (!directControl)
11504 return S_OK;
11505
11506 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11507}
11508
11509/**
11510 * @note Locks this object for reading.
11511 */
11512HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11513 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
11514{
11515 LogFlowThisFunc(("\n"));
11516
11517 AutoCaller autoCaller(this);
11518 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11519
11520 ComPtr<IInternalSessionControl> directControl;
11521 {
11522 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11523 directControl = mData->mSession.mDirectControl;
11524 }
11525
11526 /* ignore notifications sent after #OnSessionEnd() is called */
11527 if (!directControl)
11528 return S_OK;
11529 /*
11530 * instead acting like callback we ask IVirtualBox deliver corresponding event
11531 */
11532
11533 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
11534 return S_OK;
11535}
11536
11537/**
11538 * @note Locks this object for reading.
11539 */
11540HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
11541{
11542 LogFlowThisFunc(("\n"));
11543
11544 AutoCaller autoCaller(this);
11545 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11546
11547 ComPtr<IInternalSessionControl> directControl;
11548 {
11549 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11550 directControl = mData->mSession.mDirectControl;
11551 }
11552
11553 /* ignore notifications sent after #OnSessionEnd() is called */
11554 if (!directControl)
11555 return S_OK;
11556
11557 return directControl->OnSerialPortChange(serialPort);
11558}
11559
11560/**
11561 * @note Locks this object for reading.
11562 */
11563HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
11564{
11565 LogFlowThisFunc(("\n"));
11566
11567 AutoCaller autoCaller(this);
11568 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11569
11570 ComPtr<IInternalSessionControl> directControl;
11571 {
11572 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11573 directControl = mData->mSession.mDirectControl;
11574 }
11575
11576 /* ignore notifications sent after #OnSessionEnd() is called */
11577 if (!directControl)
11578 return S_OK;
11579
11580 return directControl->OnParallelPortChange(parallelPort);
11581}
11582
11583/**
11584 * @note Locks this object for reading.
11585 */
11586HRESULT SessionMachine::onStorageControllerChange()
11587{
11588 LogFlowThisFunc(("\n"));
11589
11590 AutoCaller autoCaller(this);
11591 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11592
11593 ComPtr<IInternalSessionControl> directControl;
11594 {
11595 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11596 directControl = mData->mSession.mDirectControl;
11597 }
11598
11599 /* ignore notifications sent after #OnSessionEnd() is called */
11600 if (!directControl)
11601 return S_OK;
11602
11603 return directControl->OnStorageControllerChange();
11604}
11605
11606/**
11607 * @note Locks this object for reading.
11608 */
11609HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11610{
11611 LogFlowThisFunc(("\n"));
11612
11613 AutoCaller autoCaller(this);
11614 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11615
11616 ComPtr<IInternalSessionControl> directControl;
11617 {
11618 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11619 directControl = mData->mSession.mDirectControl;
11620 }
11621
11622 /* ignore notifications sent after #OnSessionEnd() is called */
11623 if (!directControl)
11624 return S_OK;
11625
11626 return directControl->OnMediumChange(aAttachment, aForce);
11627}
11628
11629/**
11630 * @note Locks this object for reading.
11631 */
11632HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11633{
11634 LogFlowThisFunc(("\n"));
11635
11636 AutoCaller autoCaller(this);
11637 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11638
11639 ComPtr<IInternalSessionControl> directControl;
11640 {
11641 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11642 directControl = mData->mSession.mDirectControl;
11643 }
11644
11645 /* ignore notifications sent after #OnSessionEnd() is called */
11646 if (!directControl)
11647 return S_OK;
11648
11649 return directControl->OnCPUChange(aCPU, aRemove);
11650}
11651
11652HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11653{
11654 LogFlowThisFunc(("\n"));
11655
11656 AutoCaller autoCaller(this);
11657 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11658
11659 ComPtr<IInternalSessionControl> directControl;
11660 {
11661 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11662 directControl = mData->mSession.mDirectControl;
11663 }
11664
11665 /* ignore notifications sent after #OnSessionEnd() is called */
11666 if (!directControl)
11667 return S_OK;
11668
11669 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11670}
11671
11672/**
11673 * @note Locks this object for reading.
11674 */
11675HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11676{
11677 LogFlowThisFunc(("\n"));
11678
11679 AutoCaller autoCaller(this);
11680 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11681
11682 ComPtr<IInternalSessionControl> directControl;
11683 {
11684 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11685 directControl = mData->mSession.mDirectControl;
11686 }
11687
11688 /* ignore notifications sent after #OnSessionEnd() is called */
11689 if (!directControl)
11690 return S_OK;
11691
11692 return directControl->OnVRDEServerChange(aRestart);
11693}
11694
11695/**
11696 * @note Locks this object for reading.
11697 */
11698HRESULT SessionMachine::onUSBControllerChange()
11699{
11700 LogFlowThisFunc(("\n"));
11701
11702 AutoCaller autoCaller(this);
11703 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11704
11705 ComPtr<IInternalSessionControl> directControl;
11706 {
11707 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11708 directControl = mData->mSession.mDirectControl;
11709 }
11710
11711 /* ignore notifications sent after #OnSessionEnd() is called */
11712 if (!directControl)
11713 return S_OK;
11714
11715 return directControl->OnUSBControllerChange();
11716}
11717
11718/**
11719 * @note Locks this object for reading.
11720 */
11721HRESULT SessionMachine::onSharedFolderChange()
11722{
11723 LogFlowThisFunc(("\n"));
11724
11725 AutoCaller autoCaller(this);
11726 AssertComRCReturnRC(autoCaller.rc());
11727
11728 ComPtr<IInternalSessionControl> directControl;
11729 {
11730 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11731 directControl = mData->mSession.mDirectControl;
11732 }
11733
11734 /* ignore notifications sent after #OnSessionEnd() is called */
11735 if (!directControl)
11736 return S_OK;
11737
11738 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11739}
11740
11741/**
11742 * @note Locks this object for reading.
11743 */
11744HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
11745{
11746 LogFlowThisFunc(("\n"));
11747
11748 AutoCaller autoCaller(this);
11749 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11750
11751 ComPtr<IInternalSessionControl> directControl;
11752 {
11753 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11754 directControl = mData->mSession.mDirectControl;
11755 }
11756
11757 /* ignore notifications sent after #OnSessionEnd() is called */
11758 if (!directControl)
11759 return S_OK;
11760
11761 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
11762}
11763
11764/**
11765 * Returns @c true if this machine's USB controller reports it has a matching
11766 * filter for the given USB device and @c false otherwise.
11767 *
11768 * @note Caller must have requested machine read lock.
11769 */
11770bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11771{
11772 AutoCaller autoCaller(this);
11773 /* silently return if not ready -- this method may be called after the
11774 * direct machine session has been called */
11775 if (!autoCaller.isOk())
11776 return false;
11777
11778
11779#ifdef VBOX_WITH_USB
11780 switch (mData->mMachineState)
11781 {
11782 case MachineState_Starting:
11783 case MachineState_Restoring:
11784 case MachineState_TeleportingIn:
11785 case MachineState_Paused:
11786 case MachineState_Running:
11787 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11788 * elsewhere... */
11789 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11790 default: break;
11791 }
11792#else
11793 NOREF(aDevice);
11794 NOREF(aMaskedIfs);
11795#endif
11796 return false;
11797}
11798
11799/**
11800 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11801 */
11802HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11803 IVirtualBoxErrorInfo *aError,
11804 ULONG aMaskedIfs)
11805{
11806 LogFlowThisFunc(("\n"));
11807
11808 AutoCaller autoCaller(this);
11809
11810 /* This notification may happen after the machine object has been
11811 * uninitialized (the session was closed), so don't assert. */
11812 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11813
11814 ComPtr<IInternalSessionControl> directControl;
11815 {
11816 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11817 directControl = mData->mSession.mDirectControl;
11818 }
11819
11820 /* fail on notifications sent after #OnSessionEnd() is called, it is
11821 * expected by the caller */
11822 if (!directControl)
11823 return E_FAIL;
11824
11825 /* No locks should be held at this point. */
11826 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11827 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11828
11829 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11830}
11831
11832/**
11833 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11834 */
11835HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11836 IVirtualBoxErrorInfo *aError)
11837{
11838 LogFlowThisFunc(("\n"));
11839
11840 AutoCaller autoCaller(this);
11841
11842 /* This notification may happen after the machine object has been
11843 * uninitialized (the session was closed), so don't assert. */
11844 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11845
11846 ComPtr<IInternalSessionControl> directControl;
11847 {
11848 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11849 directControl = mData->mSession.mDirectControl;
11850 }
11851
11852 /* fail on notifications sent after #OnSessionEnd() is called, it is
11853 * expected by the caller */
11854 if (!directControl)
11855 return E_FAIL;
11856
11857 /* No locks should be held at this point. */
11858 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11859 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11860
11861 return directControl->OnUSBDeviceDetach(aId, aError);
11862}
11863
11864// protected methods
11865/////////////////////////////////////////////////////////////////////////////
11866
11867/**
11868 * Helper method to finalize saving the state.
11869 *
11870 * @note Must be called from under this object's lock.
11871 *
11872 * @param aRc S_OK if the snapshot has been taken successfully
11873 * @param aErrMsg human readable error message for failure
11874 *
11875 * @note Locks mParent + this objects for writing.
11876 */
11877HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
11878{
11879 LogFlowThisFuncEnter();
11880
11881 AutoCaller autoCaller(this);
11882 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11883
11884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11885
11886 HRESULT rc = S_OK;
11887
11888 if (SUCCEEDED(aRc))
11889 {
11890 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
11891
11892 /* save all VM settings */
11893 rc = saveSettings(NULL);
11894 // no need to check whether VirtualBox.xml needs saving also since
11895 // we can't have a name change pending at this point
11896 }
11897 else
11898 {
11899 // delete the saved state file (it might have been already created);
11900 // we need not check whether this is shared with a snapshot here because
11901 // we certainly created this saved state file here anew
11902 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
11903 }
11904
11905 /* notify the progress object about operation completion */
11906 Assert(mConsoleTaskData.mProgress);
11907 if (SUCCEEDED(aRc))
11908 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11909 else
11910 {
11911 if (aErrMsg.length())
11912 mConsoleTaskData.mProgress->notifyComplete(aRc,
11913 COM_IIDOF(ISession),
11914 getComponentName(),
11915 aErrMsg.c_str());
11916 else
11917 mConsoleTaskData.mProgress->notifyComplete(aRc);
11918 }
11919
11920 /* clear out the temporary saved state data */
11921 mConsoleTaskData.mLastState = MachineState_Null;
11922 mConsoleTaskData.strStateFilePath.setNull();
11923 mConsoleTaskData.mProgress.setNull();
11924
11925 LogFlowThisFuncLeave();
11926 return rc;
11927}
11928
11929/**
11930 * Deletes the given file if it is no longer in use by either the current machine state
11931 * (if the machine is "saved") or any of the machine's snapshots.
11932 *
11933 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
11934 * but is different for each SnapshotMachine. When calling this, the order of calling this
11935 * function on the one hand and changing that variable OR the snapshots tree on the other hand
11936 * is therefore critical. I know, it's all rather messy.
11937 *
11938 * @param strStateFile
11939 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
11940 */
11941void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
11942 Snapshot *pSnapshotToIgnore)
11943{
11944 // it is safe to delete this saved state file if it is not currently in use by the machine ...
11945 if ( (strStateFile.isNotEmpty())
11946 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
11947 )
11948 // ... and it must also not be shared with other snapshots
11949 if ( !mData->mFirstSnapshot
11950 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
11951 // this checks the SnapshotMachine's state file paths
11952 )
11953 RTFileDelete(strStateFile.c_str());
11954}
11955
11956/**
11957 * Locks the attached media.
11958 *
11959 * All attached hard disks are locked for writing and DVD/floppy are locked for
11960 * reading. Parents of attached hard disks (if any) are locked for reading.
11961 *
11962 * This method also performs accessibility check of all media it locks: if some
11963 * media is inaccessible, the method will return a failure and a bunch of
11964 * extended error info objects per each inaccessible medium.
11965 *
11966 * Note that this method is atomic: if it returns a success, all media are
11967 * locked as described above; on failure no media is locked at all (all
11968 * succeeded individual locks will be undone).
11969 *
11970 * This method is intended to be called when the machine is in Starting or
11971 * Restoring state and asserts otherwise.
11972 *
11973 * The locks made by this method must be undone by calling #unlockMedia() when
11974 * no more needed.
11975 */
11976HRESULT SessionMachine::lockMedia()
11977{
11978 AutoCaller autoCaller(this);
11979 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11980
11981 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11982
11983 AssertReturn( mData->mMachineState == MachineState_Starting
11984 || mData->mMachineState == MachineState_Restoring
11985 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11986 /* bail out if trying to lock things with already set up locking */
11987 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11988
11989 clearError();
11990 MultiResult mrc(S_OK);
11991
11992 /* Collect locking information for all medium objects attached to the VM. */
11993 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11994 it != mMediaData->mAttachments.end();
11995 ++it)
11996 {
11997 MediumAttachment* pAtt = *it;
11998 DeviceType_T devType = pAtt->getType();
11999 Medium *pMedium = pAtt->getMedium();
12000
12001 MediumLockList *pMediumLockList(new MediumLockList());
12002 // There can be attachments without a medium (floppy/dvd), and thus
12003 // it's impossible to create a medium lock list. It still makes sense
12004 // to have the empty medium lock list in the map in case a medium is
12005 // attached later.
12006 if (pMedium != NULL)
12007 {
12008 MediumType_T mediumType = pMedium->getType();
12009 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
12010 || mediumType == MediumType_Shareable;
12011 bool fIsVitalImage = (devType == DeviceType_HardDisk);
12012
12013 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
12014 !fIsReadOnlyLock /* fMediumLockWrite */,
12015 NULL,
12016 *pMediumLockList);
12017 if (FAILED(mrc))
12018 {
12019 delete pMediumLockList;
12020 mData->mSession.mLockedMedia.Clear();
12021 break;
12022 }
12023 }
12024
12025 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
12026 if (FAILED(rc))
12027 {
12028 mData->mSession.mLockedMedia.Clear();
12029 mrc = setError(rc,
12030 tr("Collecting locking information for all attached media failed"));
12031 break;
12032 }
12033 }
12034
12035 if (SUCCEEDED(mrc))
12036 {
12037 /* Now lock all media. If this fails, nothing is locked. */
12038 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12039 if (FAILED(rc))
12040 {
12041 mrc = setError(rc,
12042 tr("Locking of attached media failed"));
12043 }
12044 }
12045
12046 return mrc;
12047}
12048
12049/**
12050 * Undoes the locks made by by #lockMedia().
12051 */
12052void SessionMachine::unlockMedia()
12053{
12054 AutoCaller autoCaller(this);
12055 AssertComRCReturnVoid(autoCaller.rc());
12056
12057 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12058
12059 /* we may be holding important error info on the current thread;
12060 * preserve it */
12061 ErrorInfoKeeper eik;
12062
12063 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12064 AssertComRC(rc);
12065}
12066
12067/**
12068 * Helper to change the machine state (reimplementation).
12069 *
12070 * @note Locks this object for writing.
12071 */
12072HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12073{
12074 LogFlowThisFuncEnter();
12075 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12076
12077 AutoCaller autoCaller(this);
12078 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12079
12080 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12081
12082 MachineState_T oldMachineState = mData->mMachineState;
12083
12084 AssertMsgReturn(oldMachineState != aMachineState,
12085 ("oldMachineState=%s, aMachineState=%s\n",
12086 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12087 E_FAIL);
12088
12089 HRESULT rc = S_OK;
12090
12091 int stsFlags = 0;
12092 bool deleteSavedState = false;
12093
12094 /* detect some state transitions */
12095
12096 if ( ( oldMachineState == MachineState_Saved
12097 && aMachineState == MachineState_Restoring)
12098 || ( ( oldMachineState == MachineState_PoweredOff
12099 || oldMachineState == MachineState_Teleported
12100 || oldMachineState == MachineState_Aborted
12101 )
12102 && ( aMachineState == MachineState_TeleportingIn
12103 || aMachineState == MachineState_Starting
12104 )
12105 )
12106 )
12107 {
12108 /* The EMT thread is about to start */
12109
12110 /* Nothing to do here for now... */
12111
12112 /// @todo NEWMEDIA don't let mDVDDrive and other children
12113 /// change anything when in the Starting/Restoring state
12114 }
12115 else if ( ( oldMachineState == MachineState_Running
12116 || oldMachineState == MachineState_Paused
12117 || oldMachineState == MachineState_Teleporting
12118 || oldMachineState == MachineState_LiveSnapshotting
12119 || oldMachineState == MachineState_Stuck
12120 || oldMachineState == MachineState_Starting
12121 || oldMachineState == MachineState_Stopping
12122 || oldMachineState == MachineState_Saving
12123 || oldMachineState == MachineState_Restoring
12124 || oldMachineState == MachineState_TeleportingPausedVM
12125 || oldMachineState == MachineState_TeleportingIn
12126 )
12127 && ( aMachineState == MachineState_PoweredOff
12128 || aMachineState == MachineState_Saved
12129 || aMachineState == MachineState_Teleported
12130 || aMachineState == MachineState_Aborted
12131 )
12132 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
12133 * snapshot */
12134 && ( mConsoleTaskData.mSnapshot.isNull()
12135 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
12136 )
12137 )
12138 {
12139 /* The EMT thread has just stopped, unlock attached media. Note that as
12140 * opposed to locking that is done from Console, we do unlocking here
12141 * because the VM process may have aborted before having a chance to
12142 * properly unlock all media it locked. */
12143
12144 unlockMedia();
12145 }
12146
12147 if (oldMachineState == MachineState_Restoring)
12148 {
12149 if (aMachineState != MachineState_Saved)
12150 {
12151 /*
12152 * delete the saved state file once the machine has finished
12153 * restoring from it (note that Console sets the state from
12154 * Restoring to Saved if the VM couldn't restore successfully,
12155 * to give the user an ability to fix an error and retry --
12156 * we keep the saved state file in this case)
12157 */
12158 deleteSavedState = true;
12159 }
12160 }
12161 else if ( oldMachineState == MachineState_Saved
12162 && ( aMachineState == MachineState_PoweredOff
12163 || aMachineState == MachineState_Aborted
12164 || aMachineState == MachineState_Teleported
12165 )
12166 )
12167 {
12168 /*
12169 * delete the saved state after Console::ForgetSavedState() is called
12170 * or if the VM process (owning a direct VM session) crashed while the
12171 * VM was Saved
12172 */
12173
12174 /// @todo (dmik)
12175 // Not sure that deleting the saved state file just because of the
12176 // client death before it attempted to restore the VM is a good
12177 // thing. But when it crashes we need to go to the Aborted state
12178 // which cannot have the saved state file associated... The only
12179 // way to fix this is to make the Aborted condition not a VM state
12180 // but a bool flag: i.e., when a crash occurs, set it to true and
12181 // change the state to PoweredOff or Saved depending on the
12182 // saved state presence.
12183
12184 deleteSavedState = true;
12185 mData->mCurrentStateModified = TRUE;
12186 stsFlags |= SaveSTS_CurStateModified;
12187 }
12188
12189 if ( aMachineState == MachineState_Starting
12190 || aMachineState == MachineState_Restoring
12191 || aMachineState == MachineState_TeleportingIn
12192 )
12193 {
12194 /* set the current state modified flag to indicate that the current
12195 * state is no more identical to the state in the
12196 * current snapshot */
12197 if (!mData->mCurrentSnapshot.isNull())
12198 {
12199 mData->mCurrentStateModified = TRUE;
12200 stsFlags |= SaveSTS_CurStateModified;
12201 }
12202 }
12203
12204 if (deleteSavedState)
12205 {
12206 if (mRemoveSavedState)
12207 {
12208 Assert(!mSSData->strStateFilePath.isEmpty());
12209
12210 // it is safe to delete the saved state file if ...
12211 if ( !mData->mFirstSnapshot // ... we have no snapshots or
12212 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
12213 // ... none of the snapshots share the saved state file
12214 )
12215 RTFileDelete(mSSData->strStateFilePath.c_str());
12216 }
12217
12218 mSSData->strStateFilePath.setNull();
12219 stsFlags |= SaveSTS_StateFilePath;
12220 }
12221
12222 /* redirect to the underlying peer machine */
12223 mPeer->setMachineState(aMachineState);
12224
12225 if ( aMachineState == MachineState_PoweredOff
12226 || aMachineState == MachineState_Teleported
12227 || aMachineState == MachineState_Aborted
12228 || aMachineState == MachineState_Saved)
12229 {
12230 /* the machine has stopped execution
12231 * (or the saved state file was adopted) */
12232 stsFlags |= SaveSTS_StateTimeStamp;
12233 }
12234
12235 if ( ( oldMachineState == MachineState_PoweredOff
12236 || oldMachineState == MachineState_Aborted
12237 || oldMachineState == MachineState_Teleported
12238 )
12239 && aMachineState == MachineState_Saved)
12240 {
12241 /* the saved state file was adopted */
12242 Assert(!mSSData->strStateFilePath.isEmpty());
12243 stsFlags |= SaveSTS_StateFilePath;
12244 }
12245
12246#ifdef VBOX_WITH_GUEST_PROPS
12247 if ( aMachineState == MachineState_PoweredOff
12248 || aMachineState == MachineState_Aborted
12249 || aMachineState == MachineState_Teleported)
12250 {
12251 /* Make sure any transient guest properties get removed from the
12252 * property store on shutdown. */
12253
12254 HWData::GuestPropertyList::iterator it;
12255 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
12256 if (!fNeedsSaving)
12257 for (it = mHWData->mGuestProperties.begin();
12258 it != mHWData->mGuestProperties.end(); ++it)
12259 if ( (it->mFlags & guestProp::TRANSIENT)
12260 || (it->mFlags & guestProp::TRANSRESET))
12261 {
12262 fNeedsSaving = true;
12263 break;
12264 }
12265 if (fNeedsSaving)
12266 {
12267 mData->mCurrentStateModified = TRUE;
12268 stsFlags |= SaveSTS_CurStateModified;
12269 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
12270 }
12271 }
12272#endif
12273
12274 rc = saveStateSettings(stsFlags);
12275
12276 if ( ( oldMachineState != MachineState_PoweredOff
12277 && oldMachineState != MachineState_Aborted
12278 && oldMachineState != MachineState_Teleported
12279 )
12280 && ( aMachineState == MachineState_PoweredOff
12281 || aMachineState == MachineState_Aborted
12282 || aMachineState == MachineState_Teleported
12283 )
12284 )
12285 {
12286 /* we've been shut down for any reason */
12287 /* no special action so far */
12288 }
12289
12290 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
12291 LogFlowThisFuncLeave();
12292 return rc;
12293}
12294
12295/**
12296 * Sends the current machine state value to the VM process.
12297 *
12298 * @note Locks this object for reading, then calls a client process.
12299 */
12300HRESULT SessionMachine::updateMachineStateOnClient()
12301{
12302 AutoCaller autoCaller(this);
12303 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12304
12305 ComPtr<IInternalSessionControl> directControl;
12306 {
12307 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12308 AssertReturn(!!mData, E_FAIL);
12309 directControl = mData->mSession.mDirectControl;
12310
12311 /* directControl may be already set to NULL here in #OnSessionEnd()
12312 * called too early by the direct session process while there is still
12313 * some operation (like deleting the snapshot) in progress. The client
12314 * process in this case is waiting inside Session::close() for the
12315 * "end session" process object to complete, while #uninit() called by
12316 * #checkForDeath() on the Watcher thread is waiting for the pending
12317 * operation to complete. For now, we accept this inconsistent behavior
12318 * and simply do nothing here. */
12319
12320 if (mData->mSession.mState == SessionState_Unlocking)
12321 return S_OK;
12322
12323 AssertReturn(!directControl.isNull(), E_FAIL);
12324 }
12325
12326 return directControl->UpdateMachineState(mData->mMachineState);
12327}
Note: See TracBrowser for help on using the repository browser.

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