VirtualBox

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

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

Main: do not return first item from list of registry IDs unconditionally since that list may be empty; this fixes the problem that media registry do not get saved properly if a new immutable image gets attached to a machine

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