VirtualBox

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

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

Main;VBoxManage: more clone vm work

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