VirtualBox

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

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

Main: use proper casting in Machine::Delete

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