VirtualBox

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

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

Main: check if particular PCI device already attached

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