VirtualBox

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

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

Main: convert SharedFolder to utf-8

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

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