VirtualBox

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

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

Main: Do not use colons in filenames(!), add nanosecond to saved state timestamp.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 407.6 KB
Line 
1/* $Id: MachineImpl.cpp 36163 2011-03-04 11:15:36Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/* Make sure all the stdint.h macros are included - must come first! */
19#ifndef __STDC_LIMIT_MACROS
20# define __STDC_LIMIT_MACROS
21#endif
22#ifndef __STDC_CONSTANT_MACROS
23# define __STDC_CONSTANT_MACROS
24#endif
25
26#ifdef VBOX_WITH_SYS_V_IPC_SESSION_WATCHER
27# include <errno.h>
28# include <sys/types.h>
29# include <sys/stat.h>
30# include <sys/ipc.h>
31# include <sys/sem.h>
32#endif
33
34#include "Logging.h"
35#include "VirtualBoxImpl.h"
36#include "MachineImpl.h"
37#include "ProgressImpl.h"
38#include "ProgressProxyImpl.h"
39#include "MediumAttachmentImpl.h"
40#include "MediumImpl.h"
41#include "MediumLock.h"
42#include "USBControllerImpl.h"
43#include "HostImpl.h"
44#include "SharedFolderImpl.h"
45#include "GuestOSTypeImpl.h"
46#include "VirtualBoxErrorInfoImpl.h"
47#include "GuestImpl.h"
48#include "StorageControllerImpl.h"
49#include "DisplayImpl.h"
50#include "DisplayUtils.h"
51#include "BandwidthControlImpl.h"
52
53// generated header
54#include "VBoxEvents.h"
55
56#ifdef VBOX_WITH_USB
57# include "USBProxyService.h"
58#endif
59
60#include "AutoCaller.h"
61#include "Performance.h"
62
63#include <iprt/asm.h>
64#include <iprt/path.h>
65#include <iprt/dir.h>
66#include <iprt/env.h>
67#include <iprt/lockvalidator.h>
68#include <iprt/process.h>
69#include <iprt/cpp/utils.h>
70#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
71#include <iprt/string.h>
72
73#include <VBox/com/array.h>
74
75#include <VBox/err.h>
76#include <VBox/param.h>
77#include <VBox/settings.h>
78#include <VBox/vmm/ssm.h>
79
80#ifdef VBOX_WITH_GUEST_PROPS
81# include <VBox/HostServices/GuestPropertySvc.h>
82# include <VBox/com/array.h>
83#endif
84
85#include "VBox/com/MultiResult.h"
86
87#include <algorithm>
88
89#include <typeinfo>
90
91#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
92# define HOSTSUFF_EXE ".exe"
93#else /* !RT_OS_WINDOWS */
94# define HOSTSUFF_EXE ""
95#endif /* !RT_OS_WINDOWS */
96
97// defines / prototypes
98/////////////////////////////////////////////////////////////////////////////
99
100/////////////////////////////////////////////////////////////////////////////
101// Machine::Data structure
102/////////////////////////////////////////////////////////////////////////////
103
104Machine::Data::Data()
105{
106 mRegistered = FALSE;
107 pMachineConfigFile = NULL;
108 flModifications = 0;
109 mAccessible = FALSE;
110 /* mUuid is initialized in Machine::init() */
111
112 mMachineState = MachineState_PoweredOff;
113 RTTimeNow(&mLastStateChange);
114
115 mMachineStateDeps = 0;
116 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
117 mMachineStateChangePending = 0;
118
119 mCurrentStateModified = TRUE;
120 mGuestPropertiesModified = FALSE;
121
122 mSession.mPid = NIL_RTPROCESS;
123 mSession.mState = SessionState_Unlocked;
124}
125
126Machine::Data::~Data()
127{
128 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
129 {
130 RTSemEventMultiDestroy(mMachineStateDepsSem);
131 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
132 }
133 if (pMachineConfigFile)
134 {
135 delete pMachineConfigFile;
136 pMachineConfigFile = NULL;
137 }
138}
139
140/////////////////////////////////////////////////////////////////////////////
141// Machine::HWData structure
142/////////////////////////////////////////////////////////////////////////////
143
144Machine::HWData::HWData()
145{
146 /* default values for a newly created machine */
147 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
148 mMemorySize = 128;
149 mCPUCount = 1;
150 mCPUHotPlugEnabled = false;
151 mMemoryBalloonSize = 0;
152 mPageFusionEnabled = false;
153 mVRAMSize = 8;
154 mAccelerate3DEnabled = false;
155 mAccelerate2DVideoEnabled = false;
156 mMonitorCount = 1;
157 mHWVirtExEnabled = true;
158 mHWVirtExNestedPagingEnabled = true;
159#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
160 mHWVirtExLargePagesEnabled = true;
161#else
162 /* Not supported on 32 bits hosts. */
163 mHWVirtExLargePagesEnabled = false;
164#endif
165 mHWVirtExVPIDEnabled = true;
166 mHWVirtExForceEnabled = false;
167#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
168 mHWVirtExExclusive = false;
169#else
170 mHWVirtExExclusive = true;
171#endif
172#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
173 mPAEEnabled = true;
174#else
175 mPAEEnabled = false;
176#endif
177 mSyntheticCpu = false;
178 mHpetEnabled = false;
179
180 /* default boot order: floppy - DVD - HDD */
181 mBootOrder[0] = DeviceType_Floppy;
182 mBootOrder[1] = DeviceType_DVD;
183 mBootOrder[2] = DeviceType_HardDisk;
184 for (size_t i = 3; i < RT_ELEMENTS(mBootOrder); ++i)
185 mBootOrder[i] = DeviceType_Null;
186
187 mClipboardMode = ClipboardMode_Bidirectional;
188 mGuestPropertyNotificationPatterns = "";
189
190 mFirmwareType = FirmwareType_BIOS;
191 mKeyboardHidType = KeyboardHidType_PS2Keyboard;
192 mPointingHidType = PointingHidType_PS2Mouse;
193 mChipsetType = ChipsetType_PIIX3;
194
195 for (size_t i = 0; i < RT_ELEMENTS(mCPUAttached); i++)
196 mCPUAttached[i] = false;
197
198 mIoCacheEnabled = true;
199 mIoCacheSize = 5; /* 5MB */
200
201 /* Maximum CPU execution cap by default. */
202 mCpuExecutionCap = 100;
203}
204
205Machine::HWData::~HWData()
206{
207}
208
209/////////////////////////////////////////////////////////////////////////////
210// Machine::HDData structure
211/////////////////////////////////////////////////////////////////////////////
212
213Machine::MediaData::MediaData()
214{
215}
216
217Machine::MediaData::~MediaData()
218{
219}
220
221/////////////////////////////////////////////////////////////////////////////
222// Machine class
223/////////////////////////////////////////////////////////////////////////////
224
225// constructor / destructor
226/////////////////////////////////////////////////////////////////////////////
227
228Machine::Machine()
229 : 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 ComPtr<IInternalSessionControl> directControl =
5000 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 rc = directControl->AccessGuestProperty
5008 (aName,
5009 /** @todo Fix when adding DeleteGuestProperty(),
5010 see defect. */
5011 *aValue ? aValue : NULL, aFlags, true /* isSetter */,
5012 &dummy, &dummy64, &dummy);
5013 }
5014 catch (std::bad_alloc &)
5015 {
5016 rc = E_OUTOFMEMORY;
5017 }
5018
5019 return rc;
5020}
5021#endif // VBOX_WITH_GUEST_PROPS
5022
5023STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
5024 IN_BSTR aFlags)
5025{
5026#ifndef VBOX_WITH_GUEST_PROPS
5027 ReturnComNotImplemented();
5028#else // VBOX_WITH_GUEST_PROPS
5029 CheckComArgStrNotEmptyOrNull(aName);
5030 if ((aFlags != NULL) && !VALID_PTR(aFlags))
5031 return E_INVALIDARG;
5032 AutoCaller autoCaller(this);
5033 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5034
5035 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
5036 if (rc == E_ACCESSDENIED)
5037 /* The VM is not running or the service is not (yet) accessible */
5038 rc = setGuestPropertyToService(aName, aValue, aFlags);
5039 return rc;
5040#endif // VBOX_WITH_GUEST_PROPS
5041}
5042
5043STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
5044{
5045 return SetGuestProperty(aName, aValue, NULL);
5046}
5047
5048#ifdef VBOX_WITH_GUEST_PROPS
5049/**
5050 * Enumerate the guest properties in VBoxSVC's internal structures.
5051 */
5052HRESULT Machine::enumerateGuestPropertiesInService
5053 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5054 ComSafeArrayOut(BSTR, aValues),
5055 ComSafeArrayOut(LONG64, aTimestamps),
5056 ComSafeArrayOut(BSTR, aFlags))
5057{
5058 using namespace guestProp;
5059
5060 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5061 Utf8Str strPatterns(aPatterns);
5062
5063 /*
5064 * Look for matching patterns and build up a list.
5065 */
5066 HWData::GuestPropertyList propList;
5067 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
5068 it != mHWData->mGuestProperties.end();
5069 ++it)
5070 if ( strPatterns.isEmpty()
5071 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5072 RTSTR_MAX,
5073 it->strName.c_str(),
5074 RTSTR_MAX,
5075 NULL)
5076 )
5077 propList.push_back(*it);
5078
5079 /*
5080 * And build up the arrays for returning the property information.
5081 */
5082 size_t cEntries = propList.size();
5083 SafeArray<BSTR> names(cEntries);
5084 SafeArray<BSTR> values(cEntries);
5085 SafeArray<LONG64> timestamps(cEntries);
5086 SafeArray<BSTR> flags(cEntries);
5087 size_t iProp = 0;
5088 for (HWData::GuestPropertyList::iterator it = propList.begin();
5089 it != propList.end();
5090 ++it)
5091 {
5092 char szFlags[MAX_FLAGS_LEN + 1];
5093 it->strName.cloneTo(&names[iProp]);
5094 it->strValue.cloneTo(&values[iProp]);
5095 timestamps[iProp] = it->mTimestamp;
5096 writeFlags(it->mFlags, szFlags);
5097 Bstr(szFlags).cloneTo(&flags[iProp]);
5098 ++iProp;
5099 }
5100 names.detachTo(ComSafeArrayOutArg(aNames));
5101 values.detachTo(ComSafeArrayOutArg(aValues));
5102 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
5103 flags.detachTo(ComSafeArrayOutArg(aFlags));
5104 return S_OK;
5105}
5106
5107/**
5108 * Enumerate the properties managed by a VM.
5109 * @returns E_ACCESSDENIED if the VM process is not available or not
5110 * currently handling queries and the setting should then be done in
5111 * VBoxSVC.
5112 */
5113HRESULT Machine::enumerateGuestPropertiesOnVM
5114 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5115 ComSafeArrayOut(BSTR, aValues),
5116 ComSafeArrayOut(LONG64, aTimestamps),
5117 ComSafeArrayOut(BSTR, aFlags))
5118{
5119 HRESULT rc;
5120 ComPtr<IInternalSessionControl> directControl;
5121 directControl = mData->mSession.mDirectControl;
5122
5123 if (!directControl)
5124 rc = E_ACCESSDENIED;
5125 else
5126 rc = directControl->EnumerateGuestProperties
5127 (aPatterns, ComSafeArrayOutArg(aNames),
5128 ComSafeArrayOutArg(aValues),
5129 ComSafeArrayOutArg(aTimestamps),
5130 ComSafeArrayOutArg(aFlags));
5131 return rc;
5132}
5133#endif // VBOX_WITH_GUEST_PROPS
5134
5135STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
5136 ComSafeArrayOut(BSTR, aNames),
5137 ComSafeArrayOut(BSTR, aValues),
5138 ComSafeArrayOut(LONG64, aTimestamps),
5139 ComSafeArrayOut(BSTR, aFlags))
5140{
5141#ifndef VBOX_WITH_GUEST_PROPS
5142 ReturnComNotImplemented();
5143#else // VBOX_WITH_GUEST_PROPS
5144 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
5145 return E_POINTER;
5146
5147 CheckComArgOutSafeArrayPointerValid(aNames);
5148 CheckComArgOutSafeArrayPointerValid(aValues);
5149 CheckComArgOutSafeArrayPointerValid(aTimestamps);
5150 CheckComArgOutSafeArrayPointerValid(aFlags);
5151
5152 AutoCaller autoCaller(this);
5153 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5154
5155 HRESULT rc = enumerateGuestPropertiesOnVM
5156 (aPatterns, ComSafeArrayOutArg(aNames),
5157 ComSafeArrayOutArg(aValues),
5158 ComSafeArrayOutArg(aTimestamps),
5159 ComSafeArrayOutArg(aFlags));
5160 if (rc == E_ACCESSDENIED)
5161 /* The VM is not running or the service is not (yet) accessible */
5162 rc = enumerateGuestPropertiesInService
5163 (aPatterns, ComSafeArrayOutArg(aNames),
5164 ComSafeArrayOutArg(aValues),
5165 ComSafeArrayOutArg(aTimestamps),
5166 ComSafeArrayOutArg(aFlags));
5167 return rc;
5168#endif // VBOX_WITH_GUEST_PROPS
5169}
5170
5171STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
5172 ComSafeArrayOut(IMediumAttachment*, aAttachments))
5173{
5174 MediaData::AttachmentList atts;
5175
5176 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
5177 if (FAILED(rc)) return rc;
5178
5179 SafeIfaceArray<IMediumAttachment> attachments(atts);
5180 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
5181
5182 return S_OK;
5183}
5184
5185STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
5186 LONG aControllerPort,
5187 LONG aDevice,
5188 IMediumAttachment **aAttachment)
5189{
5190 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
5191 aControllerName, aControllerPort, aDevice));
5192
5193 CheckComArgStrNotEmptyOrNull(aControllerName);
5194 CheckComArgOutPointerValid(aAttachment);
5195
5196 AutoCaller autoCaller(this);
5197 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5198
5199 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5200
5201 *aAttachment = NULL;
5202
5203 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
5204 aControllerName,
5205 aControllerPort,
5206 aDevice);
5207 if (pAttach.isNull())
5208 return setError(VBOX_E_OBJECT_NOT_FOUND,
5209 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
5210 aDevice, aControllerPort, aControllerName);
5211
5212 pAttach.queryInterfaceTo(aAttachment);
5213
5214 return S_OK;
5215}
5216
5217STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
5218 StorageBus_T aConnectionType,
5219 IStorageController **controller)
5220{
5221 CheckComArgStrNotEmptyOrNull(aName);
5222
5223 if ( (aConnectionType <= StorageBus_Null)
5224 || (aConnectionType > StorageBus_SAS))
5225 return setError(E_INVALIDARG,
5226 tr("Invalid connection type: %d"),
5227 aConnectionType);
5228
5229 AutoCaller autoCaller(this);
5230 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5231
5232 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5233
5234 HRESULT rc = checkStateDependency(MutableStateDep);
5235 if (FAILED(rc)) return rc;
5236
5237 /* try to find one with the name first. */
5238 ComObjPtr<StorageController> ctrl;
5239
5240 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
5241 if (SUCCEEDED(rc))
5242 return setError(VBOX_E_OBJECT_IN_USE,
5243 tr("Storage controller named '%ls' already exists"),
5244 aName);
5245
5246 ctrl.createObject();
5247
5248 /* get a new instance number for the storage controller */
5249 ULONG ulInstance = 0;
5250 bool fBootable = true;
5251 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5252 it != mStorageControllers->end();
5253 ++it)
5254 {
5255 if ((*it)->getStorageBus() == aConnectionType)
5256 {
5257 ULONG ulCurInst = (*it)->getInstance();
5258
5259 if (ulCurInst >= ulInstance)
5260 ulInstance = ulCurInst + 1;
5261
5262 /* Only one controller of each type can be marked as bootable. */
5263 if ((*it)->getBootable())
5264 fBootable = false;
5265 }
5266 }
5267
5268 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
5269 if (FAILED(rc)) return rc;
5270
5271 setModified(IsModified_Storage);
5272 mStorageControllers.backup();
5273 mStorageControllers->push_back(ctrl);
5274
5275 ctrl.queryInterfaceTo(controller);
5276
5277 /* inform the direct session if any */
5278 alock.leave();
5279 onStorageControllerChange();
5280
5281 return S_OK;
5282}
5283
5284STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
5285 IStorageController **aStorageController)
5286{
5287 CheckComArgStrNotEmptyOrNull(aName);
5288
5289 AutoCaller autoCaller(this);
5290 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5291
5292 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5293
5294 ComObjPtr<StorageController> ctrl;
5295
5296 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5297 if (SUCCEEDED(rc))
5298 ctrl.queryInterfaceTo(aStorageController);
5299
5300 return rc;
5301}
5302
5303STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
5304 IStorageController **aStorageController)
5305{
5306 AutoCaller autoCaller(this);
5307 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5308
5309 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5310
5311 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5312 it != mStorageControllers->end();
5313 ++it)
5314 {
5315 if ((*it)->getInstance() == aInstance)
5316 {
5317 (*it).queryInterfaceTo(aStorageController);
5318 return S_OK;
5319 }
5320 }
5321
5322 return setError(VBOX_E_OBJECT_NOT_FOUND,
5323 tr("Could not find a storage controller with instance number '%lu'"),
5324 aInstance);
5325}
5326
5327STDMETHODIMP Machine::SetStorageControllerBootable(IN_BSTR aName, BOOL fBootable)
5328{
5329 AutoCaller autoCaller(this);
5330 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5331
5332 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5333
5334 HRESULT rc = checkStateDependency(MutableStateDep);
5335 if (FAILED(rc)) return rc;
5336
5337 ComObjPtr<StorageController> ctrl;
5338
5339 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5340 if (SUCCEEDED(rc))
5341 {
5342 /* Ensure that only one controller of each type is marked as bootable. */
5343 if (fBootable == TRUE)
5344 {
5345 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5346 it != mStorageControllers->end();
5347 ++it)
5348 {
5349 ComObjPtr<StorageController> aCtrl = (*it);
5350
5351 if ( (aCtrl->getName() != Utf8Str(aName))
5352 && aCtrl->getBootable() == TRUE
5353 && aCtrl->getStorageBus() == ctrl->getStorageBus()
5354 && aCtrl->getControllerType() == ctrl->getControllerType())
5355 {
5356 aCtrl->setBootable(FALSE);
5357 break;
5358 }
5359 }
5360 }
5361
5362 if (SUCCEEDED(rc))
5363 {
5364 ctrl->setBootable(fBootable);
5365 setModified(IsModified_Storage);
5366 }
5367 }
5368
5369 if (SUCCEEDED(rc))
5370 {
5371 /* inform the direct session if any */
5372 alock.leave();
5373 onStorageControllerChange();
5374 }
5375
5376 return rc;
5377}
5378
5379STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5380{
5381 CheckComArgStrNotEmptyOrNull(aName);
5382
5383 AutoCaller autoCaller(this);
5384 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5385
5386 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5387
5388 HRESULT rc = checkStateDependency(MutableStateDep);
5389 if (FAILED(rc)) return rc;
5390
5391 ComObjPtr<StorageController> ctrl;
5392 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5393 if (FAILED(rc)) return rc;
5394
5395 /* We can remove the controller only if there is no device attached. */
5396 /* check if the device slot is already busy */
5397 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5398 it != mMediaData->mAttachments.end();
5399 ++it)
5400 {
5401 if ((*it)->getControllerName() == aName)
5402 return setError(VBOX_E_OBJECT_IN_USE,
5403 tr("Storage controller named '%ls' has still devices attached"),
5404 aName);
5405 }
5406
5407 /* We can remove it now. */
5408 setModified(IsModified_Storage);
5409 mStorageControllers.backup();
5410
5411 ctrl->unshare();
5412
5413 mStorageControllers->remove(ctrl);
5414
5415 /* inform the direct session if any */
5416 alock.leave();
5417 onStorageControllerChange();
5418
5419 return S_OK;
5420}
5421
5422STDMETHODIMP Machine::QuerySavedGuestSize(ULONG uScreenId, ULONG *puWidth, ULONG *puHeight)
5423{
5424 LogFlowThisFunc(("\n"));
5425
5426 CheckComArgNotNull(puWidth);
5427 CheckComArgNotNull(puHeight);
5428
5429 uint32_t u32Width = 0;
5430 uint32_t u32Height = 0;
5431
5432 int vrc = readSavedGuestSize(mSSData->strStateFilePath, uScreenId, &u32Width, &u32Height);
5433 if (RT_FAILURE(vrc))
5434 return setError(VBOX_E_IPRT_ERROR,
5435 tr("Saved guest size is not available (%Rrc)"),
5436 vrc);
5437
5438 *puWidth = u32Width;
5439 *puHeight = u32Height;
5440
5441 return S_OK;
5442}
5443
5444STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5445{
5446 LogFlowThisFunc(("\n"));
5447
5448 CheckComArgNotNull(aSize);
5449 CheckComArgNotNull(aWidth);
5450 CheckComArgNotNull(aHeight);
5451
5452 if (aScreenId != 0)
5453 return E_NOTIMPL;
5454
5455 AutoCaller autoCaller(this);
5456 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5457
5458 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5459
5460 uint8_t *pu8Data = NULL;
5461 uint32_t cbData = 0;
5462 uint32_t u32Width = 0;
5463 uint32_t u32Height = 0;
5464
5465 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5466
5467 if (RT_FAILURE(vrc))
5468 return setError(VBOX_E_IPRT_ERROR,
5469 tr("Saved screenshot data is not available (%Rrc)"),
5470 vrc);
5471
5472 *aSize = cbData;
5473 *aWidth = u32Width;
5474 *aHeight = u32Height;
5475
5476 freeSavedDisplayScreenshot(pu8Data);
5477
5478 return S_OK;
5479}
5480
5481STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5482{
5483 LogFlowThisFunc(("\n"));
5484
5485 CheckComArgNotNull(aWidth);
5486 CheckComArgNotNull(aHeight);
5487 CheckComArgOutSafeArrayPointerValid(aData);
5488
5489 if (aScreenId != 0)
5490 return E_NOTIMPL;
5491
5492 AutoCaller autoCaller(this);
5493 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5494
5495 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5496
5497 uint8_t *pu8Data = NULL;
5498 uint32_t cbData = 0;
5499 uint32_t u32Width = 0;
5500 uint32_t u32Height = 0;
5501
5502 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5503
5504 if (RT_FAILURE(vrc))
5505 return setError(VBOX_E_IPRT_ERROR,
5506 tr("Saved screenshot data is not available (%Rrc)"),
5507 vrc);
5508
5509 *aWidth = u32Width;
5510 *aHeight = u32Height;
5511
5512 com::SafeArray<BYTE> bitmap(cbData);
5513 /* Convert pixels to format expected by the API caller. */
5514 if (aBGR)
5515 {
5516 /* [0] B, [1] G, [2] R, [3] A. */
5517 for (unsigned i = 0; i < cbData; i += 4)
5518 {
5519 bitmap[i] = pu8Data[i];
5520 bitmap[i + 1] = pu8Data[i + 1];
5521 bitmap[i + 2] = pu8Data[i + 2];
5522 bitmap[i + 3] = 0xff;
5523 }
5524 }
5525 else
5526 {
5527 /* [0] R, [1] G, [2] B, [3] A. */
5528 for (unsigned i = 0; i < cbData; i += 4)
5529 {
5530 bitmap[i] = pu8Data[i + 2];
5531 bitmap[i + 1] = pu8Data[i + 1];
5532 bitmap[i + 2] = pu8Data[i];
5533 bitmap[i + 3] = 0xff;
5534 }
5535 }
5536 bitmap.detachTo(ComSafeArrayOutArg(aData));
5537
5538 freeSavedDisplayScreenshot(pu8Data);
5539
5540 return S_OK;
5541}
5542
5543
5544STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5545{
5546 LogFlowThisFunc(("\n"));
5547
5548 CheckComArgNotNull(aWidth);
5549 CheckComArgNotNull(aHeight);
5550 CheckComArgOutSafeArrayPointerValid(aData);
5551
5552 if (aScreenId != 0)
5553 return E_NOTIMPL;
5554
5555 AutoCaller autoCaller(this);
5556 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5557
5558 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5559
5560 uint8_t *pu8Data = NULL;
5561 uint32_t cbData = 0;
5562 uint32_t u32Width = 0;
5563 uint32_t u32Height = 0;
5564
5565 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5566
5567 if (RT_FAILURE(vrc))
5568 return setError(VBOX_E_IPRT_ERROR,
5569 tr("Saved screenshot data is not available (%Rrc)"),
5570 vrc);
5571
5572 *aWidth = u32Width;
5573 *aHeight = u32Height;
5574
5575 uint8_t *pu8PNG = NULL;
5576 uint32_t cbPNG = 0;
5577 uint32_t cxPNG = 0;
5578 uint32_t cyPNG = 0;
5579
5580 DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
5581
5582 com::SafeArray<BYTE> screenData(cbPNG);
5583 screenData.initFrom(pu8PNG, cbPNG);
5584 RTMemFree(pu8PNG);
5585
5586 screenData.detachTo(ComSafeArrayOutArg(aData));
5587
5588 freeSavedDisplayScreenshot(pu8Data);
5589
5590 return S_OK;
5591}
5592
5593STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5594{
5595 LogFlowThisFunc(("\n"));
5596
5597 CheckComArgNotNull(aSize);
5598 CheckComArgNotNull(aWidth);
5599 CheckComArgNotNull(aHeight);
5600
5601 if (aScreenId != 0)
5602 return E_NOTIMPL;
5603
5604 AutoCaller autoCaller(this);
5605 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5606
5607 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5608
5609 uint8_t *pu8Data = NULL;
5610 uint32_t cbData = 0;
5611 uint32_t u32Width = 0;
5612 uint32_t u32Height = 0;
5613
5614 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5615
5616 if (RT_FAILURE(vrc))
5617 return setError(VBOX_E_IPRT_ERROR,
5618 tr("Saved screenshot data is not available (%Rrc)"),
5619 vrc);
5620
5621 *aSize = cbData;
5622 *aWidth = u32Width;
5623 *aHeight = u32Height;
5624
5625 freeSavedDisplayScreenshot(pu8Data);
5626
5627 return S_OK;
5628}
5629
5630STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5631{
5632 LogFlowThisFunc(("\n"));
5633
5634 CheckComArgNotNull(aWidth);
5635 CheckComArgNotNull(aHeight);
5636 CheckComArgOutSafeArrayPointerValid(aData);
5637
5638 if (aScreenId != 0)
5639 return E_NOTIMPL;
5640
5641 AutoCaller autoCaller(this);
5642 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5643
5644 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5645
5646 uint8_t *pu8Data = NULL;
5647 uint32_t cbData = 0;
5648 uint32_t u32Width = 0;
5649 uint32_t u32Height = 0;
5650
5651 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5652
5653 if (RT_FAILURE(vrc))
5654 return setError(VBOX_E_IPRT_ERROR,
5655 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
5656 vrc);
5657
5658 *aWidth = u32Width;
5659 *aHeight = u32Height;
5660
5661 com::SafeArray<BYTE> png(cbData);
5662 png.initFrom(pu8Data, cbData);
5663 png.detachTo(ComSafeArrayOutArg(aData));
5664
5665 freeSavedDisplayScreenshot(pu8Data);
5666
5667 return S_OK;
5668}
5669
5670STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5671{
5672 HRESULT rc = S_OK;
5673 LogFlowThisFunc(("\n"));
5674
5675 AutoCaller autoCaller(this);
5676 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5677
5678 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5679
5680 if (!mHWData->mCPUHotPlugEnabled)
5681 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5682
5683 if (aCpu >= mHWData->mCPUCount)
5684 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5685
5686 if (mHWData->mCPUAttached[aCpu])
5687 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5688
5689 alock.release();
5690 rc = onCPUChange(aCpu, false);
5691 alock.acquire();
5692 if (FAILED(rc)) return rc;
5693
5694 setModified(IsModified_MachineData);
5695 mHWData.backup();
5696 mHWData->mCPUAttached[aCpu] = true;
5697
5698 /* Save settings if online */
5699 if (Global::IsOnline(mData->mMachineState))
5700 saveSettings(NULL);
5701
5702 return S_OK;
5703}
5704
5705STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5706{
5707 HRESULT rc = S_OK;
5708 LogFlowThisFunc(("\n"));
5709
5710 AutoCaller autoCaller(this);
5711 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5712
5713 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5714
5715 if (!mHWData->mCPUHotPlugEnabled)
5716 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5717
5718 if (aCpu >= SchemaDefs::MaxCPUCount)
5719 return setError(E_INVALIDARG,
5720 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5721 SchemaDefs::MaxCPUCount);
5722
5723 if (!mHWData->mCPUAttached[aCpu])
5724 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5725
5726 /* CPU 0 can't be detached */
5727 if (aCpu == 0)
5728 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5729
5730 alock.release();
5731 rc = onCPUChange(aCpu, true);
5732 alock.acquire();
5733 if (FAILED(rc)) return rc;
5734
5735 setModified(IsModified_MachineData);
5736 mHWData.backup();
5737 mHWData->mCPUAttached[aCpu] = false;
5738
5739 /* Save settings if online */
5740 if (Global::IsOnline(mData->mMachineState))
5741 saveSettings(NULL);
5742
5743 return S_OK;
5744}
5745
5746STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5747{
5748 LogFlowThisFunc(("\n"));
5749
5750 CheckComArgNotNull(aCpuAttached);
5751
5752 *aCpuAttached = false;
5753
5754 AutoCaller autoCaller(this);
5755 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5756
5757 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5758
5759 /* If hotplug is enabled the CPU is always enabled. */
5760 if (!mHWData->mCPUHotPlugEnabled)
5761 {
5762 if (aCpu < mHWData->mCPUCount)
5763 *aCpuAttached = true;
5764 }
5765 else
5766 {
5767 if (aCpu < SchemaDefs::MaxCPUCount)
5768 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5769 }
5770
5771 return S_OK;
5772}
5773
5774STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5775{
5776 CheckComArgOutPointerValid(aName);
5777
5778 AutoCaller autoCaller(this);
5779 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5780
5781 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5782
5783 Utf8Str log = queryLogFilename(aIdx);
5784 if (!RTFileExists(log.c_str()))
5785 log.setNull();
5786 log.cloneTo(aName);
5787
5788 return S_OK;
5789}
5790
5791STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
5792{
5793 LogFlowThisFunc(("\n"));
5794 CheckComArgOutSafeArrayPointerValid(aData);
5795 if (aSize < 0)
5796 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
5797
5798 AutoCaller autoCaller(this);
5799 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5800
5801 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5802
5803 HRESULT rc = S_OK;
5804 Utf8Str log = queryLogFilename(aIdx);
5805
5806 /* do not unnecessarily hold the lock while doing something which does
5807 * not need the lock and potentially takes a long time. */
5808 alock.release();
5809
5810 /* Limit the chunk size to 32K for now, as that gives better performance
5811 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5812 * One byte expands to approx. 25 bytes of breathtaking XML. */
5813 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5814 com::SafeArray<BYTE> logData(cbData);
5815
5816 RTFILE LogFile;
5817 int vrc = RTFileOpen(&LogFile, log.c_str(),
5818 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5819 if (RT_SUCCESS(vrc))
5820 {
5821 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5822 if (RT_SUCCESS(vrc))
5823 logData.resize(cbData);
5824 else
5825 rc = setError(VBOX_E_IPRT_ERROR,
5826 tr("Could not read log file '%s' (%Rrc)"),
5827 log.c_str(), vrc);
5828 RTFileClose(LogFile);
5829 }
5830 else
5831 rc = setError(VBOX_E_IPRT_ERROR,
5832 tr("Could not open log file '%s' (%Rrc)"),
5833 log.c_str(), vrc);
5834
5835 if (FAILED(rc))
5836 logData.resize(0);
5837 logData.detachTo(ComSafeArrayOutArg(aData));
5838
5839 return rc;
5840}
5841
5842
5843/**
5844 * Currently this method doesn't attach device to the running VM,
5845 * just makes sure it's plugged on next VM start.
5846 */
5847STDMETHODIMP Machine::AttachHostPciDevice(LONG hostAddress, LONG desiredGuestAddress, BOOL /*tryToUnbind*/)
5848{
5849 AutoCaller autoCaller(this);
5850 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5851
5852 // lock scope
5853 {
5854 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5855
5856 HRESULT rc = checkStateDependency(MutableStateDep);
5857 if (FAILED(rc)) return rc;
5858
5859 ChipsetType_T aChipset = ChipsetType_PIIX3;
5860 COMGETTER(ChipsetType)(&aChipset);
5861
5862 if (aChipset != ChipsetType_ICH9)
5863 {
5864 return setError(E_INVALIDARG,
5865 tr("Host PCI attachment only supported with ICH9 chipset"));
5866 }
5867
5868 ComObjPtr<PciDeviceAttachment> pda;
5869 char name[32];
5870
5871 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (hostAddress>>8) & 0xff, (hostAddress & 0xf8) >> 3, hostAddress & 7);
5872 Bstr bname(name);
5873 pda.createObject();
5874 pda->init(this, bname, hostAddress, desiredGuestAddress, TRUE);
5875 setModified(IsModified_MachineData);
5876 mHWData.backup();
5877 mHWData->mPciDeviceAssignments.push_back(pda);
5878 }
5879
5880 return S_OK;
5881}
5882
5883/**
5884 * Currently this method doesn't detach device from the running VM,
5885 * just makes sure it's not plugged on next VM start.
5886 */
5887STDMETHODIMP Machine::DetachHostPciDevice(LONG hostAddress)
5888{
5889 AutoCaller autoCaller(this);
5890 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5891
5892 ComObjPtr<PciDeviceAttachment> pAttach;
5893 bool fRemoved = false;
5894 HRESULT rc;
5895
5896 // lock scope
5897 {
5898 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5899
5900 rc = checkStateDependency(MutableStateDep);
5901 if (FAILED(rc)) return rc;
5902
5903 for (HWData::PciDeviceAssignmentList::iterator it = mHWData->mPciDeviceAssignments.begin();
5904 it != mHWData->mPciDeviceAssignments.end();
5905 ++it)
5906 {
5907 LONG iHostAddress = -1;
5908 pAttach = *it;
5909 pAttach->COMGETTER(HostAddress)(&iHostAddress);
5910 if (iHostAddress != -1 && iHostAddress == hostAddress)
5911 {
5912 setModified(IsModified_MachineData);
5913 mHWData.backup();
5914 mHWData->mPciDeviceAssignments.remove(pAttach);
5915 fRemoved = true;
5916 break;
5917 }
5918 }
5919 }
5920
5921
5922 /* Fire event outside of the lock */
5923 if (fRemoved)
5924 {
5925 Assert(!pAttach.isNull());
5926 ComPtr<IEventSource> es;
5927 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
5928 Assert(SUCCEEDED(rc));
5929 Bstr mid;
5930 rc = this->COMGETTER(Id)(mid.asOutParam());
5931 Assert(SUCCEEDED(rc));
5932 fireHostPciDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
5933 }
5934
5935 return S_OK;
5936}
5937
5938STDMETHODIMP Machine::COMGETTER(PciDeviceAssignments)(ComSafeArrayOut(IPciDeviceAttachment *, aAssignments))
5939{
5940 CheckComArgOutSafeArrayPointerValid(aAssignments);
5941
5942 AutoCaller autoCaller(this);
5943 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5944
5945 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5946
5947 SafeIfaceArray<IPciDeviceAttachment> assignments(mHWData->mPciDeviceAssignments);
5948 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
5949
5950 return S_OK;
5951}
5952
5953STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
5954{
5955 CheckComArgOutPointerValid(aBandwidthControl);
5956
5957 AutoCaller autoCaller(this);
5958 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5959
5960 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
5961
5962 return S_OK;
5963}
5964
5965// public methods for internal purposes
5966/////////////////////////////////////////////////////////////////////////////
5967
5968/**
5969 * Adds the given IsModified_* flag to the dirty flags of the machine.
5970 * This must be called either during loadSettings or under the machine write lock.
5971 * @param fl
5972 */
5973void Machine::setModified(uint32_t fl)
5974{
5975 mData->flModifications |= fl;
5976}
5977
5978/**
5979 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
5980 * care of the write locking.
5981 *
5982 * @param fModifications The flag to add.
5983 */
5984void Machine::setModifiedLock(uint32_t fModification)
5985{
5986 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5987 mData->flModifications |= fModification;
5988}
5989
5990/**
5991 * Saves the registry entry of this machine to the given configuration node.
5992 *
5993 * @param aEntryNode Node to save the registry entry to.
5994 *
5995 * @note locks this object for reading.
5996 */
5997HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5998{
5999 AutoLimitedCaller autoCaller(this);
6000 AssertComRCReturnRC(autoCaller.rc());
6001
6002 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6003
6004 data.uuid = mData->mUuid;
6005 data.strSettingsFile = mData->m_strConfigFile;
6006
6007 return S_OK;
6008}
6009
6010/**
6011 * Calculates the absolute path of the given path taking the directory of the
6012 * machine settings file as the current directory.
6013 *
6014 * @param aPath Path to calculate the absolute path for.
6015 * @param aResult Where to put the result (used only on success, can be the
6016 * same Utf8Str instance as passed in @a aPath).
6017 * @return IPRT result.
6018 *
6019 * @note Locks this object for reading.
6020 */
6021int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
6022{
6023 AutoCaller autoCaller(this);
6024 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6025
6026 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6027
6028 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
6029
6030 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
6031
6032 strSettingsDir.stripFilename();
6033 char folder[RTPATH_MAX];
6034 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
6035 if (RT_SUCCESS(vrc))
6036 aResult = folder;
6037
6038 return vrc;
6039}
6040
6041/**
6042 * Copies strSource to strTarget, making it relative to the machine folder
6043 * if it is a subdirectory thereof, or simply copying it otherwise.
6044 *
6045 * @param strSource Path to evaluate and copy.
6046 * @param strTarget Buffer to receive target path.
6047 *
6048 * @note Locks this object for reading.
6049 */
6050void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6051 Utf8Str &strTarget)
6052{
6053 AutoCaller autoCaller(this);
6054 AssertComRCReturn(autoCaller.rc(), (void)0);
6055
6056 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6057
6058 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6059 // use strTarget as a temporary buffer to hold the machine settings dir
6060 strTarget = mData->m_strConfigFileFull;
6061 strTarget.stripFilename();
6062 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6063 // is relative: then append what's left
6064 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6065 else
6066 // is not relative: then overwrite
6067 strTarget = strSource;
6068}
6069
6070/**
6071 * Returns the full path to the machine's log folder in the
6072 * \a aLogFolder argument.
6073 */
6074void Machine::getLogFolder(Utf8Str &aLogFolder)
6075{
6076 AutoCaller autoCaller(this);
6077 AssertComRCReturnVoid(autoCaller.rc());
6078
6079 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6080
6081 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6082 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6083 aLogFolder.append(RTPATH_DELIMITER);
6084 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6085}
6086
6087/**
6088 * Returns the full path to the machine's log file for an given index.
6089 */
6090Utf8Str Machine::queryLogFilename(ULONG idx)
6091{
6092 Utf8Str logFolder;
6093 getLogFolder(logFolder);
6094 Assert(logFolder.length());
6095 Utf8Str log;
6096 if (idx == 0)
6097 log = Utf8StrFmt("%s%cVBox.log",
6098 logFolder.c_str(), RTPATH_DELIMITER);
6099 else
6100 log = Utf8StrFmt("%s%cVBox.log.%d",
6101 logFolder.c_str(), RTPATH_DELIMITER, idx);
6102 return log;
6103}
6104
6105/**
6106 * Composes a unique saved state filename based on the current system time. The filename is
6107 * granular to the second so this will work so long as no more than one snapshot is taken on
6108 * a machine per second.
6109 *
6110 * Before version 4.1, we used this formula for saved state files:
6111 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6112 * which no longer works because saved state files can now be shared between the saved state of the
6113 * "saved" machine and an online snapshot, and the following would cause problems:
6114 * 1) save machine
6115 * 2) create online snapshot from that machine state --> reusing saved state file
6116 * 3) save machine again --> filename would be reused, breaking the online snapshot
6117 *
6118 * So instead we now use a timestamp.
6119 *
6120 * @param str
6121 */
6122void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6123{
6124 AutoCaller autoCaller(this);
6125 AssertComRCReturnVoid(autoCaller.rc());
6126
6127 {
6128 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6129 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6130 }
6131
6132 RTTIMESPEC ts;
6133 RTTimeNow(&ts);
6134 RTTIME time;
6135 RTTimeExplode(&time, &ts);
6136
6137 strStateFilePath += RTPATH_DELIMITER;
6138 strStateFilePath += Utf8StrFmt("%04ld-%02u-%02uT%02u-%02u-%02u-%09luZ.sav",
6139 time.i32Year,
6140 time.u8Month,
6141 time.u8MonthDay,
6142 time.u8Hour,
6143 time.u8Minute,
6144 time.u8Second,
6145 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 /* USB Controller */
7469 rc = mUSBController->loadSettings(data.usbController);
7470 if (FAILED(rc)) return rc;
7471
7472 // network adapters
7473 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7474 it != data.llNetworkAdapters.end();
7475 ++it)
7476 {
7477 const settings::NetworkAdapter &nic = *it;
7478
7479 /* slot unicity is guaranteed by XML Schema */
7480 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7481 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7482 if (FAILED(rc)) return rc;
7483 }
7484
7485 // serial ports
7486 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7487 it != data.llSerialPorts.end();
7488 ++it)
7489 {
7490 const settings::SerialPort &s = *it;
7491
7492 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7493 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7494 if (FAILED(rc)) return rc;
7495 }
7496
7497 // parallel ports (optional)
7498 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7499 it != data.llParallelPorts.end();
7500 ++it)
7501 {
7502 const settings::ParallelPort &p = *it;
7503
7504 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7505 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7506 if (FAILED(rc)) return rc;
7507 }
7508
7509 /* AudioAdapter */
7510 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7511 if (FAILED(rc)) return rc;
7512
7513 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7514 it != data.llSharedFolders.end();
7515 ++it)
7516 {
7517 const settings::SharedFolder &sf = *it;
7518 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7519 Bstr(sf.strHostPath).raw(),
7520 sf.fWritable, sf.fAutoMount);
7521 if (FAILED(rc)) return rc;
7522 }
7523
7524 // Clipboard
7525 mHWData->mClipboardMode = data.clipboardMode;
7526
7527 // guest settings
7528 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7529
7530 // IO settings
7531 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7532 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7533
7534 // Bandwidth control
7535 rc = mBandwidthControl->loadSettings(data.ioSettings);
7536 if (FAILED(rc)) return rc;
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 configDir, newConfigDir;
8035
8036 do
8037 {
8038 int vrc = VINF_SUCCESS;
8039
8040 Utf8Str name = mUserData.backedUpData()->s.strName;
8041 Utf8Str newName = mUserData->s.strName;
8042
8043 configFile = mData->m_strConfigFileFull;
8044
8045 /* first, rename the directory if it matches the machine name */
8046 configDir = configFile;
8047 configDir.stripFilename();
8048 newConfigDir = configDir;
8049 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8050 {
8051 newConfigDir.stripFilename();
8052 newConfigDir.append(RTPATH_DELIMITER);
8053 newConfigDir.append(newName);
8054 /* new dir and old dir cannot be equal here because of 'if'
8055 * above and because name != newName */
8056 Assert(configDir != newConfigDir);
8057 if (!fSettingsFileIsNew)
8058 {
8059 /* perform real rename only if the machine is not new */
8060 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8061 if (RT_FAILURE(vrc))
8062 {
8063 rc = setError(E_FAIL,
8064 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8065 configDir.c_str(),
8066 newConfigDir.c_str(),
8067 vrc);
8068 break;
8069 }
8070 dirRenamed = true;
8071 }
8072 }
8073
8074 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8075 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8076
8077 /* then try to rename the settings file itself */
8078 if (newConfigFile != configFile)
8079 {
8080 /* get the path to old settings file in renamed directory */
8081 configFile = Utf8StrFmt("%s%c%s",
8082 newConfigDir.c_str(),
8083 RTPATH_DELIMITER,
8084 RTPathFilename(configFile.c_str()));
8085 if (!fSettingsFileIsNew)
8086 {
8087 /* perform real rename only if the machine is not new */
8088 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8089 if (RT_FAILURE(vrc))
8090 {
8091 rc = setError(E_FAIL,
8092 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8093 configFile.c_str(),
8094 newConfigFile.c_str(),
8095 vrc);
8096 break;
8097 }
8098 fileRenamed = true;
8099 }
8100 }
8101
8102 // update m_strConfigFileFull amd mConfigFile
8103 mData->m_strConfigFileFull = newConfigFile;
8104 // compute the relative path too
8105 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8106
8107 // store the old and new so that VirtualBox::saveSettings() can update
8108 // the media registry
8109 if ( mData->mRegistered
8110 && configDir != newConfigDir)
8111 {
8112 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8113
8114 if (pfNeedsGlobalSaveSettings)
8115 *pfNeedsGlobalSaveSettings = true;
8116 }
8117
8118 // in the saved state file path, replace the old directory with the new directory
8119 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8120 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8121
8122 // and do the same thing for the saved state file paths of all the online snapshots
8123 if (mData->mFirstSnapshot)
8124 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8125 newConfigDir.c_str());
8126 }
8127 while (0);
8128
8129 if (FAILED(rc))
8130 {
8131 /* silently try to rename everything back */
8132 if (fileRenamed)
8133 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8134 if (dirRenamed)
8135 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8136 }
8137
8138 if (FAILED(rc)) return rc;
8139 }
8140
8141 if (fSettingsFileIsNew)
8142 {
8143 /* create a virgin config file */
8144 int vrc = VINF_SUCCESS;
8145
8146 /* ensure the settings directory exists */
8147 Utf8Str path(mData->m_strConfigFileFull);
8148 path.stripFilename();
8149 if (!RTDirExists(path.c_str()))
8150 {
8151 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8152 if (RT_FAILURE(vrc))
8153 {
8154 return setError(E_FAIL,
8155 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8156 path.c_str(),
8157 vrc);
8158 }
8159 }
8160
8161 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8162 path = Utf8Str(mData->m_strConfigFileFull);
8163 RTFILE f = NIL_RTFILE;
8164 vrc = RTFileOpen(&f, path.c_str(),
8165 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8166 if (RT_FAILURE(vrc))
8167 return setError(E_FAIL,
8168 tr("Could not create the settings file '%s' (%Rrc)"),
8169 path.c_str(),
8170 vrc);
8171 RTFileClose(f);
8172 }
8173
8174 return rc;
8175}
8176
8177/**
8178 * Saves and commits machine data, user data and hardware data.
8179 *
8180 * Note that on failure, the data remains uncommitted.
8181 *
8182 * @a aFlags may combine the following flags:
8183 *
8184 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8185 * Used when saving settings after an operation that makes them 100%
8186 * correspond to the settings from the current snapshot.
8187 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8188 * #isReallyModified() returns false. This is necessary for cases when we
8189 * change machine data directly, not through the backup()/commit() mechanism.
8190 * - SaveS_Force: settings will be saved without doing a deep compare of the
8191 * settings structures. This is used when this is called because snapshots
8192 * have changed to avoid the overhead of the deep compare.
8193 *
8194 * @note Must be called from under this object's write lock. Locks children for
8195 * writing.
8196 *
8197 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8198 * initialized to false and that will be set to true by this function if
8199 * the caller must invoke VirtualBox::saveSettings() because the global
8200 * settings have changed. This will happen if a machine rename has been
8201 * saved and the global machine and media registries will therefore need
8202 * updating.
8203 */
8204HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8205 int aFlags /*= 0*/)
8206{
8207 LogFlowThisFuncEnter();
8208
8209 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8210
8211 /* make sure child objects are unable to modify the settings while we are
8212 * saving them */
8213 ensureNoStateDependencies();
8214
8215 AssertReturn(!isSnapshotMachine(),
8216 E_FAIL);
8217
8218 HRESULT rc = S_OK;
8219 bool fNeedsWrite = false;
8220
8221 /* First, prepare to save settings. It will care about renaming the
8222 * settings directory and file if the machine name was changed and about
8223 * creating a new settings file if this is a new machine. */
8224 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8225 if (FAILED(rc)) return rc;
8226
8227 // keep a pointer to the current settings structures
8228 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8229 settings::MachineConfigFile *pNewConfig = NULL;
8230
8231 try
8232 {
8233 // make a fresh one to have everyone write stuff into
8234 pNewConfig = new settings::MachineConfigFile(NULL);
8235 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8236
8237 // now go and copy all the settings data from COM to the settings structures
8238 // (this calles saveSettings() on all the COM objects in the machine)
8239 copyMachineDataToSettings(*pNewConfig);
8240
8241 if (aFlags & SaveS_ResetCurStateModified)
8242 {
8243 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8244 mData->mCurrentStateModified = FALSE;
8245 fNeedsWrite = true; // always, no need to compare
8246 }
8247 else if (aFlags & SaveS_Force)
8248 {
8249 fNeedsWrite = true; // always, no need to compare
8250 }
8251 else
8252 {
8253 if (!mData->mCurrentStateModified)
8254 {
8255 // do a deep compare of the settings that we just saved with the settings
8256 // previously stored in the config file; this invokes MachineConfigFile::operator==
8257 // which does a deep compare of all the settings, which is expensive but less expensive
8258 // than writing out XML in vain
8259 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8260
8261 // could still be modified if any settings changed
8262 mData->mCurrentStateModified = fAnySettingsChanged;
8263
8264 fNeedsWrite = fAnySettingsChanged;
8265 }
8266 else
8267 fNeedsWrite = true;
8268 }
8269
8270 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8271
8272 if (fNeedsWrite)
8273 // now spit it all out!
8274 pNewConfig->write(mData->m_strConfigFileFull);
8275
8276 mData->pMachineConfigFile = pNewConfig;
8277 delete pOldConfig;
8278 commit();
8279
8280 // after saving settings, we are no longer different from the XML on disk
8281 mData->flModifications = 0;
8282 }
8283 catch (HRESULT err)
8284 {
8285 // we assume that error info is set by the thrower
8286 rc = err;
8287
8288 // restore old config
8289 delete pNewConfig;
8290 mData->pMachineConfigFile = pOldConfig;
8291 }
8292 catch (...)
8293 {
8294 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8295 }
8296
8297 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8298 {
8299 /* Fire the data change event, even on failure (since we've already
8300 * committed all data). This is done only for SessionMachines because
8301 * mutable Machine instances are always not registered (i.e. private
8302 * to the client process that creates them) and thus don't need to
8303 * inform callbacks. */
8304 if (isSessionMachine())
8305 mParent->onMachineDataChange(mData->mUuid);
8306 }
8307
8308 LogFlowThisFunc(("rc=%08X\n", rc));
8309 LogFlowThisFuncLeave();
8310 return rc;
8311}
8312
8313/**
8314 * Implementation for saving the machine settings into the given
8315 * settings::MachineConfigFile instance. This copies machine extradata
8316 * from the previous machine config file in the instance data, if any.
8317 *
8318 * This gets called from two locations:
8319 *
8320 * -- Machine::saveSettings(), during the regular XML writing;
8321 *
8322 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8323 * exported to OVF and we write the VirtualBox proprietary XML
8324 * into a <vbox:Machine> tag.
8325 *
8326 * This routine fills all the fields in there, including snapshots, *except*
8327 * for the following:
8328 *
8329 * -- fCurrentStateModified. There is some special logic associated with that.
8330 *
8331 * The caller can then call MachineConfigFile::write() or do something else
8332 * with it.
8333 *
8334 * Caller must hold the machine lock!
8335 *
8336 * This throws XML errors and HRESULT, so the caller must have a catch block!
8337 */
8338void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8339{
8340 // deep copy extradata
8341 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8342
8343 config.uuid = mData->mUuid;
8344
8345 // copy name, description, OS type, teleport, UTC etc.
8346 config.machineUserData = mUserData->s;
8347
8348 if ( mData->mMachineState == MachineState_Saved
8349 || mData->mMachineState == MachineState_Restoring
8350 // when deleting a snapshot we may or may not have a saved state in the current state,
8351 // so let's not assert here please
8352 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8353 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8354 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8355 && (!mSSData->strStateFilePath.isEmpty())
8356 )
8357 )
8358 {
8359 Assert(!mSSData->strStateFilePath.isEmpty());
8360 /* try to make the file name relative to the settings file dir */
8361 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
8362 }
8363 else
8364 {
8365 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
8366 config.strStateFile.setNull();
8367 }
8368
8369 if (mData->mCurrentSnapshot)
8370 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8371 else
8372 config.uuidCurrentSnapshot.clear();
8373
8374 config.timeLastStateChange = mData->mLastStateChange;
8375 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8376 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8377
8378 HRESULT rc = saveHardware(config.hardwareMachine);
8379 if (FAILED(rc)) throw rc;
8380
8381 rc = saveStorageControllers(config.storageMachine);
8382 if (FAILED(rc)) throw rc;
8383
8384 // save machine's media registry if this is VirtualBox 4.0 or later
8385 if (config.canHaveOwnMediaRegistry())
8386 {
8387 // determine machine folder
8388 Utf8Str strMachineFolder = getSettingsFileFull();
8389 strMachineFolder.stripFilename();
8390 mParent->saveMediaRegistry(config.mediaRegistry,
8391 getId(), // only media with registry ID == machine UUID
8392 strMachineFolder);
8393 // this throws HRESULT
8394 }
8395
8396 // save snapshots
8397 rc = saveAllSnapshots(config);
8398 if (FAILED(rc)) throw rc;
8399}
8400
8401/**
8402 * Saves all snapshots of the machine into the given machine config file. Called
8403 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8404 * @param config
8405 * @return
8406 */
8407HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8408{
8409 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8410
8411 HRESULT rc = S_OK;
8412
8413 try
8414 {
8415 config.llFirstSnapshot.clear();
8416
8417 if (mData->mFirstSnapshot)
8418 {
8419 settings::Snapshot snapNew;
8420 config.llFirstSnapshot.push_back(snapNew);
8421
8422 // get reference to the fresh copy of the snapshot on the list and
8423 // work on that copy directly to avoid excessive copying later
8424 settings::Snapshot &snap = config.llFirstSnapshot.front();
8425
8426 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8427 if (FAILED(rc)) throw rc;
8428 }
8429
8430// if (mType == IsSessionMachine)
8431// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8432
8433 }
8434 catch (HRESULT err)
8435 {
8436 /* we assume that error info is set by the thrower */
8437 rc = err;
8438 }
8439 catch (...)
8440 {
8441 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8442 }
8443
8444 return rc;
8445}
8446
8447/**
8448 * Saves the VM hardware configuration. It is assumed that the
8449 * given node is empty.
8450 *
8451 * @param aNode <Hardware> node to save the VM hardware configuration to.
8452 */
8453HRESULT Machine::saveHardware(settings::Hardware &data)
8454{
8455 HRESULT rc = S_OK;
8456
8457 try
8458 {
8459 /* The hardware version attribute (optional).
8460 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8461 if ( mHWData->mHWVersion == "1"
8462 && mSSData->strStateFilePath.isEmpty()
8463 )
8464 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. */
8465
8466 data.strVersion = mHWData->mHWVersion;
8467 data.uuid = mHWData->mHardwareUUID;
8468
8469 // CPU
8470 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8471 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8472 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8473 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8474 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8475 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8476 data.fPAE = !!mHWData->mPAEEnabled;
8477 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8478
8479 /* Standard and Extended CPUID leafs. */
8480 data.llCpuIdLeafs.clear();
8481 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8482 {
8483 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8484 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8485 }
8486 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8487 {
8488 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8489 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8490 }
8491
8492 data.cCPUs = mHWData->mCPUCount;
8493 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8494 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8495
8496 data.llCpus.clear();
8497 if (data.fCpuHotPlug)
8498 {
8499 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8500 {
8501 if (mHWData->mCPUAttached[idx])
8502 {
8503 settings::Cpu cpu;
8504 cpu.ulId = idx;
8505 data.llCpus.push_back(cpu);
8506 }
8507 }
8508 }
8509
8510 // memory
8511 data.ulMemorySizeMB = mHWData->mMemorySize;
8512 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8513
8514 // firmware
8515 data.firmwareType = mHWData->mFirmwareType;
8516
8517 // HID
8518 data.pointingHidType = mHWData->mPointingHidType;
8519 data.keyboardHidType = mHWData->mKeyboardHidType;
8520
8521 // chipset
8522 data.chipsetType = mHWData->mChipsetType;
8523
8524 // HPET
8525 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8526
8527 // boot order
8528 data.mapBootOrder.clear();
8529 for (size_t i = 0;
8530 i < RT_ELEMENTS(mHWData->mBootOrder);
8531 ++i)
8532 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8533
8534 // display
8535 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8536 data.cMonitors = mHWData->mMonitorCount;
8537 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8538 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8539
8540 /* VRDEServer settings (optional) */
8541 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8542 if (FAILED(rc)) throw rc;
8543
8544 /* BIOS (required) */
8545 rc = mBIOSSettings->saveSettings(data.biosSettings);
8546 if (FAILED(rc)) throw rc;
8547
8548 /* USB Controller (required) */
8549 rc = mUSBController->saveSettings(data.usbController);
8550 if (FAILED(rc)) throw rc;
8551
8552 /* Network adapters (required) */
8553 data.llNetworkAdapters.clear();
8554 for (ULONG slot = 0;
8555 slot < RT_ELEMENTS(mNetworkAdapters);
8556 ++slot)
8557 {
8558 settings::NetworkAdapter nic;
8559 nic.ulSlot = slot;
8560 rc = mNetworkAdapters[slot]->saveSettings(nic);
8561 if (FAILED(rc)) throw rc;
8562
8563 data.llNetworkAdapters.push_back(nic);
8564 }
8565
8566 /* Serial ports */
8567 data.llSerialPorts.clear();
8568 for (ULONG slot = 0;
8569 slot < RT_ELEMENTS(mSerialPorts);
8570 ++slot)
8571 {
8572 settings::SerialPort s;
8573 s.ulSlot = slot;
8574 rc = mSerialPorts[slot]->saveSettings(s);
8575 if (FAILED(rc)) return rc;
8576
8577 data.llSerialPorts.push_back(s);
8578 }
8579
8580 /* Parallel ports */
8581 data.llParallelPorts.clear();
8582 for (ULONG slot = 0;
8583 slot < RT_ELEMENTS(mParallelPorts);
8584 ++slot)
8585 {
8586 settings::ParallelPort p;
8587 p.ulSlot = slot;
8588 rc = mParallelPorts[slot]->saveSettings(p);
8589 if (FAILED(rc)) return rc;
8590
8591 data.llParallelPorts.push_back(p);
8592 }
8593
8594 /* Audio adapter */
8595 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8596 if (FAILED(rc)) return rc;
8597
8598 /* Shared folders */
8599 data.llSharedFolders.clear();
8600 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8601 it != mHWData->mSharedFolders.end();
8602 ++it)
8603 {
8604 SharedFolder *pSF = *it;
8605 AutoCaller sfCaller(pSF);
8606 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8607 settings::SharedFolder sf;
8608 sf.strName = pSF->getName();
8609 sf.strHostPath = pSF->getHostPath();
8610 sf.fWritable = !!pSF->isWritable();
8611 sf.fAutoMount = !!pSF->isAutoMounted();
8612
8613 data.llSharedFolders.push_back(sf);
8614 }
8615
8616 // clipboard
8617 data.clipboardMode = mHWData->mClipboardMode;
8618
8619 /* Guest */
8620 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8621
8622 // IO settings
8623 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8624 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8625
8626 /* BandwidthControl (required) */
8627 rc = mBandwidthControl->saveSettings(data.ioSettings);
8628 if (FAILED(rc)) throw rc;
8629
8630 /* Host PCI devices */
8631 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
8632 it != mHWData->mPciDeviceAssignments.end();
8633 ++it)
8634 {
8635 ComObjPtr<PciDeviceAttachment> pda = *it;
8636 settings::HostPciDeviceAttachment hpda;
8637
8638 rc = pda->saveSettings(hpda);
8639 if (FAILED(rc)) throw rc;
8640
8641 data.pciAttachments.push_back(hpda);
8642 }
8643
8644
8645 // guest properties
8646 data.llGuestProperties.clear();
8647#ifdef VBOX_WITH_GUEST_PROPS
8648 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8649 it != mHWData->mGuestProperties.end();
8650 ++it)
8651 {
8652 HWData::GuestProperty property = *it;
8653
8654 /* Remove transient guest properties at shutdown unless we
8655 * are saving state */
8656 if ( ( mData->mMachineState == MachineState_PoweredOff
8657 || mData->mMachineState == MachineState_Aborted
8658 || mData->mMachineState == MachineState_Teleported)
8659 && property.mFlags & guestProp::TRANSIENT)
8660 continue;
8661 settings::GuestProperty prop;
8662 prop.strName = property.strName;
8663 prop.strValue = property.strValue;
8664 prop.timestamp = property.mTimestamp;
8665 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8666 guestProp::writeFlags(property.mFlags, szFlags);
8667 prop.strFlags = szFlags;
8668
8669 data.llGuestProperties.push_back(prop);
8670 }
8671
8672 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8673 /* I presume this doesn't require a backup(). */
8674 mData->mGuestPropertiesModified = FALSE;
8675#endif /* VBOX_WITH_GUEST_PROPS defined */
8676 }
8677 catch(std::bad_alloc &)
8678 {
8679 return E_OUTOFMEMORY;
8680 }
8681
8682 AssertComRC(rc);
8683 return rc;
8684}
8685
8686/**
8687 * Saves the storage controller configuration.
8688 *
8689 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8690 */
8691HRESULT Machine::saveStorageControllers(settings::Storage &data)
8692{
8693 data.llStorageControllers.clear();
8694
8695 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8696 it != mStorageControllers->end();
8697 ++it)
8698 {
8699 HRESULT rc;
8700 ComObjPtr<StorageController> pCtl = *it;
8701
8702 settings::StorageController ctl;
8703 ctl.strName = pCtl->getName();
8704 ctl.controllerType = pCtl->getControllerType();
8705 ctl.storageBus = pCtl->getStorageBus();
8706 ctl.ulInstance = pCtl->getInstance();
8707 ctl.fBootable = pCtl->getBootable();
8708
8709 /* Save the port count. */
8710 ULONG portCount;
8711 rc = pCtl->COMGETTER(PortCount)(&portCount);
8712 ComAssertComRCRet(rc, rc);
8713 ctl.ulPortCount = portCount;
8714
8715 /* Save fUseHostIOCache */
8716 BOOL fUseHostIOCache;
8717 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8718 ComAssertComRCRet(rc, rc);
8719 ctl.fUseHostIOCache = !!fUseHostIOCache;
8720
8721 /* Save IDE emulation settings. */
8722 if (ctl.controllerType == StorageControllerType_IntelAhci)
8723 {
8724 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8725 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8726 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8727 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8728 )
8729 ComAssertComRCRet(rc, rc);
8730 }
8731
8732 /* save the devices now. */
8733 rc = saveStorageDevices(pCtl, ctl);
8734 ComAssertComRCRet(rc, rc);
8735
8736 data.llStorageControllers.push_back(ctl);
8737 }
8738
8739 return S_OK;
8740}
8741
8742/**
8743 * Saves the hard disk configuration.
8744 */
8745HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8746 settings::StorageController &data)
8747{
8748 MediaData::AttachmentList atts;
8749
8750 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8751 if (FAILED(rc)) return rc;
8752
8753 data.llAttachedDevices.clear();
8754 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8755 it != atts.end();
8756 ++it)
8757 {
8758 settings::AttachedDevice dev;
8759
8760 MediumAttachment *pAttach = *it;
8761 Medium *pMedium = pAttach->getMedium();
8762
8763 dev.deviceType = pAttach->getType();
8764 dev.lPort = pAttach->getPort();
8765 dev.lDevice = pAttach->getDevice();
8766 if (pMedium)
8767 {
8768 if (pMedium->isHostDrive())
8769 dev.strHostDriveSrc = pMedium->getLocationFull();
8770 else
8771 dev.uuid = pMedium->getId();
8772 dev.fPassThrough = pAttach->getPassthrough();
8773 }
8774
8775 dev.strBwGroup = pAttach->getBandwidthGroup();
8776
8777 data.llAttachedDevices.push_back(dev);
8778 }
8779
8780 return S_OK;
8781}
8782
8783/**
8784 * Saves machine state settings as defined by aFlags
8785 * (SaveSTS_* values).
8786 *
8787 * @param aFlags Combination of SaveSTS_* flags.
8788 *
8789 * @note Locks objects for writing.
8790 */
8791HRESULT Machine::saveStateSettings(int aFlags)
8792{
8793 if (aFlags == 0)
8794 return S_OK;
8795
8796 AutoCaller autoCaller(this);
8797 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8798
8799 /* This object's write lock is also necessary to serialize file access
8800 * (prevent concurrent reads and writes) */
8801 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8802
8803 HRESULT rc = S_OK;
8804
8805 Assert(mData->pMachineConfigFile);
8806
8807 try
8808 {
8809 if (aFlags & SaveSTS_CurStateModified)
8810 mData->pMachineConfigFile->fCurrentStateModified = true;
8811
8812 if (aFlags & SaveSTS_StateFilePath)
8813 {
8814 if (!mSSData->strStateFilePath.isEmpty())
8815 /* try to make the file name relative to the settings file dir */
8816 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
8817 else
8818 mData->pMachineConfigFile->strStateFile.setNull();
8819 }
8820
8821 if (aFlags & SaveSTS_StateTimeStamp)
8822 {
8823 Assert( mData->mMachineState != MachineState_Aborted
8824 || mSSData->strStateFilePath.isEmpty());
8825
8826 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8827
8828 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8829//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8830 }
8831
8832 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8833 }
8834 catch (...)
8835 {
8836 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8837 }
8838
8839 return rc;
8840}
8841
8842/**
8843 * Ensures that the given medium is added to a media registry. If this machine
8844 * was created with 4.0 or later, then the machine registry is used. Otherwise
8845 * the global VirtualBox media registry is used. If the medium was actually
8846 * added to a registry (because it wasn't in the registry yet), the UUID of
8847 * that registry is added to the given list so that the caller can save the
8848 * registry.
8849 *
8850 * Caller must hold machine read lock!
8851 *
8852 * @param pMedium
8853 * @param llRegistriesThatNeedSaving
8854 * @param puuid Optional buffer that receives the registry UUID that was used.
8855 */
8856void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
8857 GuidList &llRegistriesThatNeedSaving,
8858 Guid *puuid)
8859{
8860 // decide which medium registry to use now that the medium is attached:
8861 Guid uuid;
8862 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
8863 // machine XML is VirtualBox 4.0 or higher:
8864 uuid = getId(); // machine UUID
8865 else
8866 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
8867
8868 AutoCaller autoCaller(pMedium);
8869 if (FAILED(autoCaller.rc())) return;
8870 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8871
8872 if (pMedium->addRegistry(uuid, false /* fRecurse */))
8873 // registry actually changed:
8874 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
8875
8876 if (puuid)
8877 *puuid = uuid;
8878}
8879
8880/**
8881 * Creates differencing hard disks for all normal hard disks attached to this
8882 * machine and a new set of attachments to refer to created disks.
8883 *
8884 * Used when taking a snapshot or when deleting the current state. Gets called
8885 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8886 *
8887 * This method assumes that mMediaData contains the original hard disk attachments
8888 * it needs to create diffs for. On success, these attachments will be replaced
8889 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8890 * called to delete created diffs which will also rollback mMediaData and restore
8891 * whatever was backed up before calling this method.
8892 *
8893 * Attachments with non-normal hard disks are left as is.
8894 *
8895 * If @a aOnline is @c false then the original hard disks that require implicit
8896 * diffs will be locked for reading. Otherwise it is assumed that they are
8897 * already locked for writing (when the VM was started). Note that in the latter
8898 * case it is responsibility of the caller to lock the newly created diffs for
8899 * writing if this method succeeds.
8900 *
8901 * @param aProgress Progress object to run (must contain at least as
8902 * many operations left as the number of hard disks
8903 * attached).
8904 * @param aOnline Whether the VM was online prior to this operation.
8905 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
8906 *
8907 * @note The progress object is not marked as completed, neither on success nor
8908 * on failure. This is a responsibility of the caller.
8909 *
8910 * @note Locks this object for writing.
8911 */
8912HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8913 ULONG aWeight,
8914 bool aOnline,
8915 GuidList *pllRegistriesThatNeedSaving)
8916{
8917 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8918
8919 AutoCaller autoCaller(this);
8920 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8921
8922 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8923
8924 /* must be in a protective state because we leave the lock below */
8925 AssertReturn( mData->mMachineState == MachineState_Saving
8926 || mData->mMachineState == MachineState_LiveSnapshotting
8927 || mData->mMachineState == MachineState_RestoringSnapshot
8928 || mData->mMachineState == MachineState_DeletingSnapshot
8929 , E_FAIL);
8930
8931 HRESULT rc = S_OK;
8932
8933 MediumLockListMap lockedMediaOffline;
8934 MediumLockListMap *lockedMediaMap;
8935 if (aOnline)
8936 lockedMediaMap = &mData->mSession.mLockedMedia;
8937 else
8938 lockedMediaMap = &lockedMediaOffline;
8939
8940 try
8941 {
8942 if (!aOnline)
8943 {
8944 /* lock all attached hard disks early to detect "in use"
8945 * situations before creating actual diffs */
8946 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8947 it != mMediaData->mAttachments.end();
8948 ++it)
8949 {
8950 MediumAttachment* pAtt = *it;
8951 if (pAtt->getType() == DeviceType_HardDisk)
8952 {
8953 Medium* pMedium = pAtt->getMedium();
8954 Assert(pMedium);
8955
8956 MediumLockList *pMediumLockList(new MediumLockList());
8957 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8958 false /* fMediumLockWrite */,
8959 NULL,
8960 *pMediumLockList);
8961 if (FAILED(rc))
8962 {
8963 delete pMediumLockList;
8964 throw rc;
8965 }
8966 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8967 if (FAILED(rc))
8968 {
8969 throw setError(rc,
8970 tr("Collecting locking information for all attached media failed"));
8971 }
8972 }
8973 }
8974
8975 /* Now lock all media. If this fails, nothing is locked. */
8976 rc = lockedMediaMap->Lock();
8977 if (FAILED(rc))
8978 {
8979 throw setError(rc,
8980 tr("Locking of attached media failed"));
8981 }
8982 }
8983
8984 /* remember the current list (note that we don't use backup() since
8985 * mMediaData may be already backed up) */
8986 MediaData::AttachmentList atts = mMediaData->mAttachments;
8987
8988 /* start from scratch */
8989 mMediaData->mAttachments.clear();
8990
8991 /* go through remembered attachments and create diffs for normal hard
8992 * disks and attach them */
8993 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8994 it != atts.end();
8995 ++it)
8996 {
8997 MediumAttachment* pAtt = *it;
8998
8999 DeviceType_T devType = pAtt->getType();
9000 Medium* pMedium = pAtt->getMedium();
9001
9002 if ( devType != DeviceType_HardDisk
9003 || pMedium == NULL
9004 || pMedium->getType() != MediumType_Normal)
9005 {
9006 /* copy the attachment as is */
9007
9008 /** @todo the progress object created in Console::TakeSnaphot
9009 * only expects operations for hard disks. Later other
9010 * device types need to show up in the progress as well. */
9011 if (devType == DeviceType_HardDisk)
9012 {
9013 if (pMedium == NULL)
9014 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9015 aWeight); // weight
9016 else
9017 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9018 pMedium->getBase()->getName().c_str()).raw(),
9019 aWeight); // weight
9020 }
9021
9022 mMediaData->mAttachments.push_back(pAtt);
9023 continue;
9024 }
9025
9026 /* need a diff */
9027 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9028 pMedium->getBase()->getName().c_str()).raw(),
9029 aWeight); // weight
9030
9031 Utf8Str strFullSnapshotFolder;
9032 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9033
9034 ComObjPtr<Medium> diff;
9035 diff.createObject();
9036 // store the diff in the same registry as the parent
9037 // (this cannot fail here because we can't create implicit diffs for
9038 // unregistered images)
9039 Guid uuidRegistryParent;
9040 Assert(pMedium->getFirstRegistryMachineId(uuidRegistryParent));
9041 rc = diff->init(mParent,
9042 pMedium->getPreferredDiffFormat(),
9043 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9044 uuidRegistryParent,
9045 pllRegistriesThatNeedSaving);
9046 if (FAILED(rc)) throw rc;
9047
9048 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9049 * the push_back? Looks like we're going to leave medium with the
9050 * wrong kind of lock (general issue with if we fail anywhere at all)
9051 * and an orphaned VDI in the snapshots folder. */
9052
9053 /* update the appropriate lock list */
9054 MediumLockList *pMediumLockList;
9055 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9056 AssertComRCThrowRC(rc);
9057 if (aOnline)
9058 {
9059 rc = pMediumLockList->Update(pMedium, false);
9060 AssertComRCThrowRC(rc);
9061 }
9062
9063 /* leave the lock before the potentially lengthy operation */
9064 alock.leave();
9065 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9066 pMediumLockList,
9067 NULL /* aProgress */,
9068 true /* aWait */,
9069 pllRegistriesThatNeedSaving);
9070 alock.enter();
9071 if (FAILED(rc)) throw rc;
9072
9073 rc = lockedMediaMap->Unlock();
9074 AssertComRCThrowRC(rc);
9075 rc = pMediumLockList->Append(diff, true);
9076 AssertComRCThrowRC(rc);
9077 rc = lockedMediaMap->Lock();
9078 AssertComRCThrowRC(rc);
9079
9080 rc = diff->addBackReference(mData->mUuid);
9081 AssertComRCThrowRC(rc);
9082
9083 /* add a new attachment */
9084 ComObjPtr<MediumAttachment> attachment;
9085 attachment.createObject();
9086 rc = attachment->init(this,
9087 diff,
9088 pAtt->getControllerName(),
9089 pAtt->getPort(),
9090 pAtt->getDevice(),
9091 DeviceType_HardDisk,
9092 true /* aImplicit */,
9093 pAtt->getBandwidthGroup());
9094 if (FAILED(rc)) throw rc;
9095
9096 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9097 AssertComRCThrowRC(rc);
9098 mMediaData->mAttachments.push_back(attachment);
9099 }
9100 }
9101 catch (HRESULT aRC) { rc = aRC; }
9102
9103 /* unlock all hard disks we locked */
9104 if (!aOnline)
9105 {
9106 ErrorInfoKeeper eik;
9107
9108 rc = lockedMediaMap->Clear();
9109 AssertComRC(rc);
9110 }
9111
9112 if (FAILED(rc))
9113 {
9114 MultiResult mrc = rc;
9115
9116 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9117 }
9118
9119 return rc;
9120}
9121
9122/**
9123 * Deletes implicit differencing hard disks created either by
9124 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
9125 *
9126 * Note that to delete hard disks created by #AttachMedium() this method is
9127 * called from #fixupMedia() when the changes are rolled back.
9128 *
9129 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9130 *
9131 * @note Locks this object for writing.
9132 */
9133HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9134{
9135 AutoCaller autoCaller(this);
9136 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9137
9138 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9139 LogFlowThisFuncEnter();
9140
9141 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9142
9143 HRESULT rc = S_OK;
9144
9145 MediaData::AttachmentList implicitAtts;
9146
9147 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9148
9149 /* enumerate new attachments */
9150 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9151 it != mMediaData->mAttachments.end();
9152 ++it)
9153 {
9154 ComObjPtr<Medium> hd = (*it)->getMedium();
9155 if (hd.isNull())
9156 continue;
9157
9158 if ((*it)->isImplicit())
9159 {
9160 /* deassociate and mark for deletion */
9161 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
9162 rc = hd->removeBackReference(mData->mUuid);
9163 AssertComRC(rc);
9164 implicitAtts.push_back(*it);
9165 continue;
9166 }
9167
9168 /* was this hard disk attached before? */
9169 if (!findAttachment(oldAtts, hd))
9170 {
9171 /* no: de-associate */
9172 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9173 rc = hd->removeBackReference(mData->mUuid);
9174 AssertComRC(rc);
9175 continue;
9176 }
9177 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9178 }
9179
9180 /* rollback hard disk changes */
9181 mMediaData.rollback();
9182
9183 MultiResult mrc(S_OK);
9184
9185 /* delete unused implicit diffs */
9186 if (implicitAtts.size() != 0)
9187 {
9188 /* will leave the lock before the potentially lengthy
9189 * operation, so protect with the special state (unless already
9190 * protected) */
9191 MachineState_T oldState = mData->mMachineState;
9192 if ( oldState != MachineState_Saving
9193 && oldState != MachineState_LiveSnapshotting
9194 && oldState != MachineState_RestoringSnapshot
9195 && oldState != MachineState_DeletingSnapshot
9196 && oldState != MachineState_DeletingSnapshotOnline
9197 && oldState != MachineState_DeletingSnapshotPaused
9198 )
9199 setMachineState(MachineState_SettingUp);
9200
9201 alock.leave();
9202
9203 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9204 it != implicitAtts.end();
9205 ++it)
9206 {
9207 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9208 ComObjPtr<Medium> hd = (*it)->getMedium();
9209
9210 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9211 pllRegistriesThatNeedSaving);
9212 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9213 mrc = rc;
9214 }
9215
9216 alock.enter();
9217
9218 if (mData->mMachineState == MachineState_SettingUp)
9219 setMachineState(oldState);
9220 }
9221
9222 return mrc;
9223}
9224
9225/**
9226 * Looks through the given list of media attachments for one with the given parameters
9227 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9228 * can be searched as well if needed.
9229 *
9230 * @param list
9231 * @param aControllerName
9232 * @param aControllerPort
9233 * @param aDevice
9234 * @return
9235 */
9236MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9237 IN_BSTR aControllerName,
9238 LONG aControllerPort,
9239 LONG aDevice)
9240{
9241 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9242 it != ll.end();
9243 ++it)
9244 {
9245 MediumAttachment *pAttach = *it;
9246 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9247 return pAttach;
9248 }
9249
9250 return NULL;
9251}
9252
9253/**
9254 * Looks through the given list of media attachments for one with the given parameters
9255 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9256 * can be searched as well if needed.
9257 *
9258 * @param list
9259 * @param aControllerName
9260 * @param aControllerPort
9261 * @param aDevice
9262 * @return
9263 */
9264MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9265 ComObjPtr<Medium> pMedium)
9266{
9267 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9268 it != ll.end();
9269 ++it)
9270 {
9271 MediumAttachment *pAttach = *it;
9272 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9273 if (pMediumThis == pMedium)
9274 return pAttach;
9275 }
9276
9277 return NULL;
9278}
9279
9280/**
9281 * Looks through the given list of media attachments for one with the given parameters
9282 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9283 * can be searched as well if needed.
9284 *
9285 * @param list
9286 * @param aControllerName
9287 * @param aControllerPort
9288 * @param aDevice
9289 * @return
9290 */
9291MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9292 Guid &id)
9293{
9294 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9295 it != ll.end();
9296 ++it)
9297 {
9298 MediumAttachment *pAttach = *it;
9299 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9300 if (pMediumThis->getId() == id)
9301 return pAttach;
9302 }
9303
9304 return NULL;
9305}
9306
9307/**
9308 * Main implementation for Machine::DetachDevice. This also gets called
9309 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9310 *
9311 * @param pAttach Medium attachment to detach.
9312 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9313 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9314 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9315 * @return
9316 */
9317HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9318 AutoWriteLock &writeLock,
9319 Snapshot *pSnapshot,
9320 GuidList *pllRegistriesThatNeedSaving)
9321{
9322 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9323 DeviceType_T mediumType = pAttach->getType();
9324
9325 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9326
9327 if (pAttach->isImplicit())
9328 {
9329 /* attempt to implicitly delete the implicitly created diff */
9330
9331 /// @todo move the implicit flag from MediumAttachment to Medium
9332 /// and forbid any hard disk operation when it is implicit. Or maybe
9333 /// a special media state for it to make it even more simple.
9334
9335 Assert(mMediaData.isBackedUp());
9336
9337 /* will leave the lock before the potentially lengthy operation, so
9338 * protect with the special state */
9339 MachineState_T oldState = mData->mMachineState;
9340 setMachineState(MachineState_SettingUp);
9341
9342 writeLock.release();
9343
9344 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
9345 true /*aWait*/,
9346 pllRegistriesThatNeedSaving);
9347
9348 writeLock.acquire();
9349
9350 setMachineState(oldState);
9351
9352 if (FAILED(rc)) return rc;
9353 }
9354
9355 setModified(IsModified_Storage);
9356 mMediaData.backup();
9357
9358 // we cannot use erase (it) below because backup() above will create
9359 // a copy of the list and make this copy active, but the iterator
9360 // still refers to the original and is not valid for the copy
9361 mMediaData->mAttachments.remove(pAttach);
9362
9363 if (!oldmedium.isNull())
9364 {
9365 // if this is from a snapshot, do not defer detachment to commitMedia()
9366 if (pSnapshot)
9367 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9368 // else if non-hard disk media, do not defer detachment to commitMedia() either
9369 else if (mediumType != DeviceType_HardDisk)
9370 oldmedium->removeBackReference(mData->mUuid);
9371 }
9372
9373 return S_OK;
9374}
9375
9376/**
9377 * Goes thru all media of the given list and
9378 *
9379 * 1) calls detachDevice() on each of them for this machine and
9380 * 2) adds all Medium objects found in the process to the given list,
9381 * depending on cleanupMode.
9382 *
9383 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
9384 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
9385 * media to the list.
9386 *
9387 * This gets called from Machine::Unregister, both for the actual Machine and
9388 * the SnapshotMachine objects that might be found in the snapshots.
9389 *
9390 * Requires caller and locking. The machine lock must be passed in because it
9391 * will be passed on to detachDevice which needs it for temporary unlocking.
9392 *
9393 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9394 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9395 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9396 * otherwise no media get added.
9397 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9398 * @return
9399 */
9400HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9401 Snapshot *pSnapshot,
9402 CleanupMode_T cleanupMode,
9403 MediaList &llMedia)
9404{
9405 Assert(isWriteLockOnCurrentThread());
9406
9407 HRESULT rc;
9408
9409 // make a temporary list because detachDevice invalidates iterators into
9410 // mMediaData->mAttachments
9411 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9412
9413 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9414 it != llAttachments2.end();
9415 ++it)
9416 {
9417 ComObjPtr<MediumAttachment> &pAttach = *it;
9418 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9419
9420 if (!pMedium.isNull())
9421 {
9422 DeviceType_T devType = pMedium->getDeviceType();
9423 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9424 && devType == DeviceType_HardDisk)
9425 || (cleanupMode == CleanupMode_Full)
9426 )
9427 llMedia.push_back(pMedium);
9428 }
9429
9430 // real machine: then we need to use the proper method
9431 rc = detachDevice(pAttach,
9432 writeLock,
9433 pSnapshot,
9434 NULL /* pfNeedsSaveSettings */);
9435
9436 if (FAILED(rc))
9437 return rc;
9438 }
9439
9440 return S_OK;
9441}
9442
9443/**
9444 * Perform deferred hard disk detachments.
9445 *
9446 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9447 * backed up).
9448 *
9449 * If @a aOnline is @c true then this method will also unlock the old hard disks
9450 * for which the new implicit diffs were created and will lock these new diffs for
9451 * writing.
9452 *
9453 * @param aOnline Whether the VM was online prior to this operation.
9454 *
9455 * @note Locks this object for writing!
9456 */
9457void Machine::commitMedia(bool aOnline /*= false*/)
9458{
9459 AutoCaller autoCaller(this);
9460 AssertComRCReturnVoid(autoCaller.rc());
9461
9462 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9463
9464 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9465
9466 HRESULT rc = S_OK;
9467
9468 /* no attach/detach operations -- nothing to do */
9469 if (!mMediaData.isBackedUp())
9470 return;
9471
9472 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9473 bool fMediaNeedsLocking = false;
9474
9475 /* enumerate new attachments */
9476 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9477 it != mMediaData->mAttachments.end();
9478 ++it)
9479 {
9480 MediumAttachment *pAttach = *it;
9481
9482 pAttach->commit();
9483
9484 Medium* pMedium = pAttach->getMedium();
9485 bool fImplicit = pAttach->isImplicit();
9486
9487 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9488 (pMedium) ? pMedium->getName().c_str() : "NULL",
9489 fImplicit));
9490
9491 /** @todo convert all this Machine-based voodoo to MediumAttachment
9492 * based commit logic. */
9493 if (fImplicit)
9494 {
9495 /* convert implicit attachment to normal */
9496 pAttach->setImplicit(false);
9497
9498 if ( aOnline
9499 && pMedium
9500 && pAttach->getType() == DeviceType_HardDisk
9501 )
9502 {
9503 ComObjPtr<Medium> parent = pMedium->getParent();
9504 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9505
9506 /* update the appropriate lock list */
9507 MediumLockList *pMediumLockList;
9508 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9509 AssertComRC(rc);
9510 if (pMediumLockList)
9511 {
9512 /* unlock if there's a need to change the locking */
9513 if (!fMediaNeedsLocking)
9514 {
9515 rc = mData->mSession.mLockedMedia.Unlock();
9516 AssertComRC(rc);
9517 fMediaNeedsLocking = true;
9518 }
9519 rc = pMediumLockList->Update(parent, false);
9520 AssertComRC(rc);
9521 rc = pMediumLockList->Append(pMedium, true);
9522 AssertComRC(rc);
9523 }
9524 }
9525
9526 continue;
9527 }
9528
9529 if (pMedium)
9530 {
9531 /* was this medium attached before? */
9532 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9533 oldIt != oldAtts.end();
9534 ++oldIt)
9535 {
9536 MediumAttachment *pOldAttach = *oldIt;
9537 if (pOldAttach->getMedium() == pMedium)
9538 {
9539 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9540
9541 /* yes: remove from old to avoid de-association */
9542 oldAtts.erase(oldIt);
9543 break;
9544 }
9545 }
9546 }
9547 }
9548
9549 /* enumerate remaining old attachments and de-associate from the
9550 * current machine state */
9551 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9552 it != oldAtts.end();
9553 ++it)
9554 {
9555 MediumAttachment *pAttach = *it;
9556 Medium* pMedium = pAttach->getMedium();
9557
9558 /* Detach only hard disks, since DVD/floppy media is detached
9559 * instantly in MountMedium. */
9560 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9561 {
9562 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9563
9564 /* now de-associate from the current machine state */
9565 rc = pMedium->removeBackReference(mData->mUuid);
9566 AssertComRC(rc);
9567
9568 if (aOnline)
9569 {
9570 /* unlock since medium is not used anymore */
9571 MediumLockList *pMediumLockList;
9572 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9573 AssertComRC(rc);
9574 if (pMediumLockList)
9575 {
9576 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9577 AssertComRC(rc);
9578 }
9579 }
9580 }
9581 }
9582
9583 /* take media locks again so that the locking state is consistent */
9584 if (fMediaNeedsLocking)
9585 {
9586 Assert(aOnline);
9587 rc = mData->mSession.mLockedMedia.Lock();
9588 AssertComRC(rc);
9589 }
9590
9591 /* commit the hard disk changes */
9592 mMediaData.commit();
9593
9594 if (isSessionMachine())
9595 {
9596 /* attach new data to the primary machine and reshare it */
9597 mPeer->mMediaData.attach(mMediaData);
9598 }
9599
9600 return;
9601}
9602
9603/**
9604 * Perform deferred deletion of implicitly created diffs.
9605 *
9606 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9607 * backed up).
9608 *
9609 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9610 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9611 *
9612 * @note Locks this object for writing!
9613 *
9614 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
9615 */
9616void Machine::rollbackMedia()
9617{
9618 AutoCaller autoCaller(this);
9619 AssertComRCReturnVoid (autoCaller.rc());
9620
9621 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9622
9623 LogFlowThisFunc(("Entering\n"));
9624
9625 HRESULT rc = S_OK;
9626
9627 /* no attach/detach operations -- nothing to do */
9628 if (!mMediaData.isBackedUp())
9629 return;
9630
9631 /* enumerate new attachments */
9632 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9633 it != mMediaData->mAttachments.end();
9634 ++it)
9635 {
9636 MediumAttachment *pAttach = *it;
9637 /* Fix up the backrefs for DVD/floppy media. */
9638 if (pAttach->getType() != DeviceType_HardDisk)
9639 {
9640 Medium* pMedium = pAttach->getMedium();
9641 if (pMedium)
9642 {
9643 rc = pMedium->removeBackReference(mData->mUuid);
9644 AssertComRC(rc);
9645 }
9646 }
9647
9648 (*it)->rollback();
9649
9650 pAttach = *it;
9651 /* Fix up the backrefs for DVD/floppy media. */
9652 if (pAttach->getType() != DeviceType_HardDisk)
9653 {
9654 Medium* pMedium = pAttach->getMedium();
9655 if (pMedium)
9656 {
9657 rc = pMedium->addBackReference(mData->mUuid);
9658 AssertComRC(rc);
9659 }
9660 }
9661 }
9662
9663 /** @todo convert all this Machine-based voodoo to MediumAttachment
9664 * based rollback logic. */
9665 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9666 // which gets called if Machine::registeredInit() fails...
9667 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9668
9669 return;
9670}
9671
9672/**
9673 * Returns true if the settings file is located in the directory named exactly
9674 * as the machine; this means, among other things, that the machine directory
9675 * should be auto-renamed.
9676 *
9677 * @param aSettingsDir if not NULL, the full machine settings file directory
9678 * name will be assigned there.
9679 *
9680 * @note Doesn't lock anything.
9681 * @note Not thread safe (must be called from this object's lock).
9682 */
9683bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9684{
9685 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9686 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9687 if (aSettingsDir)
9688 *aSettingsDir = strMachineDirName;
9689 strMachineDirName.stripPath(); // vmname
9690 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9691 strConfigFileOnly.stripPath() // vmname.vbox
9692 .stripExt(); // vmname
9693
9694 AssertReturn(!strMachineDirName.isEmpty(), false);
9695 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9696
9697 return strMachineDirName == strConfigFileOnly;
9698}
9699
9700/**
9701 * Discards all changes to machine settings.
9702 *
9703 * @param aNotify Whether to notify the direct session about changes or not.
9704 *
9705 * @note Locks objects for writing!
9706 */
9707void Machine::rollback(bool aNotify)
9708{
9709 AutoCaller autoCaller(this);
9710 AssertComRCReturn(autoCaller.rc(), (void)0);
9711
9712 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9713
9714 if (!mStorageControllers.isNull())
9715 {
9716 if (mStorageControllers.isBackedUp())
9717 {
9718 /* unitialize all new devices (absent in the backed up list). */
9719 StorageControllerList::const_iterator it = mStorageControllers->begin();
9720 StorageControllerList *backedList = mStorageControllers.backedUpData();
9721 while (it != mStorageControllers->end())
9722 {
9723 if ( std::find(backedList->begin(), backedList->end(), *it)
9724 == backedList->end()
9725 )
9726 {
9727 (*it)->uninit();
9728 }
9729 ++it;
9730 }
9731
9732 /* restore the list */
9733 mStorageControllers.rollback();
9734 }
9735
9736 /* rollback any changes to devices after restoring the list */
9737 if (mData->flModifications & IsModified_Storage)
9738 {
9739 StorageControllerList::const_iterator it = mStorageControllers->begin();
9740 while (it != mStorageControllers->end())
9741 {
9742 (*it)->rollback();
9743 ++it;
9744 }
9745 }
9746 }
9747
9748 mUserData.rollback();
9749
9750 mHWData.rollback();
9751
9752 if (mData->flModifications & IsModified_Storage)
9753 rollbackMedia();
9754
9755 if (mBIOSSettings)
9756 mBIOSSettings->rollback();
9757
9758 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9759 mVRDEServer->rollback();
9760
9761 if (mAudioAdapter)
9762 mAudioAdapter->rollback();
9763
9764 if (mUSBController && (mData->flModifications & IsModified_USB))
9765 mUSBController->rollback();
9766
9767 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
9768 mBandwidthControl->rollback();
9769
9770 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9771 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9772 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9773
9774 if (mData->flModifications & IsModified_NetworkAdapters)
9775 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9776 if ( mNetworkAdapters[slot]
9777 && mNetworkAdapters[slot]->isModified())
9778 {
9779 mNetworkAdapters[slot]->rollback();
9780 networkAdapters[slot] = mNetworkAdapters[slot];
9781 }
9782
9783 if (mData->flModifications & IsModified_SerialPorts)
9784 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9785 if ( mSerialPorts[slot]
9786 && mSerialPorts[slot]->isModified())
9787 {
9788 mSerialPorts[slot]->rollback();
9789 serialPorts[slot] = mSerialPorts[slot];
9790 }
9791
9792 if (mData->flModifications & IsModified_ParallelPorts)
9793 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9794 if ( mParallelPorts[slot]
9795 && mParallelPorts[slot]->isModified())
9796 {
9797 mParallelPorts[slot]->rollback();
9798 parallelPorts[slot] = mParallelPorts[slot];
9799 }
9800
9801 if (aNotify)
9802 {
9803 /* inform the direct session about changes */
9804
9805 ComObjPtr<Machine> that = this;
9806 uint32_t flModifications = mData->flModifications;
9807 alock.leave();
9808
9809 if (flModifications & IsModified_SharedFolders)
9810 that->onSharedFolderChange();
9811
9812 if (flModifications & IsModified_VRDEServer)
9813 that->onVRDEServerChange(/* aRestart */ TRUE);
9814 if (flModifications & IsModified_USB)
9815 that->onUSBControllerChange();
9816
9817 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9818 if (networkAdapters[slot])
9819 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9820 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9821 if (serialPorts[slot])
9822 that->onSerialPortChange(serialPorts[slot]);
9823 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9824 if (parallelPorts[slot])
9825 that->onParallelPortChange(parallelPorts[slot]);
9826
9827 if (flModifications & IsModified_Storage)
9828 that->onStorageControllerChange();
9829
9830#if 0
9831 if (flModifications & IsModified_BandwidthControl)
9832 that->onBandwidthControlChange();
9833#endif
9834 }
9835}
9836
9837/**
9838 * Commits all the changes to machine settings.
9839 *
9840 * Note that this operation is supposed to never fail.
9841 *
9842 * @note Locks this object and children for writing.
9843 */
9844void Machine::commit()
9845{
9846 AutoCaller autoCaller(this);
9847 AssertComRCReturnVoid(autoCaller.rc());
9848
9849 AutoCaller peerCaller(mPeer);
9850 AssertComRCReturnVoid(peerCaller.rc());
9851
9852 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9853
9854 /*
9855 * use safe commit to ensure Snapshot machines (that share mUserData)
9856 * will still refer to a valid memory location
9857 */
9858 mUserData.commitCopy();
9859
9860 mHWData.commit();
9861
9862 if (mMediaData.isBackedUp())
9863 commitMedia();
9864
9865 mBIOSSettings->commit();
9866 mVRDEServer->commit();
9867 mAudioAdapter->commit();
9868 mUSBController->commit();
9869 mBandwidthControl->commit();
9870
9871 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9872 mNetworkAdapters[slot]->commit();
9873 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9874 mSerialPorts[slot]->commit();
9875 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9876 mParallelPorts[slot]->commit();
9877
9878 bool commitStorageControllers = false;
9879
9880 if (mStorageControllers.isBackedUp())
9881 {
9882 mStorageControllers.commit();
9883
9884 if (mPeer)
9885 {
9886 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9887
9888 /* Commit all changes to new controllers (this will reshare data with
9889 * peers for those who have peers) */
9890 StorageControllerList *newList = new StorageControllerList();
9891 StorageControllerList::const_iterator it = mStorageControllers->begin();
9892 while (it != mStorageControllers->end())
9893 {
9894 (*it)->commit();
9895
9896 /* look if this controller has a peer device */
9897 ComObjPtr<StorageController> peer = (*it)->getPeer();
9898 if (!peer)
9899 {
9900 /* no peer means the device is a newly created one;
9901 * create a peer owning data this device share it with */
9902 peer.createObject();
9903 peer->init(mPeer, *it, true /* aReshare */);
9904 }
9905 else
9906 {
9907 /* remove peer from the old list */
9908 mPeer->mStorageControllers->remove(peer);
9909 }
9910 /* and add it to the new list */
9911 newList->push_back(peer);
9912
9913 ++it;
9914 }
9915
9916 /* uninit old peer's controllers that are left */
9917 it = mPeer->mStorageControllers->begin();
9918 while (it != mPeer->mStorageControllers->end())
9919 {
9920 (*it)->uninit();
9921 ++it;
9922 }
9923
9924 /* attach new list of controllers to our peer */
9925 mPeer->mStorageControllers.attach(newList);
9926 }
9927 else
9928 {
9929 /* we have no peer (our parent is the newly created machine);
9930 * just commit changes to devices */
9931 commitStorageControllers = true;
9932 }
9933 }
9934 else
9935 {
9936 /* the list of controllers itself is not changed,
9937 * just commit changes to controllers themselves */
9938 commitStorageControllers = true;
9939 }
9940
9941 if (commitStorageControllers)
9942 {
9943 StorageControllerList::const_iterator it = mStorageControllers->begin();
9944 while (it != mStorageControllers->end())
9945 {
9946 (*it)->commit();
9947 ++it;
9948 }
9949 }
9950
9951 if (isSessionMachine())
9952 {
9953 /* attach new data to the primary machine and reshare it */
9954 mPeer->mUserData.attach(mUserData);
9955 mPeer->mHWData.attach(mHWData);
9956 /* mMediaData is reshared by fixupMedia */
9957 // mPeer->mMediaData.attach(mMediaData);
9958 Assert(mPeer->mMediaData.data() == mMediaData.data());
9959 }
9960}
9961
9962/**
9963 * Copies all the hardware data from the given machine.
9964 *
9965 * Currently, only called when the VM is being restored from a snapshot. In
9966 * particular, this implies that the VM is not running during this method's
9967 * call.
9968 *
9969 * @note This method must be called from under this object's lock.
9970 *
9971 * @note This method doesn't call #commit(), so all data remains backed up and
9972 * unsaved.
9973 */
9974void Machine::copyFrom(Machine *aThat)
9975{
9976 AssertReturnVoid(!isSnapshotMachine());
9977 AssertReturnVoid(aThat->isSnapshotMachine());
9978
9979 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9980
9981 mHWData.assignCopy(aThat->mHWData);
9982
9983 // create copies of all shared folders (mHWData after attaching a copy
9984 // contains just references to original objects)
9985 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9986 it != mHWData->mSharedFolders.end();
9987 ++it)
9988 {
9989 ComObjPtr<SharedFolder> folder;
9990 folder.createObject();
9991 HRESULT rc = folder->initCopy(getMachine(), *it);
9992 AssertComRC(rc);
9993 *it = folder;
9994 }
9995
9996 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9997 mVRDEServer->copyFrom(aThat->mVRDEServer);
9998 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9999 mUSBController->copyFrom(aThat->mUSBController);
10000 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10001
10002 /* create private copies of all controllers */
10003 mStorageControllers.backup();
10004 mStorageControllers->clear();
10005 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10006 it != aThat->mStorageControllers->end();
10007 ++it)
10008 {
10009 ComObjPtr<StorageController> ctrl;
10010 ctrl.createObject();
10011 ctrl->initCopy(this, *it);
10012 mStorageControllers->push_back(ctrl);
10013 }
10014
10015 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10016 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10017 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10018 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10019 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10020 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10021}
10022
10023#ifdef VBOX_WITH_RESOURCE_USAGE_API
10024
10025void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10026{
10027 AssertReturnVoid(isWriteLockOnCurrentThread());
10028 AssertPtrReturnVoid(aCollector);
10029
10030 pm::CollectorHAL *hal = aCollector->getHAL();
10031 /* Create sub metrics */
10032 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10033 "Percentage of processor time spent in user mode by the VM process.");
10034 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10035 "Percentage of processor time spent in kernel mode by the VM process.");
10036 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10037 "Size of resident portion of VM process in memory.");
10038 /* Create and register base metrics */
10039 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10040 cpuLoadUser, cpuLoadKernel);
10041 aCollector->registerBaseMetric(cpuLoad);
10042 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10043 ramUsageUsed);
10044 aCollector->registerBaseMetric(ramUsage);
10045
10046 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10047 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10048 new pm::AggregateAvg()));
10049 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10050 new pm::AggregateMin()));
10051 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10052 new pm::AggregateMax()));
10053 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10054 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10055 new pm::AggregateAvg()));
10056 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10057 new pm::AggregateMin()));
10058 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10059 new pm::AggregateMax()));
10060
10061 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10062 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10063 new pm::AggregateAvg()));
10064 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10065 new pm::AggregateMin()));
10066 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10067 new pm::AggregateMax()));
10068
10069
10070 /* Guest metrics collector */
10071 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10072 aCollector->registerGuest(mCollectorGuest);
10073 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10074 this, __PRETTY_FUNCTION__, mCollectorGuest));
10075
10076 /* Create sub metrics */
10077 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10078 "Percentage of processor time spent in user mode as seen by the guest.");
10079 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10080 "Percentage of processor time spent in kernel mode as seen by the guest.");
10081 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10082 "Percentage of processor time spent idling as seen by the guest.");
10083
10084 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10085 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10086 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10087 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10088 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10089 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10090
10091 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10092
10093 /* Create and register base metrics */
10094 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10095 guestLoadUser, guestLoadKernel, guestLoadIdle);
10096 aCollector->registerBaseMetric(guestCpuLoad);
10097
10098 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10099 guestMemTotal, guestMemFree,
10100 guestMemBalloon, guestMemShared,
10101 guestMemCache, guestPagedTotal);
10102 aCollector->registerBaseMetric(guestCpuMem);
10103
10104 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10105 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10106 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10107 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
10108
10109 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
10110 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
10111 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
10112 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
10113
10114 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
10115 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
10116 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
10117 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
10118
10119 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
10120 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
10121 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
10122 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
10123
10124 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
10125 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
10126 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
10127 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
10128
10129 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
10130 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
10131 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
10132 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
10133
10134 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
10135 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
10136 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
10137 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
10138
10139 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
10140 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
10141 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
10142 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
10143
10144 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
10145 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
10146 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
10147 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
10148}
10149
10150void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
10151{
10152 AssertReturnVoid(isWriteLockOnCurrentThread());
10153
10154 if (aCollector)
10155 {
10156 aCollector->unregisterMetricsFor(aMachine);
10157 aCollector->unregisterBaseMetricsFor(aMachine);
10158 }
10159}
10160
10161#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10162
10163
10164////////////////////////////////////////////////////////////////////////////////
10165
10166DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
10167
10168HRESULT SessionMachine::FinalConstruct()
10169{
10170 LogFlowThisFunc(("\n"));
10171
10172#if defined(RT_OS_WINDOWS)
10173 mIPCSem = NULL;
10174#elif defined(RT_OS_OS2)
10175 mIPCSem = NULLHANDLE;
10176#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10177 mIPCSem = -1;
10178#else
10179# error "Port me!"
10180#endif
10181
10182 return BaseFinalConstruct();
10183}
10184
10185void SessionMachine::FinalRelease()
10186{
10187 LogFlowThisFunc(("\n"));
10188
10189 uninit(Uninit::Unexpected);
10190
10191 BaseFinalRelease();
10192}
10193
10194/**
10195 * @note Must be called only by Machine::openSession() from its own write lock.
10196 */
10197HRESULT SessionMachine::init(Machine *aMachine)
10198{
10199 LogFlowThisFuncEnter();
10200 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10201
10202 AssertReturn(aMachine, E_INVALIDARG);
10203
10204 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10205
10206 /* Enclose the state transition NotReady->InInit->Ready */
10207 AutoInitSpan autoInitSpan(this);
10208 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10209
10210 /* create the interprocess semaphore */
10211#if defined(RT_OS_WINDOWS)
10212 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10213 for (size_t i = 0; i < mIPCSemName.length(); i++)
10214 if (mIPCSemName.raw()[i] == '\\')
10215 mIPCSemName.raw()[i] = '/';
10216 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10217 ComAssertMsgRet(mIPCSem,
10218 ("Cannot create IPC mutex '%ls', err=%d",
10219 mIPCSemName.raw(), ::GetLastError()),
10220 E_FAIL);
10221#elif defined(RT_OS_OS2)
10222 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10223 aMachine->mData->mUuid.raw());
10224 mIPCSemName = ipcSem;
10225 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10226 ComAssertMsgRet(arc == NO_ERROR,
10227 ("Cannot create IPC mutex '%s', arc=%ld",
10228 ipcSem.c_str(), arc),
10229 E_FAIL);
10230#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10231# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10232# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10233 /** @todo Check that this still works correctly. */
10234 AssertCompileSize(key_t, 8);
10235# else
10236 AssertCompileSize(key_t, 4);
10237# endif
10238 key_t key;
10239 mIPCSem = -1;
10240 mIPCKey = "0";
10241 for (uint32_t i = 0; i < 1 << 24; i++)
10242 {
10243 key = ((uint32_t)'V' << 24) | i;
10244 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10245 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10246 {
10247 mIPCSem = sem;
10248 if (sem >= 0)
10249 mIPCKey = BstrFmt("%u", key);
10250 break;
10251 }
10252 }
10253# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10254 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10255 char *pszSemName = NULL;
10256 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10257 key_t key = ::ftok(pszSemName, 'V');
10258 RTStrFree(pszSemName);
10259
10260 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10261# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10262
10263 int errnoSave = errno;
10264 if (mIPCSem < 0 && errnoSave == ENOSYS)
10265 {
10266 setError(E_FAIL,
10267 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10268 "support for SysV IPC. Check the host kernel configuration for "
10269 "CONFIG_SYSVIPC=y"));
10270 return E_FAIL;
10271 }
10272 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10273 * the IPC semaphores */
10274 if (mIPCSem < 0 && errnoSave == ENOSPC)
10275 {
10276#ifdef RT_OS_LINUX
10277 setError(E_FAIL,
10278 tr("Cannot create IPC semaphore because the system limit for the "
10279 "maximum number of semaphore sets (SEMMNI), or the system wide "
10280 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10281 "current set of SysV IPC semaphores can be determined from "
10282 "the file /proc/sysvipc/sem"));
10283#else
10284 setError(E_FAIL,
10285 tr("Cannot create IPC semaphore because the system-imposed limit "
10286 "on the maximum number of allowed semaphores or semaphore "
10287 "identifiers system-wide would be exceeded"));
10288#endif
10289 return E_FAIL;
10290 }
10291 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10292 E_FAIL);
10293 /* set the initial value to 1 */
10294 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10295 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10296 E_FAIL);
10297#else
10298# error "Port me!"
10299#endif
10300
10301 /* memorize the peer Machine */
10302 unconst(mPeer) = aMachine;
10303 /* share the parent pointer */
10304 unconst(mParent) = aMachine->mParent;
10305
10306 /* take the pointers to data to share */
10307 mData.share(aMachine->mData);
10308 mSSData.share(aMachine->mSSData);
10309
10310 mUserData.share(aMachine->mUserData);
10311 mHWData.share(aMachine->mHWData);
10312 mMediaData.share(aMachine->mMediaData);
10313
10314 mStorageControllers.allocate();
10315 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10316 it != aMachine->mStorageControllers->end();
10317 ++it)
10318 {
10319 ComObjPtr<StorageController> ctl;
10320 ctl.createObject();
10321 ctl->init(this, *it);
10322 mStorageControllers->push_back(ctl);
10323 }
10324
10325 unconst(mBIOSSettings).createObject();
10326 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10327 /* create another VRDEServer object that will be mutable */
10328 unconst(mVRDEServer).createObject();
10329 mVRDEServer->init(this, aMachine->mVRDEServer);
10330 /* create another audio adapter object that will be mutable */
10331 unconst(mAudioAdapter).createObject();
10332 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10333 /* create a list of serial ports that will be mutable */
10334 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10335 {
10336 unconst(mSerialPorts[slot]).createObject();
10337 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10338 }
10339 /* create a list of parallel ports that will be mutable */
10340 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10341 {
10342 unconst(mParallelPorts[slot]).createObject();
10343 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10344 }
10345 /* create another USB controller object that will be mutable */
10346 unconst(mUSBController).createObject();
10347 mUSBController->init(this, aMachine->mUSBController);
10348
10349 /* create a list of network adapters that will be mutable */
10350 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10351 {
10352 unconst(mNetworkAdapters[slot]).createObject();
10353 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10354 }
10355
10356 /* create another bandwidth control object that will be mutable */
10357 unconst(mBandwidthControl).createObject();
10358 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10359
10360 /* default is to delete saved state on Saved -> PoweredOff transition */
10361 mRemoveSavedState = true;
10362
10363 /* Confirm a successful initialization when it's the case */
10364 autoInitSpan.setSucceeded();
10365
10366 LogFlowThisFuncLeave();
10367 return S_OK;
10368}
10369
10370/**
10371 * Uninitializes this session object. If the reason is other than
10372 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10373 *
10374 * @param aReason uninitialization reason
10375 *
10376 * @note Locks mParent + this object for writing.
10377 */
10378void SessionMachine::uninit(Uninit::Reason aReason)
10379{
10380 LogFlowThisFuncEnter();
10381 LogFlowThisFunc(("reason=%d\n", aReason));
10382
10383 /*
10384 * Strongly reference ourselves to prevent this object deletion after
10385 * mData->mSession.mMachine.setNull() below (which can release the last
10386 * reference and call the destructor). Important: this must be done before
10387 * accessing any members (and before AutoUninitSpan that does it as well).
10388 * This self reference will be released as the very last step on return.
10389 */
10390 ComObjPtr<SessionMachine> selfRef = this;
10391
10392 /* Enclose the state transition Ready->InUninit->NotReady */
10393 AutoUninitSpan autoUninitSpan(this);
10394 if (autoUninitSpan.uninitDone())
10395 {
10396 LogFlowThisFunc(("Already uninitialized\n"));
10397 LogFlowThisFuncLeave();
10398 return;
10399 }
10400
10401 if (autoUninitSpan.initFailed())
10402 {
10403 /* We've been called by init() because it's failed. It's not really
10404 * necessary (nor it's safe) to perform the regular uninit sequence
10405 * below, the following is enough.
10406 */
10407 LogFlowThisFunc(("Initialization failed.\n"));
10408#if defined(RT_OS_WINDOWS)
10409 if (mIPCSem)
10410 ::CloseHandle(mIPCSem);
10411 mIPCSem = NULL;
10412#elif defined(RT_OS_OS2)
10413 if (mIPCSem != NULLHANDLE)
10414 ::DosCloseMutexSem(mIPCSem);
10415 mIPCSem = NULLHANDLE;
10416#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10417 if (mIPCSem >= 0)
10418 ::semctl(mIPCSem, 0, IPC_RMID);
10419 mIPCSem = -1;
10420# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10421 mIPCKey = "0";
10422# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10423#else
10424# error "Port me!"
10425#endif
10426 uninitDataAndChildObjects();
10427 mData.free();
10428 unconst(mParent) = NULL;
10429 unconst(mPeer) = NULL;
10430 LogFlowThisFuncLeave();
10431 return;
10432 }
10433
10434 MachineState_T lastState;
10435 {
10436 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10437 lastState = mData->mMachineState;
10438 }
10439 NOREF(lastState);
10440
10441#ifdef VBOX_WITH_USB
10442 // release all captured USB devices, but do this before requesting the locks below
10443 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10444 {
10445 /* Console::captureUSBDevices() is called in the VM process only after
10446 * setting the machine state to Starting or Restoring.
10447 * Console::detachAllUSBDevices() will be called upon successful
10448 * termination. So, we need to release USB devices only if there was
10449 * an abnormal termination of a running VM.
10450 *
10451 * This is identical to SessionMachine::DetachAllUSBDevices except
10452 * for the aAbnormal argument. */
10453 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10454 AssertComRC(rc);
10455 NOREF(rc);
10456
10457 USBProxyService *service = mParent->host()->usbProxyService();
10458 if (service)
10459 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10460 }
10461#endif /* VBOX_WITH_USB */
10462
10463 // we need to lock this object in uninit() because the lock is shared
10464 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10465 // and others need mParent lock, and USB needs host lock.
10466 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10467
10468 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10469 this, __PRETTY_FUNCTION__, mCollectorGuest));
10470 if (mCollectorGuest)
10471 {
10472 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
10473 delete mCollectorGuest;
10474 mCollectorGuest = NULL;
10475 }
10476 // Trigger async cleanup tasks, avoid doing things here which are not
10477 // vital to be done immediately and maybe need more locks. This calls
10478 // Machine::unregisterMetrics().
10479 mParent->onMachineUninit(mPeer);
10480
10481 if (aReason == Uninit::Abnormal)
10482 {
10483 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10484 Global::IsOnlineOrTransient(lastState)));
10485
10486 /* reset the state to Aborted */
10487 if (mData->mMachineState != MachineState_Aborted)
10488 setMachineState(MachineState_Aborted);
10489 }
10490
10491 // any machine settings modified?
10492 if (mData->flModifications)
10493 {
10494 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10495 rollback(false /* aNotify */);
10496 }
10497
10498 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
10499 || !mConsoleTaskData.mSnapshot);
10500 if (!mConsoleTaskData.strStateFilePath.isEmpty())
10501 {
10502 LogWarningThisFunc(("canceling failed save state request!\n"));
10503 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10504 }
10505 else if (!mConsoleTaskData.mSnapshot.isNull())
10506 {
10507 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10508
10509 /* delete all differencing hard disks created (this will also attach
10510 * their parents back by rolling back mMediaData) */
10511 rollbackMedia();
10512
10513 // delete the saved state file (it might have been already created)
10514 // AFTER killing the snapshot so that releaseSavedStateFile() won't
10515 // think it's still in use
10516 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
10517 mConsoleTaskData.mSnapshot->uninit();
10518 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
10519 }
10520
10521 if (!mData->mSession.mType.isEmpty())
10522 {
10523 /* mType is not null when this machine's process has been started by
10524 * Machine::launchVMProcess(), therefore it is our child. We
10525 * need to queue the PID to reap the process (and avoid zombies on
10526 * Linux). */
10527 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10528 mParent->addProcessToReap(mData->mSession.mPid);
10529 }
10530
10531 mData->mSession.mPid = NIL_RTPROCESS;
10532
10533 if (aReason == Uninit::Unexpected)
10534 {
10535 /* Uninitialization didn't come from #checkForDeath(), so tell the
10536 * client watcher thread to update the set of machines that have open
10537 * sessions. */
10538 mParent->updateClientWatcher();
10539 }
10540
10541 /* uninitialize all remote controls */
10542 if (mData->mSession.mRemoteControls.size())
10543 {
10544 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10545 mData->mSession.mRemoteControls.size()));
10546
10547 Data::Session::RemoteControlList::iterator it =
10548 mData->mSession.mRemoteControls.begin();
10549 while (it != mData->mSession.mRemoteControls.end())
10550 {
10551 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10552 HRESULT rc = (*it)->Uninitialize();
10553 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10554 if (FAILED(rc))
10555 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10556 ++it;
10557 }
10558 mData->mSession.mRemoteControls.clear();
10559 }
10560
10561 /*
10562 * An expected uninitialization can come only from #checkForDeath().
10563 * Otherwise it means that something's gone really wrong (for example,
10564 * the Session implementation has released the VirtualBox reference
10565 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10566 * etc). However, it's also possible, that the client releases the IPC
10567 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10568 * but the VirtualBox release event comes first to the server process.
10569 * This case is practically possible, so we should not assert on an
10570 * unexpected uninit, just log a warning.
10571 */
10572
10573 if ((aReason == Uninit::Unexpected))
10574 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10575
10576 if (aReason != Uninit::Normal)
10577 {
10578 mData->mSession.mDirectControl.setNull();
10579 }
10580 else
10581 {
10582 /* this must be null here (see #OnSessionEnd()) */
10583 Assert(mData->mSession.mDirectControl.isNull());
10584 Assert(mData->mSession.mState == SessionState_Unlocking);
10585 Assert(!mData->mSession.mProgress.isNull());
10586 }
10587 if (mData->mSession.mProgress)
10588 {
10589 if (aReason == Uninit::Normal)
10590 mData->mSession.mProgress->notifyComplete(S_OK);
10591 else
10592 mData->mSession.mProgress->notifyComplete(E_FAIL,
10593 COM_IIDOF(ISession),
10594 getComponentName(),
10595 tr("The VM session was aborted"));
10596 mData->mSession.mProgress.setNull();
10597 }
10598
10599 /* remove the association between the peer machine and this session machine */
10600 Assert( (SessionMachine*)mData->mSession.mMachine == this
10601 || aReason == Uninit::Unexpected);
10602
10603 /* reset the rest of session data */
10604 mData->mSession.mMachine.setNull();
10605 mData->mSession.mState = SessionState_Unlocked;
10606 mData->mSession.mType.setNull();
10607
10608 /* close the interprocess semaphore before leaving the exclusive lock */
10609#if defined(RT_OS_WINDOWS)
10610 if (mIPCSem)
10611 ::CloseHandle(mIPCSem);
10612 mIPCSem = NULL;
10613#elif defined(RT_OS_OS2)
10614 if (mIPCSem != NULLHANDLE)
10615 ::DosCloseMutexSem(mIPCSem);
10616 mIPCSem = NULLHANDLE;
10617#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10618 if (mIPCSem >= 0)
10619 ::semctl(mIPCSem, 0, IPC_RMID);
10620 mIPCSem = -1;
10621# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10622 mIPCKey = "0";
10623# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10624#else
10625# error "Port me!"
10626#endif
10627
10628 /* fire an event */
10629 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10630
10631 uninitDataAndChildObjects();
10632
10633 /* free the essential data structure last */
10634 mData.free();
10635
10636#if 1 /** @todo Please review this change! (bird) */
10637 /* drop the exclusive lock before setting the below two to NULL */
10638 multilock.release();
10639#else
10640 /* leave the exclusive lock before setting the below two to NULL */
10641 multilock.leave();
10642#endif
10643
10644 unconst(mParent) = NULL;
10645 unconst(mPeer) = NULL;
10646
10647 LogFlowThisFuncLeave();
10648}
10649
10650// util::Lockable interface
10651////////////////////////////////////////////////////////////////////////////////
10652
10653/**
10654 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10655 * with the primary Machine instance (mPeer).
10656 */
10657RWLockHandle *SessionMachine::lockHandle() const
10658{
10659 AssertReturn(mPeer != NULL, NULL);
10660 return mPeer->lockHandle();
10661}
10662
10663// IInternalMachineControl methods
10664////////////////////////////////////////////////////////////////////////////////
10665
10666/**
10667 * @note Locks this object for writing.
10668 */
10669STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10670{
10671 AutoCaller autoCaller(this);
10672 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10673
10674 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10675
10676 mRemoveSavedState = aRemove;
10677
10678 return S_OK;
10679}
10680
10681/**
10682 * @note Locks the same as #setMachineState() does.
10683 */
10684STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10685{
10686 return setMachineState(aMachineState);
10687}
10688
10689/**
10690 * @note Locks this object for reading.
10691 */
10692STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10693{
10694 AutoCaller autoCaller(this);
10695 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10696
10697 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10698
10699#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10700 mIPCSemName.cloneTo(aId);
10701 return S_OK;
10702#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10703# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10704 mIPCKey.cloneTo(aId);
10705# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10706 mData->m_strConfigFileFull.cloneTo(aId);
10707# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10708 return S_OK;
10709#else
10710# error "Port me!"
10711#endif
10712}
10713
10714/**
10715 * @note Locks this object for writing.
10716 */
10717STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10718{
10719 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10720 AutoCaller autoCaller(this);
10721 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10722
10723 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10724
10725 if (mData->mSession.mState != SessionState_Locked)
10726 return VBOX_E_INVALID_OBJECT_STATE;
10727
10728 if (!mData->mSession.mProgress.isNull())
10729 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10730
10731 LogFlowThisFunc(("returns S_OK.\n"));
10732 return S_OK;
10733}
10734
10735/**
10736 * @note Locks this object for writing.
10737 */
10738STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10739{
10740 AutoCaller autoCaller(this);
10741 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10742
10743 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10744
10745 if (mData->mSession.mState != SessionState_Locked)
10746 return VBOX_E_INVALID_OBJECT_STATE;
10747
10748 /* Finalize the openRemoteSession progress object. */
10749 if (mData->mSession.mProgress)
10750 {
10751 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10752 mData->mSession.mProgress.setNull();
10753 }
10754
10755 if (SUCCEEDED((HRESULT)iResult))
10756 {
10757#ifdef VBOX_WITH_RESOURCE_USAGE_API
10758 /* The VM has been powered up successfully, so it makes sense
10759 * now to offer the performance metrics for a running machine
10760 * object. Doing it earlier wouldn't be safe. */
10761 registerMetrics(mParent->performanceCollector(), mPeer,
10762 mData->mSession.mPid);
10763#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10764 }
10765
10766 return S_OK;
10767}
10768
10769/**
10770 * @note Locks this object for writing.
10771 */
10772STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
10773{
10774 LogFlowThisFuncEnter();
10775
10776 CheckComArgOutPointerValid(aProgress);
10777
10778 AutoCaller autoCaller(this);
10779 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10780
10781 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10782
10783 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
10784 E_FAIL);
10785
10786 /* create a progress object to track operation completion */
10787 ComObjPtr<Progress> pProgress;
10788 pProgress.createObject();
10789 pProgress->init(getVirtualBox(),
10790 static_cast<IMachine *>(this) /* aInitiator */,
10791 Bstr(tr("Stopping the virtual machine")).raw(),
10792 FALSE /* aCancelable */);
10793
10794 /* fill in the console task data */
10795 mConsoleTaskData.mLastState = mData->mMachineState;
10796 mConsoleTaskData.mProgress = pProgress;
10797
10798 /* set the state to Stopping (this is expected by Console::PowerDown()) */
10799 setMachineState(MachineState_Stopping);
10800
10801 pProgress.queryInterfaceTo(aProgress);
10802
10803 return S_OK;
10804}
10805
10806/**
10807 * @note Locks this object for writing.
10808 */
10809STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
10810{
10811 LogFlowThisFuncEnter();
10812
10813 AutoCaller autoCaller(this);
10814 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10815
10816 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10817
10818 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
10819 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
10820 && mConsoleTaskData.mLastState != MachineState_Null,
10821 E_FAIL);
10822
10823 /*
10824 * On failure, set the state to the state we had when BeginPoweringDown()
10825 * was called (this is expected by Console::PowerDown() and the associated
10826 * task). On success the VM process already changed the state to
10827 * MachineState_PoweredOff, so no need to do anything.
10828 */
10829 if (FAILED(iResult))
10830 setMachineState(mConsoleTaskData.mLastState);
10831
10832 /* notify the progress object about operation completion */
10833 Assert(mConsoleTaskData.mProgress);
10834 if (SUCCEEDED(iResult))
10835 mConsoleTaskData.mProgress->notifyComplete(S_OK);
10836 else
10837 {
10838 Utf8Str strErrMsg(aErrMsg);
10839 if (strErrMsg.length())
10840 mConsoleTaskData.mProgress->notifyComplete(iResult,
10841 COM_IIDOF(ISession),
10842 getComponentName(),
10843 strErrMsg.c_str());
10844 else
10845 mConsoleTaskData.mProgress->notifyComplete(iResult);
10846 }
10847
10848 /* clear out the temporary saved state data */
10849 mConsoleTaskData.mLastState = MachineState_Null;
10850 mConsoleTaskData.mProgress.setNull();
10851
10852 LogFlowThisFuncLeave();
10853 return S_OK;
10854}
10855
10856
10857/**
10858 * Goes through the USB filters of the given machine to see if the given
10859 * device matches any filter or not.
10860 *
10861 * @note Locks the same as USBController::hasMatchingFilter() does.
10862 */
10863STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10864 BOOL *aMatched,
10865 ULONG *aMaskedIfs)
10866{
10867 LogFlowThisFunc(("\n"));
10868
10869 CheckComArgNotNull(aUSBDevice);
10870 CheckComArgOutPointerValid(aMatched);
10871
10872 AutoCaller autoCaller(this);
10873 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10874
10875#ifdef VBOX_WITH_USB
10876 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10877#else
10878 NOREF(aUSBDevice);
10879 NOREF(aMaskedIfs);
10880 *aMatched = FALSE;
10881#endif
10882
10883 return S_OK;
10884}
10885
10886/**
10887 * @note Locks the same as Host::captureUSBDevice() does.
10888 */
10889STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10890{
10891 LogFlowThisFunc(("\n"));
10892
10893 AutoCaller autoCaller(this);
10894 AssertComRCReturnRC(autoCaller.rc());
10895
10896#ifdef VBOX_WITH_USB
10897 /* if captureDeviceForVM() fails, it must have set extended error info */
10898 MultiResult rc = mParent->host()->checkUSBProxyService();
10899 if (FAILED(rc)) return rc;
10900
10901 USBProxyService *service = mParent->host()->usbProxyService();
10902 AssertReturn(service, E_FAIL);
10903 return service->captureDeviceForVM(this, Guid(aId).ref());
10904#else
10905 NOREF(aId);
10906 return E_NOTIMPL;
10907#endif
10908}
10909
10910/**
10911 * @note Locks the same as Host::detachUSBDevice() does.
10912 */
10913STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10914{
10915 LogFlowThisFunc(("\n"));
10916
10917 AutoCaller autoCaller(this);
10918 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10919
10920#ifdef VBOX_WITH_USB
10921 USBProxyService *service = mParent->host()->usbProxyService();
10922 AssertReturn(service, E_FAIL);
10923 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10924#else
10925 NOREF(aId);
10926 NOREF(aDone);
10927 return E_NOTIMPL;
10928#endif
10929}
10930
10931/**
10932 * Inserts all machine filters to the USB proxy service and then calls
10933 * Host::autoCaptureUSBDevices().
10934 *
10935 * Called by Console from the VM process upon VM startup.
10936 *
10937 * @note Locks what called methods lock.
10938 */
10939STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10940{
10941 LogFlowThisFunc(("\n"));
10942
10943 AutoCaller autoCaller(this);
10944 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10945
10946#ifdef VBOX_WITH_USB
10947 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10948 AssertComRC(rc);
10949 NOREF(rc);
10950
10951 USBProxyService *service = mParent->host()->usbProxyService();
10952 AssertReturn(service, E_FAIL);
10953 return service->autoCaptureDevicesForVM(this);
10954#else
10955 return S_OK;
10956#endif
10957}
10958
10959/**
10960 * Removes all machine filters from the USB proxy service and then calls
10961 * Host::detachAllUSBDevices().
10962 *
10963 * Called by Console from the VM process upon normal VM termination or by
10964 * SessionMachine::uninit() upon abnormal VM termination (from under the
10965 * Machine/SessionMachine lock).
10966 *
10967 * @note Locks what called methods lock.
10968 */
10969STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10970{
10971 LogFlowThisFunc(("\n"));
10972
10973 AutoCaller autoCaller(this);
10974 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10975
10976#ifdef VBOX_WITH_USB
10977 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10978 AssertComRC(rc);
10979 NOREF(rc);
10980
10981 USBProxyService *service = mParent->host()->usbProxyService();
10982 AssertReturn(service, E_FAIL);
10983 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10984#else
10985 NOREF(aDone);
10986 return S_OK;
10987#endif
10988}
10989
10990/**
10991 * @note Locks this object for writing.
10992 */
10993STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10994 IProgress **aProgress)
10995{
10996 LogFlowThisFuncEnter();
10997
10998 AssertReturn(aSession, E_INVALIDARG);
10999 AssertReturn(aProgress, E_INVALIDARG);
11000
11001 AutoCaller autoCaller(this);
11002
11003 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11004 /*
11005 * We don't assert below because it might happen that a non-direct session
11006 * informs us it is closed right after we've been uninitialized -- it's ok.
11007 */
11008 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11009
11010 /* get IInternalSessionControl interface */
11011 ComPtr<IInternalSessionControl> control(aSession);
11012
11013 ComAssertRet(!control.isNull(), E_INVALIDARG);
11014
11015 /* Creating a Progress object requires the VirtualBox lock, and
11016 * thus locking it here is required by the lock order rules. */
11017 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
11018
11019 if (control == mData->mSession.mDirectControl)
11020 {
11021 ComAssertRet(aProgress, E_POINTER);
11022
11023 /* The direct session is being normally closed by the client process
11024 * ----------------------------------------------------------------- */
11025
11026 /* go to the closing state (essential for all open*Session() calls and
11027 * for #checkForDeath()) */
11028 Assert(mData->mSession.mState == SessionState_Locked);
11029 mData->mSession.mState = SessionState_Unlocking;
11030
11031 /* set direct control to NULL to release the remote instance */
11032 mData->mSession.mDirectControl.setNull();
11033 LogFlowThisFunc(("Direct control is set to NULL\n"));
11034
11035 if (mData->mSession.mProgress)
11036 {
11037 /* finalize the progress, someone might wait if a frontend
11038 * closes the session before powering on the VM. */
11039 mData->mSession.mProgress->notifyComplete(E_FAIL,
11040 COM_IIDOF(ISession),
11041 getComponentName(),
11042 tr("The VM session was closed before any attempt to power it on"));
11043 mData->mSession.mProgress.setNull();
11044 }
11045
11046 /* Create the progress object the client will use to wait until
11047 * #checkForDeath() is called to uninitialize this session object after
11048 * it releases the IPC semaphore.
11049 * Note! Because we're "reusing" mProgress here, this must be a proxy
11050 * object just like for openRemoteSession. */
11051 Assert(mData->mSession.mProgress.isNull());
11052 ComObjPtr<ProgressProxy> progress;
11053 progress.createObject();
11054 ComPtr<IUnknown> pPeer(mPeer);
11055 progress->init(mParent, pPeer,
11056 Bstr(tr("Closing session")).raw(),
11057 FALSE /* aCancelable */);
11058 progress.queryInterfaceTo(aProgress);
11059 mData->mSession.mProgress = progress;
11060 }
11061 else
11062 {
11063 /* the remote session is being normally closed */
11064 Data::Session::RemoteControlList::iterator it =
11065 mData->mSession.mRemoteControls.begin();
11066 while (it != mData->mSession.mRemoteControls.end())
11067 {
11068 if (control == *it)
11069 break;
11070 ++it;
11071 }
11072 BOOL found = it != mData->mSession.mRemoteControls.end();
11073 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11074 E_INVALIDARG);
11075 mData->mSession.mRemoteControls.remove(*it);
11076 }
11077
11078 LogFlowThisFuncLeave();
11079 return S_OK;
11080}
11081
11082/**
11083 * @note Locks this object for writing.
11084 */
11085STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11086{
11087 LogFlowThisFuncEnter();
11088
11089 CheckComArgOutPointerValid(aProgress);
11090 CheckComArgOutPointerValid(aStateFilePath);
11091
11092 AutoCaller autoCaller(this);
11093 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11094
11095 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11096
11097 AssertReturn( mData->mMachineState == MachineState_Paused
11098 && mConsoleTaskData.mLastState == MachineState_Null
11099 && mConsoleTaskData.strStateFilePath.isEmpty(),
11100 E_FAIL);
11101
11102 /* create a progress object to track operation completion */
11103 ComObjPtr<Progress> pProgress;
11104 pProgress.createObject();
11105 pProgress->init(getVirtualBox(),
11106 static_cast<IMachine *>(this) /* aInitiator */,
11107 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
11108 FALSE /* aCancelable */);
11109
11110 Utf8Str strStateFilePath;
11111 /* stateFilePath is null when the machine is not running */
11112 if (mData->mMachineState == MachineState_Paused)
11113 composeSavedStateFilename(strStateFilePath);
11114
11115 /* fill in the console task data */
11116 mConsoleTaskData.mLastState = mData->mMachineState;
11117 mConsoleTaskData.strStateFilePath = strStateFilePath;
11118 mConsoleTaskData.mProgress = pProgress;
11119
11120 /* set the state to Saving (this is expected by Console::SaveState()) */
11121 setMachineState(MachineState_Saving);
11122
11123 strStateFilePath.cloneTo(aStateFilePath);
11124 pProgress.queryInterfaceTo(aProgress);
11125
11126 return S_OK;
11127}
11128
11129/**
11130 * @note Locks mParent + this object for writing.
11131 */
11132STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
11133{
11134 LogFlowThisFunc(("\n"));
11135
11136 AutoCaller autoCaller(this);
11137 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11138
11139 /* endSavingState() need mParent lock */
11140 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11141
11142 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
11143 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
11144 && mConsoleTaskData.mLastState != MachineState_Null
11145 && !mConsoleTaskData.strStateFilePath.isEmpty(),
11146 E_FAIL);
11147
11148 /*
11149 * On failure, set the state to the state we had when BeginSavingState()
11150 * was called (this is expected by Console::SaveState() and the associated
11151 * task). On success the VM process already changed the state to
11152 * MachineState_Saved, so no need to do anything.
11153 */
11154 if (FAILED(iResult))
11155 setMachineState(mConsoleTaskData.mLastState);
11156
11157 return endSavingState(iResult, aErrMsg);
11158}
11159
11160/**
11161 * @note Locks this object for writing.
11162 */
11163STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
11164{
11165 LogFlowThisFunc(("\n"));
11166
11167 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
11168
11169 AutoCaller autoCaller(this);
11170 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11171
11172 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11173
11174 AssertReturn( mData->mMachineState == MachineState_PoweredOff
11175 || mData->mMachineState == MachineState_Teleported
11176 || mData->mMachineState == MachineState_Aborted
11177 , E_FAIL); /** @todo setError. */
11178
11179 Utf8Str stateFilePathFull = aSavedStateFile;
11180 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
11181 if (RT_FAILURE(vrc))
11182 return setError(VBOX_E_FILE_ERROR,
11183 tr("Invalid saved state file path '%ls' (%Rrc)"),
11184 aSavedStateFile,
11185 vrc);
11186
11187 mSSData->strStateFilePath = stateFilePathFull;
11188
11189 /* The below setMachineState() will detect the state transition and will
11190 * update the settings file */
11191
11192 return setMachineState(MachineState_Saved);
11193}
11194
11195STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
11196 ComSafeArrayOut(BSTR, aValues),
11197 ComSafeArrayOut(LONG64, aTimestamps),
11198 ComSafeArrayOut(BSTR, aFlags))
11199{
11200 LogFlowThisFunc(("\n"));
11201
11202#ifdef VBOX_WITH_GUEST_PROPS
11203 using namespace guestProp;
11204
11205 AutoCaller autoCaller(this);
11206 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11207
11208 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11209
11210 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
11211 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
11212 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
11213 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
11214
11215 size_t cEntries = mHWData->mGuestProperties.size();
11216 com::SafeArray<BSTR> names(cEntries);
11217 com::SafeArray<BSTR> values(cEntries);
11218 com::SafeArray<LONG64> timestamps(cEntries);
11219 com::SafeArray<BSTR> flags(cEntries);
11220 unsigned i = 0;
11221 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
11222 it != mHWData->mGuestProperties.end();
11223 ++it)
11224 {
11225 char szFlags[MAX_FLAGS_LEN + 1];
11226 it->strName.cloneTo(&names[i]);
11227 it->strValue.cloneTo(&values[i]);
11228 timestamps[i] = it->mTimestamp;
11229 /* If it is NULL, keep it NULL. */
11230 if (it->mFlags)
11231 {
11232 writeFlags(it->mFlags, szFlags);
11233 Bstr(szFlags).cloneTo(&flags[i]);
11234 }
11235 else
11236 flags[i] = NULL;
11237 ++i;
11238 }
11239 names.detachTo(ComSafeArrayOutArg(aNames));
11240 values.detachTo(ComSafeArrayOutArg(aValues));
11241 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11242 flags.detachTo(ComSafeArrayOutArg(aFlags));
11243 return S_OK;
11244#else
11245 ReturnComNotImplemented();
11246#endif
11247}
11248
11249STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11250 IN_BSTR aValue,
11251 LONG64 aTimestamp,
11252 IN_BSTR aFlags)
11253{
11254 LogFlowThisFunc(("\n"));
11255
11256#ifdef VBOX_WITH_GUEST_PROPS
11257 using namespace guestProp;
11258
11259 CheckComArgStrNotEmptyOrNull(aName);
11260 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
11261 return E_POINTER; /* aValue can be NULL to indicate deletion */
11262
11263 try
11264 {
11265 /*
11266 * Convert input up front.
11267 */
11268 Utf8Str utf8Name(aName);
11269 uint32_t fFlags = NILFLAG;
11270 if (aFlags)
11271 {
11272 Utf8Str utf8Flags(aFlags);
11273 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11274 AssertRCReturn(vrc, E_INVALIDARG);
11275 }
11276
11277 /*
11278 * Now grab the object lock, validate the state and do the update.
11279 */
11280 AutoCaller autoCaller(this);
11281 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11282
11283 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11284
11285 switch (mData->mMachineState)
11286 {
11287 case MachineState_Paused:
11288 case MachineState_Running:
11289 case MachineState_Teleporting:
11290 case MachineState_TeleportingPausedVM:
11291 case MachineState_LiveSnapshotting:
11292 case MachineState_DeletingSnapshotOnline:
11293 case MachineState_DeletingSnapshotPaused:
11294 case MachineState_Saving:
11295 break;
11296
11297 default:
11298#ifndef DEBUG_sunlover
11299 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11300 VBOX_E_INVALID_VM_STATE);
11301#else
11302 return VBOX_E_INVALID_VM_STATE;
11303#endif
11304 }
11305
11306 setModified(IsModified_MachineData);
11307 mHWData.backup();
11308
11309 /** @todo r=bird: The careful memory handling doesn't work out here because
11310 * the catch block won't undo any damage we've done. So, if push_back throws
11311 * bad_alloc then you've lost the value.
11312 *
11313 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11314 * since values that changes actually bubbles to the end of the list. Using
11315 * something that has an efficient lookup and can tolerate a bit of updates
11316 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11317 * combination of RTStrCache (for sharing names and getting uniqueness into
11318 * the bargain) and hash/tree is another. */
11319 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11320 iter != mHWData->mGuestProperties.end();
11321 ++iter)
11322 if (utf8Name == iter->strName)
11323 {
11324 mHWData->mGuestProperties.erase(iter);
11325 mData->mGuestPropertiesModified = TRUE;
11326 break;
11327 }
11328 if (aValue != NULL)
11329 {
11330 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11331 mHWData->mGuestProperties.push_back(property);
11332 mData->mGuestPropertiesModified = TRUE;
11333 }
11334
11335 /*
11336 * Send a callback notification if appropriate
11337 */
11338 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11339 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11340 RTSTR_MAX,
11341 utf8Name.c_str(),
11342 RTSTR_MAX, NULL)
11343 )
11344 {
11345 alock.leave();
11346
11347 mParent->onGuestPropertyChange(mData->mUuid,
11348 aName,
11349 aValue,
11350 aFlags);
11351 }
11352 }
11353 catch (...)
11354 {
11355 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11356 }
11357 return S_OK;
11358#else
11359 ReturnComNotImplemented();
11360#endif
11361}
11362
11363// public methods only for internal purposes
11364/////////////////////////////////////////////////////////////////////////////
11365
11366/**
11367 * Called from the client watcher thread to check for expected or unexpected
11368 * death of the client process that has a direct session to this machine.
11369 *
11370 * On Win32 and on OS/2, this method is called only when we've got the
11371 * mutex (i.e. the client has either died or terminated normally) so it always
11372 * returns @c true (the client is terminated, the session machine is
11373 * uninitialized).
11374 *
11375 * On other platforms, the method returns @c true if the client process has
11376 * terminated normally or abnormally and the session machine was uninitialized,
11377 * and @c false if the client process is still alive.
11378 *
11379 * @note Locks this object for writing.
11380 */
11381bool SessionMachine::checkForDeath()
11382{
11383 Uninit::Reason reason;
11384 bool terminated = false;
11385
11386 /* Enclose autoCaller with a block because calling uninit() from under it
11387 * will deadlock. */
11388 {
11389 AutoCaller autoCaller(this);
11390 if (!autoCaller.isOk())
11391 {
11392 /* return true if not ready, to cause the client watcher to exclude
11393 * the corresponding session from watching */
11394 LogFlowThisFunc(("Already uninitialized!\n"));
11395 return true;
11396 }
11397
11398 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11399
11400 /* Determine the reason of death: if the session state is Closing here,
11401 * everything is fine. Otherwise it means that the client did not call
11402 * OnSessionEnd() before it released the IPC semaphore. This may happen
11403 * either because the client process has abnormally terminated, or
11404 * because it simply forgot to call ISession::Close() before exiting. We
11405 * threat the latter also as an abnormal termination (see
11406 * Session::uninit() for details). */
11407 reason = mData->mSession.mState == SessionState_Unlocking ?
11408 Uninit::Normal :
11409 Uninit::Abnormal;
11410
11411#if defined(RT_OS_WINDOWS)
11412
11413 AssertMsg(mIPCSem, ("semaphore must be created"));
11414
11415 /* release the IPC mutex */
11416 ::ReleaseMutex(mIPCSem);
11417
11418 terminated = true;
11419
11420#elif defined(RT_OS_OS2)
11421
11422 AssertMsg(mIPCSem, ("semaphore must be created"));
11423
11424 /* release the IPC mutex */
11425 ::DosReleaseMutexSem(mIPCSem);
11426
11427 terminated = true;
11428
11429#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11430
11431 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11432
11433 int val = ::semctl(mIPCSem, 0, GETVAL);
11434 if (val > 0)
11435 {
11436 /* the semaphore is signaled, meaning the session is terminated */
11437 terminated = true;
11438 }
11439
11440#else
11441# error "Port me!"
11442#endif
11443
11444 } /* AutoCaller block */
11445
11446 if (terminated)
11447 uninit(reason);
11448
11449 return terminated;
11450}
11451
11452/**
11453 * @note Locks this object for reading.
11454 */
11455HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11456{
11457 LogFlowThisFunc(("\n"));
11458
11459 AutoCaller autoCaller(this);
11460 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11461
11462 ComPtr<IInternalSessionControl> directControl;
11463 {
11464 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11465 directControl = mData->mSession.mDirectControl;
11466 }
11467
11468 /* ignore notifications sent after #OnSessionEnd() is called */
11469 if (!directControl)
11470 return S_OK;
11471
11472 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11473}
11474
11475/**
11476 * @note Locks this object for reading.
11477 */
11478HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11479 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
11480{
11481 LogFlowThisFunc(("\n"));
11482
11483 AutoCaller autoCaller(this);
11484 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11485
11486 ComPtr<IInternalSessionControl> directControl;
11487 {
11488 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11489 directControl = mData->mSession.mDirectControl;
11490 }
11491
11492 /* ignore notifications sent after #OnSessionEnd() is called */
11493 if (!directControl)
11494 return S_OK;
11495 /*
11496 * instead acting like callback we ask IVirtualBox deliver corresponding event
11497 */
11498
11499 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
11500 return S_OK;
11501}
11502
11503/**
11504 * @note Locks this object for reading.
11505 */
11506HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
11507{
11508 LogFlowThisFunc(("\n"));
11509
11510 AutoCaller autoCaller(this);
11511 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11512
11513 ComPtr<IInternalSessionControl> directControl;
11514 {
11515 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11516 directControl = mData->mSession.mDirectControl;
11517 }
11518
11519 /* ignore notifications sent after #OnSessionEnd() is called */
11520 if (!directControl)
11521 return S_OK;
11522
11523 return directControl->OnSerialPortChange(serialPort);
11524}
11525
11526/**
11527 * @note Locks this object for reading.
11528 */
11529HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
11530{
11531 LogFlowThisFunc(("\n"));
11532
11533 AutoCaller autoCaller(this);
11534 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11535
11536 ComPtr<IInternalSessionControl> directControl;
11537 {
11538 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11539 directControl = mData->mSession.mDirectControl;
11540 }
11541
11542 /* ignore notifications sent after #OnSessionEnd() is called */
11543 if (!directControl)
11544 return S_OK;
11545
11546 return directControl->OnParallelPortChange(parallelPort);
11547}
11548
11549/**
11550 * @note Locks this object for reading.
11551 */
11552HRESULT SessionMachine::onStorageControllerChange()
11553{
11554 LogFlowThisFunc(("\n"));
11555
11556 AutoCaller autoCaller(this);
11557 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11558
11559 ComPtr<IInternalSessionControl> directControl;
11560 {
11561 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11562 directControl = mData->mSession.mDirectControl;
11563 }
11564
11565 /* ignore notifications sent after #OnSessionEnd() is called */
11566 if (!directControl)
11567 return S_OK;
11568
11569 return directControl->OnStorageControllerChange();
11570}
11571
11572/**
11573 * @note Locks this object for reading.
11574 */
11575HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11576{
11577 LogFlowThisFunc(("\n"));
11578
11579 AutoCaller autoCaller(this);
11580 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11581
11582 ComPtr<IInternalSessionControl> directControl;
11583 {
11584 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11585 directControl = mData->mSession.mDirectControl;
11586 }
11587
11588 /* ignore notifications sent after #OnSessionEnd() is called */
11589 if (!directControl)
11590 return S_OK;
11591
11592 return directControl->OnMediumChange(aAttachment, aForce);
11593}
11594
11595/**
11596 * @note Locks this object for reading.
11597 */
11598HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11599{
11600 LogFlowThisFunc(("\n"));
11601
11602 AutoCaller autoCaller(this);
11603 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11604
11605 ComPtr<IInternalSessionControl> directControl;
11606 {
11607 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11608 directControl = mData->mSession.mDirectControl;
11609 }
11610
11611 /* ignore notifications sent after #OnSessionEnd() is called */
11612 if (!directControl)
11613 return S_OK;
11614
11615 return directControl->OnCPUChange(aCPU, aRemove);
11616}
11617
11618HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11619{
11620 LogFlowThisFunc(("\n"));
11621
11622 AutoCaller autoCaller(this);
11623 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11624
11625 ComPtr<IInternalSessionControl> directControl;
11626 {
11627 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11628 directControl = mData->mSession.mDirectControl;
11629 }
11630
11631 /* ignore notifications sent after #OnSessionEnd() is called */
11632 if (!directControl)
11633 return S_OK;
11634
11635 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11636}
11637
11638/**
11639 * @note Locks this object for reading.
11640 */
11641HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11642{
11643 LogFlowThisFunc(("\n"));
11644
11645 AutoCaller autoCaller(this);
11646 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11647
11648 ComPtr<IInternalSessionControl> directControl;
11649 {
11650 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11651 directControl = mData->mSession.mDirectControl;
11652 }
11653
11654 /* ignore notifications sent after #OnSessionEnd() is called */
11655 if (!directControl)
11656 return S_OK;
11657
11658 return directControl->OnVRDEServerChange(aRestart);
11659}
11660
11661/**
11662 * @note Locks this object for reading.
11663 */
11664HRESULT SessionMachine::onUSBControllerChange()
11665{
11666 LogFlowThisFunc(("\n"));
11667
11668 AutoCaller autoCaller(this);
11669 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11670
11671 ComPtr<IInternalSessionControl> directControl;
11672 {
11673 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11674 directControl = mData->mSession.mDirectControl;
11675 }
11676
11677 /* ignore notifications sent after #OnSessionEnd() is called */
11678 if (!directControl)
11679 return S_OK;
11680
11681 return directControl->OnUSBControllerChange();
11682}
11683
11684/**
11685 * @note Locks this object for reading.
11686 */
11687HRESULT SessionMachine::onSharedFolderChange()
11688{
11689 LogFlowThisFunc(("\n"));
11690
11691 AutoCaller autoCaller(this);
11692 AssertComRCReturnRC(autoCaller.rc());
11693
11694 ComPtr<IInternalSessionControl> directControl;
11695 {
11696 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11697 directControl = mData->mSession.mDirectControl;
11698 }
11699
11700 /* ignore notifications sent after #OnSessionEnd() is called */
11701 if (!directControl)
11702 return S_OK;
11703
11704 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11705}
11706
11707/**
11708 * @note Locks this object for reading.
11709 */
11710HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
11711{
11712 LogFlowThisFunc(("\n"));
11713
11714 AutoCaller autoCaller(this);
11715 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11716
11717 ComPtr<IInternalSessionControl> directControl;
11718 {
11719 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11720 directControl = mData->mSession.mDirectControl;
11721 }
11722
11723 /* ignore notifications sent after #OnSessionEnd() is called */
11724 if (!directControl)
11725 return S_OK;
11726
11727 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
11728}
11729
11730/**
11731 * Returns @c true if this machine's USB controller reports it has a matching
11732 * filter for the given USB device and @c false otherwise.
11733 *
11734 * @note Caller must have requested machine read lock.
11735 */
11736bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11737{
11738 AutoCaller autoCaller(this);
11739 /* silently return if not ready -- this method may be called after the
11740 * direct machine session has been called */
11741 if (!autoCaller.isOk())
11742 return false;
11743
11744
11745#ifdef VBOX_WITH_USB
11746 switch (mData->mMachineState)
11747 {
11748 case MachineState_Starting:
11749 case MachineState_Restoring:
11750 case MachineState_TeleportingIn:
11751 case MachineState_Paused:
11752 case MachineState_Running:
11753 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11754 * elsewhere... */
11755 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11756 default: break;
11757 }
11758#else
11759 NOREF(aDevice);
11760 NOREF(aMaskedIfs);
11761#endif
11762 return false;
11763}
11764
11765/**
11766 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11767 */
11768HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11769 IVirtualBoxErrorInfo *aError,
11770 ULONG aMaskedIfs)
11771{
11772 LogFlowThisFunc(("\n"));
11773
11774 AutoCaller autoCaller(this);
11775
11776 /* This notification may happen after the machine object has been
11777 * uninitialized (the session was closed), so don't assert. */
11778 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11779
11780 ComPtr<IInternalSessionControl> directControl;
11781 {
11782 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11783 directControl = mData->mSession.mDirectControl;
11784 }
11785
11786 /* fail on notifications sent after #OnSessionEnd() is called, it is
11787 * expected by the caller */
11788 if (!directControl)
11789 return E_FAIL;
11790
11791 /* No locks should be held at this point. */
11792 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11793 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11794
11795 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11796}
11797
11798/**
11799 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11800 */
11801HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11802 IVirtualBoxErrorInfo *aError)
11803{
11804 LogFlowThisFunc(("\n"));
11805
11806 AutoCaller autoCaller(this);
11807
11808 /* This notification may happen after the machine object has been
11809 * uninitialized (the session was closed), so don't assert. */
11810 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11811
11812 ComPtr<IInternalSessionControl> directControl;
11813 {
11814 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11815 directControl = mData->mSession.mDirectControl;
11816 }
11817
11818 /* fail on notifications sent after #OnSessionEnd() is called, it is
11819 * expected by the caller */
11820 if (!directControl)
11821 return E_FAIL;
11822
11823 /* No locks should be held at this point. */
11824 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11825 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11826
11827 return directControl->OnUSBDeviceDetach(aId, aError);
11828}
11829
11830// protected methods
11831/////////////////////////////////////////////////////////////////////////////
11832
11833/**
11834 * Helper method to finalize saving the state.
11835 *
11836 * @note Must be called from under this object's lock.
11837 *
11838 * @param aRc S_OK if the snapshot has been taken successfully
11839 * @param aErrMsg human readable error message for failure
11840 *
11841 * @note Locks mParent + this objects for writing.
11842 */
11843HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
11844{
11845 LogFlowThisFuncEnter();
11846
11847 AutoCaller autoCaller(this);
11848 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11849
11850 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11851
11852 HRESULT rc = S_OK;
11853
11854 if (SUCCEEDED(aRc))
11855 {
11856 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
11857
11858 /* save all VM settings */
11859 rc = saveSettings(NULL);
11860 // no need to check whether VirtualBox.xml needs saving also since
11861 // we can't have a name change pending at this point
11862 }
11863 else
11864 {
11865 // delete the saved state file (it might have been already created);
11866 // we need not check whether this is shared with a snapshot here because
11867 // we certainly created this saved state file here anew
11868 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
11869 }
11870
11871 /* notify the progress object about operation completion */
11872 Assert(mConsoleTaskData.mProgress);
11873 if (SUCCEEDED(aRc))
11874 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11875 else
11876 {
11877 if (aErrMsg.length())
11878 mConsoleTaskData.mProgress->notifyComplete(aRc,
11879 COM_IIDOF(ISession),
11880 getComponentName(),
11881 aErrMsg.c_str());
11882 else
11883 mConsoleTaskData.mProgress->notifyComplete(aRc);
11884 }
11885
11886 /* clear out the temporary saved state data */
11887 mConsoleTaskData.mLastState = MachineState_Null;
11888 mConsoleTaskData.strStateFilePath.setNull();
11889 mConsoleTaskData.mProgress.setNull();
11890
11891 LogFlowThisFuncLeave();
11892 return rc;
11893}
11894
11895/**
11896 * Deletes the given file if it is no longer in use by either the current machine state
11897 * (if the machine is "saved") or any of the machine's snapshots.
11898 *
11899 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
11900 * but is different for each SnapshotMachine. When calling this, the order of calling this
11901 * function on the one hand and changing that variable OR the snapshots tree on the other hand
11902 * is therefore critical. I know, it's all rather messy.
11903 *
11904 * @param strStateFile
11905 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
11906 */
11907void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
11908 Snapshot *pSnapshotToIgnore)
11909{
11910 // it is safe to delete this saved state file if it is not currently in use by the machine ...
11911 if ( (strStateFile.isNotEmpty())
11912 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
11913 )
11914 // ... and it must also not be shared with other snapshots
11915 if ( !mData->mFirstSnapshot
11916 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
11917 // this checks the SnapshotMachine's state file paths
11918 )
11919 RTFileDelete(strStateFile.c_str());
11920}
11921
11922/**
11923 * Locks the attached media.
11924 *
11925 * All attached hard disks are locked for writing and DVD/floppy are locked for
11926 * reading. Parents of attached hard disks (if any) are locked for reading.
11927 *
11928 * This method also performs accessibility check of all media it locks: if some
11929 * media is inaccessible, the method will return a failure and a bunch of
11930 * extended error info objects per each inaccessible medium.
11931 *
11932 * Note that this method is atomic: if it returns a success, all media are
11933 * locked as described above; on failure no media is locked at all (all
11934 * succeeded individual locks will be undone).
11935 *
11936 * This method is intended to be called when the machine is in Starting or
11937 * Restoring state and asserts otherwise.
11938 *
11939 * The locks made by this method must be undone by calling #unlockMedia() when
11940 * no more needed.
11941 */
11942HRESULT SessionMachine::lockMedia()
11943{
11944 AutoCaller autoCaller(this);
11945 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11946
11947 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11948
11949 AssertReturn( mData->mMachineState == MachineState_Starting
11950 || mData->mMachineState == MachineState_Restoring
11951 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11952 /* bail out if trying to lock things with already set up locking */
11953 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11954
11955 MultiResult mrc(S_OK);
11956
11957 /* Collect locking information for all medium objects attached to the VM. */
11958 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11959 it != mMediaData->mAttachments.end();
11960 ++it)
11961 {
11962 MediumAttachment* pAtt = *it;
11963 DeviceType_T devType = pAtt->getType();
11964 Medium *pMedium = pAtt->getMedium();
11965
11966 MediumLockList *pMediumLockList(new MediumLockList());
11967 // There can be attachments without a medium (floppy/dvd), and thus
11968 // it's impossible to create a medium lock list. It still makes sense
11969 // to have the empty medium lock list in the map in case a medium is
11970 // attached later.
11971 if (pMedium != NULL)
11972 {
11973 MediumType_T mediumType = pMedium->getType();
11974 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
11975 || mediumType == MediumType_Shareable;
11976 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11977
11978 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11979 !fIsReadOnlyLock /* fMediumLockWrite */,
11980 NULL,
11981 *pMediumLockList);
11982 if (FAILED(mrc))
11983 {
11984 delete pMediumLockList;
11985 mData->mSession.mLockedMedia.Clear();
11986 break;
11987 }
11988 }
11989
11990 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11991 if (FAILED(rc))
11992 {
11993 mData->mSession.mLockedMedia.Clear();
11994 mrc = setError(rc,
11995 tr("Collecting locking information for all attached media failed"));
11996 break;
11997 }
11998 }
11999
12000 if (SUCCEEDED(mrc))
12001 {
12002 /* Now lock all media. If this fails, nothing is locked. */
12003 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12004 if (FAILED(rc))
12005 {
12006 mrc = setError(rc,
12007 tr("Locking of attached media failed"));
12008 }
12009 }
12010
12011 return mrc;
12012}
12013
12014/**
12015 * Undoes the locks made by by #lockMedia().
12016 */
12017void SessionMachine::unlockMedia()
12018{
12019 AutoCaller autoCaller(this);
12020 AssertComRCReturnVoid(autoCaller.rc());
12021
12022 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12023
12024 /* we may be holding important error info on the current thread;
12025 * preserve it */
12026 ErrorInfoKeeper eik;
12027
12028 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12029 AssertComRC(rc);
12030}
12031
12032/**
12033 * Helper to change the machine state (reimplementation).
12034 *
12035 * @note Locks this object for writing.
12036 */
12037HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12038{
12039 LogFlowThisFuncEnter();
12040 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12041
12042 AutoCaller autoCaller(this);
12043 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12044
12045 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12046
12047 MachineState_T oldMachineState = mData->mMachineState;
12048
12049 AssertMsgReturn(oldMachineState != aMachineState,
12050 ("oldMachineState=%s, aMachineState=%s\n",
12051 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12052 E_FAIL);
12053
12054 HRESULT rc = S_OK;
12055
12056 int stsFlags = 0;
12057 bool deleteSavedState = false;
12058
12059 /* detect some state transitions */
12060
12061 if ( ( oldMachineState == MachineState_Saved
12062 && aMachineState == MachineState_Restoring)
12063 || ( ( oldMachineState == MachineState_PoweredOff
12064 || oldMachineState == MachineState_Teleported
12065 || oldMachineState == MachineState_Aborted
12066 )
12067 && ( aMachineState == MachineState_TeleportingIn
12068 || aMachineState == MachineState_Starting
12069 )
12070 )
12071 )
12072 {
12073 /* The EMT thread is about to start */
12074
12075 /* Nothing to do here for now... */
12076
12077 /// @todo NEWMEDIA don't let mDVDDrive and other children
12078 /// change anything when in the Starting/Restoring state
12079 }
12080 else if ( ( oldMachineState == MachineState_Running
12081 || oldMachineState == MachineState_Paused
12082 || oldMachineState == MachineState_Teleporting
12083 || oldMachineState == MachineState_LiveSnapshotting
12084 || oldMachineState == MachineState_Stuck
12085 || oldMachineState == MachineState_Starting
12086 || oldMachineState == MachineState_Stopping
12087 || oldMachineState == MachineState_Saving
12088 || oldMachineState == MachineState_Restoring
12089 || oldMachineState == MachineState_TeleportingPausedVM
12090 || oldMachineState == MachineState_TeleportingIn
12091 )
12092 && ( aMachineState == MachineState_PoweredOff
12093 || aMachineState == MachineState_Saved
12094 || aMachineState == MachineState_Teleported
12095 || aMachineState == MachineState_Aborted
12096 )
12097 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
12098 * snapshot */
12099 && ( mConsoleTaskData.mSnapshot.isNull()
12100 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
12101 )
12102 )
12103 {
12104 /* The EMT thread has just stopped, unlock attached media. Note that as
12105 * opposed to locking that is done from Console, we do unlocking here
12106 * because the VM process may have aborted before having a chance to
12107 * properly unlock all media it locked. */
12108
12109 unlockMedia();
12110 }
12111
12112 if (oldMachineState == MachineState_Restoring)
12113 {
12114 if (aMachineState != MachineState_Saved)
12115 {
12116 /*
12117 * delete the saved state file once the machine has finished
12118 * restoring from it (note that Console sets the state from
12119 * Restoring to Saved if the VM couldn't restore successfully,
12120 * to give the user an ability to fix an error and retry --
12121 * we keep the saved state file in this case)
12122 */
12123 deleteSavedState = true;
12124 }
12125 }
12126 else if ( oldMachineState == MachineState_Saved
12127 && ( aMachineState == MachineState_PoweredOff
12128 || aMachineState == MachineState_Aborted
12129 || aMachineState == MachineState_Teleported
12130 )
12131 )
12132 {
12133 /*
12134 * delete the saved state after Console::ForgetSavedState() is called
12135 * or if the VM process (owning a direct VM session) crashed while the
12136 * VM was Saved
12137 */
12138
12139 /// @todo (dmik)
12140 // Not sure that deleting the saved state file just because of the
12141 // client death before it attempted to restore the VM is a good
12142 // thing. But when it crashes we need to go to the Aborted state
12143 // which cannot have the saved state file associated... The only
12144 // way to fix this is to make the Aborted condition not a VM state
12145 // but a bool flag: i.e., when a crash occurs, set it to true and
12146 // change the state to PoweredOff or Saved depending on the
12147 // saved state presence.
12148
12149 deleteSavedState = true;
12150 mData->mCurrentStateModified = TRUE;
12151 stsFlags |= SaveSTS_CurStateModified;
12152 }
12153
12154 if ( aMachineState == MachineState_Starting
12155 || aMachineState == MachineState_Restoring
12156 || aMachineState == MachineState_TeleportingIn
12157 )
12158 {
12159 /* set the current state modified flag to indicate that the current
12160 * state is no more identical to the state in the
12161 * current snapshot */
12162 if (!mData->mCurrentSnapshot.isNull())
12163 {
12164 mData->mCurrentStateModified = TRUE;
12165 stsFlags |= SaveSTS_CurStateModified;
12166 }
12167 }
12168
12169 if (deleteSavedState)
12170 {
12171 if (mRemoveSavedState)
12172 {
12173 Assert(!mSSData->strStateFilePath.isEmpty());
12174
12175 // it is safe to delete the saved state file if ...
12176 if ( !mData->mFirstSnapshot // ... we have no snapshots or
12177 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
12178 // ... none of the snapshots share the saved state file
12179 )
12180 RTFileDelete(mSSData->strStateFilePath.c_str());
12181 }
12182
12183 mSSData->strStateFilePath.setNull();
12184 stsFlags |= SaveSTS_StateFilePath;
12185 }
12186
12187 /* redirect to the underlying peer machine */
12188 mPeer->setMachineState(aMachineState);
12189
12190 if ( aMachineState == MachineState_PoweredOff
12191 || aMachineState == MachineState_Teleported
12192 || aMachineState == MachineState_Aborted
12193 || aMachineState == MachineState_Saved)
12194 {
12195 /* the machine has stopped execution
12196 * (or the saved state file was adopted) */
12197 stsFlags |= SaveSTS_StateTimeStamp;
12198 }
12199
12200 if ( ( oldMachineState == MachineState_PoweredOff
12201 || oldMachineState == MachineState_Aborted
12202 || oldMachineState == MachineState_Teleported
12203 )
12204 && aMachineState == MachineState_Saved)
12205 {
12206 /* the saved state file was adopted */
12207 Assert(!mSSData->strStateFilePath.isEmpty());
12208 stsFlags |= SaveSTS_StateFilePath;
12209 }
12210
12211#ifdef VBOX_WITH_GUEST_PROPS
12212 if ( aMachineState == MachineState_PoweredOff
12213 || aMachineState == MachineState_Aborted
12214 || aMachineState == MachineState_Teleported)
12215 {
12216 /* Make sure any transient guest properties get removed from the
12217 * property store on shutdown. */
12218
12219 HWData::GuestPropertyList::iterator it;
12220 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
12221 if (!fNeedsSaving)
12222 for (it = mHWData->mGuestProperties.begin();
12223 it != mHWData->mGuestProperties.end(); ++it)
12224 if (it->mFlags & guestProp::TRANSIENT)
12225 {
12226 fNeedsSaving = true;
12227 break;
12228 }
12229 if (fNeedsSaving)
12230 {
12231 mData->mCurrentStateModified = TRUE;
12232 stsFlags |= SaveSTS_CurStateModified;
12233 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
12234 }
12235 }
12236#endif
12237
12238 rc = saveStateSettings(stsFlags);
12239
12240 if ( ( oldMachineState != MachineState_PoweredOff
12241 && oldMachineState != MachineState_Aborted
12242 && oldMachineState != MachineState_Teleported
12243 )
12244 && ( aMachineState == MachineState_PoweredOff
12245 || aMachineState == MachineState_Aborted
12246 || aMachineState == MachineState_Teleported
12247 )
12248 )
12249 {
12250 /* we've been shut down for any reason */
12251 /* no special action so far */
12252 }
12253
12254 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
12255 LogFlowThisFuncLeave();
12256 return rc;
12257}
12258
12259/**
12260 * Sends the current machine state value to the VM process.
12261 *
12262 * @note Locks this object for reading, then calls a client process.
12263 */
12264HRESULT SessionMachine::updateMachineStateOnClient()
12265{
12266 AutoCaller autoCaller(this);
12267 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12268
12269 ComPtr<IInternalSessionControl> directControl;
12270 {
12271 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12272 AssertReturn(!!mData, E_FAIL);
12273 directControl = mData->mSession.mDirectControl;
12274
12275 /* directControl may be already set to NULL here in #OnSessionEnd()
12276 * called too early by the direct session process while there is still
12277 * some operation (like deleting the snapshot) in progress. The client
12278 * process in this case is waiting inside Session::close() for the
12279 * "end session" process object to complete, while #uninit() called by
12280 * #checkForDeath() on the Watcher thread is waiting for the pending
12281 * operation to complete. For now, we accept this inconsistent behavior
12282 * and simply do nothing here. */
12283
12284 if (mData->mSession.mState == SessionState_Unlocking)
12285 return S_OK;
12286
12287 AssertReturn(!directControl.isNull(), E_FAIL);
12288 }
12289
12290 return directControl->UpdateMachineState(mData->mMachineState);
12291}
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