VirtualBox

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

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

Main/Machine: first draft of method for cloning entire machines

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

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