VirtualBox

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

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

MachineImpl.cpp,VirtualBoxBase.h: Re r70709 - caller validated the setGuestPropertyToVM arguments already. Checking the caller I found a few VALID_PTR checks which didn't set error, added CheckComArgMaybeNull to hide deal with it.

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