VirtualBox

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

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

Main-CloneVM: add save state file support; multi result errors

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 445.3 KB
Line 
1/* $Id: MachineImpl.cpp 37485 2011-06-16 08:37:49Z 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 typedef struct
6096 {
6097 Guid snapshotUuid;
6098 Utf8Str strSaveStateFile;
6099 uint64_t cbSize;
6100 }SaveStateTask;
6101 RTCList<SaveStateTask> llSaveStateFiles; /* Snapshot UUID -> File path */
6102};
6103
6104STDMETHODIMP Machine::CloneTo(IMachine *pTarget, CloneMode_T mode, BOOL fFullClone, IProgress **pProgress)
6105{
6106 LogFlowFuncEnter();
6107
6108 CheckComArgNotNull(pTarget);
6109 CheckComArgOutPointerValid(pProgress);
6110
6111 AutoCaller autoCaller(this);
6112 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6113
6114 AutoReadLock srcLock(this COMMA_LOCKVAL_SRC_POS);
6115
6116 CloneVMTask *pTask = NULL;
6117
6118 HRESULT rc;
6119 try
6120 {
6121 pTask = new CloneVMTask;
6122 pTask->pSrcMachine = this;
6123 pTask->pTrgMachine = static_cast<Machine*>(pTarget);
6124 pTask->fLinkDisks = !fFullClone;
6125 pTask->mode = mode;
6126
6127 /* Lock the target machine early (so nobody mess around with it in the meantime). */
6128 AutoWriteLock trgLock(pTask->pTrgMachine COMMA_LOCKVAL_SRC_POS);
6129
6130 if (pTask->pSrcMachine->isSnapshotMachine())
6131 pTask->snapshotId = pTask->pSrcMachine->getSnapshotId();
6132
6133 /* Add the current machine and all snapshot machines below this machine
6134 * in a list for further processing. */
6135 RTCList< ComObjPtr<Machine> > machineList;
6136
6137 /* Include current state? */
6138 if ( pTask->mode == CloneMode_MachineState)
6139// || pTask->mode == CloneMode_AllStates)
6140 machineList.append(pTask->pSrcMachine);
6141 /* Should be done a depth copy with all child snapshots? */
6142 if ( pTask->mode == CloneMode_MachineAndChildStates
6143 || pTask->mode == CloneMode_AllStates)
6144 {
6145 ULONG cSnapshots = 0;
6146 rc = pTask->pSrcMachine->COMGETTER(SnapshotCount)(&cSnapshots);
6147 if (FAILED(rc)) throw rc;
6148 if (cSnapshots > 0)
6149 {
6150 Utf8Str id;
6151 if ( pTask->mode == CloneMode_MachineAndChildStates
6152 && !pTask->snapshotId.isEmpty())
6153 id = pTask->snapshotId.toString();
6154 ComPtr<ISnapshot> pSnapshot;
6155 rc = pTask->pSrcMachine->FindSnapshot(Bstr(id).raw(), pSnapshot.asOutParam());
6156 if (FAILED(rc)) throw rc;
6157 rc = cloneCreateMachineList(pSnapshot, machineList);
6158 if (FAILED(rc)) throw rc;
6159 rc = pSnapshot->COMGETTER(Machine)(pTask->pOldMachineState.asOutParam());
6160 if (FAILED(rc)) throw rc;
6161 }
6162 }
6163
6164 /* Go over every machine and walk over every attachment this machine has. */
6165 ULONG uCount = 2; /* One init task and the machine creation. */
6166 ULONG uTotalWeight = 2; /* The init task and the machine creation is worth one. */
6167 for (size_t i = 0; i < machineList.size(); ++i)
6168 {
6169 ComObjPtr<Machine> machine = machineList.at(i);
6170 /* If this is the Snapshot Machine we want to clone, we need to
6171 * create a new diff file for the new "current state". */
6172 bool fCreateDiffs = false;
6173 if (machine == pTask->pOldMachineState)
6174 fCreateDiffs = true;
6175 SafeIfaceArray<IMediumAttachment> sfaAttachments;
6176 rc = machine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
6177 if (FAILED(rc)) throw rc;
6178 /* Add all attachments (and there parents) of the different
6179 * machines to a worker list. */
6180 for (size_t a = 0; a < sfaAttachments.size(); ++a)
6181 {
6182 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
6183 DeviceType_T type;
6184 rc = pAtt->COMGETTER(Type)(&type);
6185 if (FAILED(rc)) throw rc;
6186
6187 /* Only harddisk's are of interest. */
6188 if (type != DeviceType_HardDisk)
6189 continue;
6190
6191 /* Valid medium attached? */
6192 ComPtr<IMedium> pSrcMedium;
6193 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
6194 if (FAILED(rc)) throw rc;
6195 if (pSrcMedium.isNull())
6196 continue;
6197
6198 /* Build up a child->parent list of this attachment. (Note: we are
6199 * not interested of any child's not attached to this VM. So this
6200 * will not create a full copy of the base/child relationship.) */
6201 Machine::CloneVMTask::MediumTaskChain mtc;
6202 mtc.fCreateDiffs = fCreateDiffs;
6203 while(!pSrcMedium.isNull())
6204 {
6205 /* Refresh the state so that the file size get read. */
6206 MediumState_T e;
6207 rc = pSrcMedium->RefreshState(&e);
6208 if (FAILED(rc)) throw rc;
6209 LONG64 lSize;
6210 rc = pSrcMedium->COMGETTER(Size)(&lSize);
6211 if (FAILED(rc)) throw rc;
6212
6213 /* Save the current medium, for later cloning. */
6214 Machine::CloneVMTask::MediumTask mt;
6215 mt.pMedium = pSrcMedium;
6216 mt.uSize = lSize;
6217 mtc.chain.append(mt);
6218
6219 /* Calculate progress data */
6220 ++uCount;
6221 uTotalWeight += lSize;
6222
6223 /* Query next parent. */
6224 rc = pSrcMedium->COMGETTER(Parent)(pSrcMedium.asOutParam());
6225 if (FAILED(rc)) throw rc;
6226 };
6227 pTask->llMedias.append(mtc);
6228 }
6229 Bstr bstrSrcSaveStatePath;
6230 rc = machine->COMGETTER(StateFilePath)(bstrSrcSaveStatePath.asOutParam());
6231 if (FAILED(rc)) throw rc;
6232 if (!bstrSrcSaveStatePath.isEmpty())
6233 {
6234 Machine::CloneVMTask::SaveStateTask sst;
6235 sst.snapshotUuid = machine->getSnapshotId();
6236 sst.strSaveStateFile = bstrSrcSaveStatePath;
6237 int vrc = RTFileQuerySize(sst.strSaveStateFile.c_str(), &sst.cbSize);
6238 if (RT_FAILURE(vrc))
6239 throw setError(VBOX_E_IPRT_ERROR, tr("Could not query file size of '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), vrc);
6240 pTask->llSaveStateFiles.append(sst);
6241 ++uCount;
6242 uTotalWeight += sst.cbSize;
6243 }
6244 }
6245
6246 rc = pTask->pProgress.createObject();
6247 if (FAILED(rc)) throw rc;
6248 rc = pTask->pProgress->init(getVirtualBox(),
6249 static_cast<IMachine*>(this) /* aInitiator */,
6250 Bstr(tr("Cloning Machine")).raw(),
6251 true /* fCancellable */,
6252 uCount,
6253 uTotalWeight,
6254 Bstr(tr("Initialize Cloning")).raw(),
6255 1);
6256 if (FAILED(rc)) throw rc;
6257
6258 int vrc = RTThreadCreate(NULL,
6259 Machine::cloneVMThread,
6260 static_cast<void*>(pTask),
6261 0,
6262 RTTHREADTYPE_MAIN_WORKER,
6263 0,
6264 "MachineClone");
6265 if (RT_FAILURE(vrc))
6266 throw setError(VBOX_E_IPRT_ERROR, "Could not create machine clone thread (%Rrc)", vrc);
6267 }
6268 catch (HRESULT rc2)
6269 {
6270 if (pTask)
6271 delete pTask;
6272 rc = rc2;
6273 }
6274
6275 if (SUCCEEDED(rc))
6276 pTask->pProgress.queryInterfaceTo(pProgress);
6277
6278 LogFlowFuncLeave();
6279
6280 return rc;
6281}
6282
6283/**
6284 * Static task wrapper passed to RTThreadCreate() in Machine::CloneTo() which then
6285 * calls Machine::cloneVMTaskWorker() on the actual machine object.
6286 * @param Thread
6287 * @param pvUser
6288 * @return
6289 */
6290/* static */
6291DECLCALLBACK(int) Machine::cloneVMThread(RTTHREAD /* Thread */, void *pvUser)
6292{
6293 LogFlowFuncEnter();
6294
6295 CloneVMTask *pTask = static_cast<CloneVMTask*>(pvUser);
6296 AssertReturn(pTask, VERR_INVALID_POINTER);
6297 AssertReturn(pTask->pSrcMachine, VERR_INVALID_POINTER);
6298 AssertReturn(pTask->pTrgMachine, VERR_INVALID_POINTER);
6299 AssertReturn(pTask->pProgress, VERR_INVALID_POINTER);
6300
6301 HRESULT rc = pTask->pSrcMachine->cloneVMTaskWorker(pTask);
6302 pTask->pProgress->notifyComplete(rc);
6303
6304 delete pTask;
6305
6306 LogFlowFuncLeave();
6307
6308 return VINF_SUCCESS;
6309}
6310
6311HRESULT Machine::cloneCreateMachineList(const ComPtr<ISnapshot> &pSnapshot, RTCList< ComObjPtr<Machine> > &machineList) const
6312{
6313 HRESULT rc = S_OK;
6314 Bstr name;
6315 rc = pSnapshot->COMGETTER(Name)(name.asOutParam());
6316 if (FAILED(rc)) return rc;
6317
6318 ComPtr<IMachine> pMachine;
6319 rc = pSnapshot->COMGETTER(Machine)(pMachine.asOutParam());
6320 if (FAILED(rc)) return rc;
6321 machineList.append((Machine*)(IMachine*)pMachine);
6322
6323 SafeIfaceArray<ISnapshot> sfaChilds;
6324 rc = pSnapshot->COMGETTER(Children)(ComSafeArrayAsOutParam(sfaChilds));
6325 if (FAILED(rc)) return rc;
6326 for (size_t i = 0; i < sfaChilds.size(); ++i)
6327 {
6328 rc = cloneCreateMachineList(sfaChilds[i], machineList);
6329 if (FAILED(rc)) return rc;
6330 }
6331
6332 return rc;
6333}
6334
6335settings::Snapshot Machine::cloneFindSnapshot(settings::MachineConfigFile *pMCF, const settings::SnapshotsList &snl, const Guid &id) const
6336{
6337 settings::SnapshotsList::const_iterator it;
6338 for (it = snl.begin(); it != snl.end(); ++it)
6339 {
6340 if (it->uuid == id)
6341 return *it;
6342 else if (!it->llChildSnapshots.empty())
6343 return cloneFindSnapshot(pMCF, it->llChildSnapshots, id);
6344 }
6345 return settings::Snapshot();
6346}
6347
6348void Machine::cloneUpdateStorageLists(settings::StorageControllersList &sc, const Bstr &bstrOldId, const Bstr &bstrNewId) const
6349{
6350 settings::StorageControllersList::iterator it3;
6351 for (it3 = sc.begin();
6352 it3 != sc.end();
6353 ++it3)
6354 {
6355 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
6356 settings::AttachedDevicesList::iterator it4;
6357 for (it4 = llAttachments.begin();
6358 it4 != llAttachments.end();
6359 ++it4)
6360 {
6361 if ( it4->deviceType == DeviceType_HardDisk
6362 && it4->uuid == bstrOldId)
6363 {
6364 it4->uuid = bstrNewId;
6365 }
6366 }
6367 }
6368}
6369
6370void Machine::cloneUpdateSnapshotStorageLists(settings::SnapshotsList &sl, const Bstr &bstrOldId, const Bstr &bstrNewId) const
6371{
6372 settings::SnapshotsList::iterator it;
6373 for ( it = sl.begin();
6374 it != sl.end();
6375 ++it)
6376 {
6377 cloneUpdateStorageLists(it->storage.llStorageControllers, bstrOldId, bstrNewId);
6378 if (!it->llChildSnapshots.empty())
6379 cloneUpdateSnapshotStorageLists(it->llChildSnapshots, bstrOldId, bstrNewId);
6380 }
6381}
6382
6383void Machine::cloneUpdateStateFile(settings::SnapshotsList &snl, const Guid &id, const Utf8Str &strFile) const
6384{
6385 settings::SnapshotsList::iterator it;
6386 for (it = snl.begin(); it != snl.end(); ++it)
6387 {
6388 if (it->uuid == id)
6389 it->strStateFile = strFile;
6390 else if (!it->llChildSnapshots.empty())
6391 cloneUpdateStateFile(it->llChildSnapshots, id, strFile);
6392 }
6393}
6394
6395/* static */
6396int Machine::cloneCopyStateFileProgress(unsigned uPercentage, void *pvUser)
6397{
6398 ComObjPtr<Progress> pProgress = *static_cast< ComObjPtr<Progress>* >(pvUser);
6399
6400 BOOL fCanceled = false;
6401 HRESULT rc = pProgress->COMGETTER(Canceled)(&fCanceled);
6402 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
6403 /* If canceled by the user tell it to the copy operation. */
6404 if (fCanceled) return VERR_CANCELLED;
6405 /* Set the new process. */
6406 RTPrintf("stat %d %%\n", uPercentage);
6407 rc = pProgress->SetCurrentOperationProgress(uPercentage);
6408 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
6409
6410 return VINF_SUCCESS;
6411}
6412
6413/**
6414 * Task thread implementation for Machine::CloneTo(), called from Machine::cloneVMThread().
6415 * @param task
6416 * @return
6417 */
6418HRESULT Machine::cloneVMTaskWorker(CloneVMTask *pTask)
6419{
6420 AutoCaller autoCaller(this);
6421 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6422
6423 AutoReadLock srcLock(this COMMA_LOCKVAL_SRC_POS);
6424 AutoWriteLock trgLock(pTask->pTrgMachine COMMA_LOCKVAL_SRC_POS);
6425
6426 MultiResult rc = S_OK;
6427
6428 /*
6429 * Todo:
6430 * - Regardless where the old media comes from (e.g. snapshots folder) it
6431 * goes to the new main VM folder. Maybe we like to be a little bit
6432 * smarter here.
6433 * - Snapshot diffs (can) have the uuid as name. After cloning this isn't
6434 * right anymore. Is it worth to change to the new uuid? Or should the
6435 * cloned disks called exactly as the original one or should all new disks
6436 * get a new name with the new VM name in it.
6437 */
6438
6439 /* Where should all the media go? */
6440 Utf8Str strTrgMachineFolder = pTask->pTrgMachine->getSettingsFileFull();
6441 strTrgMachineFolder.stripFilename();
6442
6443 RTCList< ComObjPtr<Medium> > newMedias; /* All created images */
6444 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
6445 try
6446 {
6447 /* Copy all the configuration from this machine to an empty
6448 * configuration dataset. */
6449 settings::MachineConfigFile *pTrgMCF = new settings::MachineConfigFile(0);
6450 *pTrgMCF = *mData->pMachineConfigFile;
6451
6452 /* Reset media registry. */
6453 pTrgMCF->mediaRegistry.llHardDisks.clear();
6454 /* If we got a valid snapshot id, replace the hardware/storage section
6455 * with the stuff from the snapshot. */
6456 settings::Snapshot sn;
6457 if (!pTask->snapshotId.isEmpty())
6458 sn = cloneFindSnapshot(pTrgMCF, pTrgMCF->llFirstSnapshot, pTask->snapshotId);
6459
6460 if (pTask->mode == CloneMode_MachineState)
6461 {
6462 if (!sn.uuid.isEmpty())
6463 {
6464 pTrgMCF->hardwareMachine = sn.hardware;
6465 pTrgMCF->storageMachine = sn.storage;
6466 }
6467
6468 /* Remove any hint on snapshots. */
6469 pTrgMCF->llFirstSnapshot.clear();
6470 pTrgMCF->uuidCurrentSnapshot.clear();
6471 }else
6472 if ( pTask->mode == CloneMode_MachineAndChildStates
6473 && !sn.uuid.isEmpty())
6474 {
6475 /* Copy the snapshot data to the current machine. */
6476 pTrgMCF->hardwareMachine = sn.hardware;
6477 pTrgMCF->storageMachine = sn.storage;
6478
6479 /* The snapshot will be the root one. */
6480 pTrgMCF->uuidCurrentSnapshot = sn.uuid;
6481 pTrgMCF->llFirstSnapshot.clear();
6482 pTrgMCF->llFirstSnapshot.push_back(sn);
6483 }
6484
6485 /* When the current snapshot folder is absolute we reset it to the
6486 * default relative folder. */
6487 if (RTPathStartsWithRoot(pTrgMCF->machineUserData.strSnapshotFolder.c_str()))
6488 pTrgMCF->machineUserData.strSnapshotFolder = "Snapshots";
6489 pTrgMCF->strStateFile = "";
6490 /* Force writing of setting file. */
6491 pTrgMCF->fCurrentStateModified = true;
6492 /* Set the new name. */
6493 pTrgMCF->machineUserData.strName = pTask->pTrgMachine->mUserData->s.strName;
6494 pTrgMCF->uuid = pTask->pTrgMachine->mData->mUuid;
6495
6496 Bstr bstrSrcSnapshotFolder;
6497 rc = pTask->pSrcMachine->COMGETTER(SnapshotFolder)(bstrSrcSnapshotFolder.asOutParam());
6498 if (FAILED(rc)) throw rc;
6499 /* The absolute name of the snapshot folder. */
6500 Utf8Str strTrgSnapshotFolder = Utf8StrFmt("%s%c%s%c", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, pTrgMCF->machineUserData.strSnapshotFolder.c_str(), RTPATH_DELIMITER);
6501
6502 /* We need to create a map with the already created medias. This is
6503 * necessary, cause different snapshots could have the same
6504 * parents/parent chain. If a medium is in this map already, it isn't
6505 * cloned a second time, but simply used. */
6506 typedef std::map<Utf8Str, ComObjPtr<Medium> > TStrMediumMap;
6507 typedef std::pair<Utf8Str, ComObjPtr<Medium> > TStrMediumPair;
6508 TStrMediumMap map;
6509 for (size_t i = 0; i < pTask->llMedias.size(); ++i)
6510 {
6511 const Machine::CloneVMTask::MediumTaskChain &mtc = pTask->llMedias.at(i);
6512 ComObjPtr<Medium> pNewParent;
6513 for (size_t a = mtc.chain.size(); a > 0; --a)
6514 {
6515 const Machine::CloneVMTask::MediumTask &mt = mtc.chain.at(a - 1);
6516 ComPtr<IMedium> pMedium = mt.pMedium;
6517
6518 Bstr bstrSrcName;
6519 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
6520 if (FAILED(rc)) throw rc;
6521
6522 rc = pTask->pProgress->SetNextOperation(BstrFmt(tr("Cloning Disk '%ls' ..."), bstrSrcName.raw()).raw(), mt.uSize);
6523 if (FAILED(rc)) throw rc;
6524
6525 Bstr bstrSrcId;
6526 rc = pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
6527 if (FAILED(rc)) throw rc;
6528
6529 /* Is a clone already there? */
6530 TStrMediumMap::iterator it = map.find(Utf8Str(bstrSrcId));
6531 if (it != map.end())
6532 pNewParent = it->second;
6533 else
6534 {
6535 ComPtr<IMediumFormat> pSrcFormat;
6536 rc = pMedium->COMGETTER(MediumFormat)(pSrcFormat.asOutParam());
6537 ULONG uSrcCaps = 0;
6538 rc = pSrcFormat->COMGETTER(Capabilities)(&uSrcCaps);
6539 if (FAILED(rc)) throw rc;
6540
6541 Bstr bstrSrcFormat = "VDI";
6542 ULONG srcVar = MediumVariant_Standard;
6543 /* Is the source file based? */
6544 if ((uSrcCaps & MediumFormatCapabilities_File) == MediumFormatCapabilities_File)
6545 {
6546 /* Yes, just use the source format. Otherwise the defaults
6547 * will be used. */
6548 rc = pMedium->COMGETTER(Format)(bstrSrcFormat.asOutParam());
6549 if (FAILED(rc)) throw rc;
6550 rc = pMedium->COMGETTER(Variant)(&srcVar);
6551 if (FAILED(rc)) throw rc;
6552 }
6553
6554 /* Start creating the clone. */
6555 ComObjPtr<Medium> pTarget;
6556 rc = pTarget.createObject();
6557 if (FAILED(rc)) throw rc;
6558
6559 Utf8Str strFile = Utf8StrFmt("%s%c%lS", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, bstrSrcName.raw());
6560 rc = pTarget->init(mParent,
6561 Utf8Str(bstrSrcFormat),
6562 strFile,
6563 pTask->pTrgMachine->mData->mUuid, /* media registry */
6564 NULL /* llRegistriesThatNeedSaving */);
6565 if (FAILED(rc)) throw rc;
6566
6567 /* Do the disk cloning. */
6568 ComPtr<IProgress> progress2;
6569 rc = pMedium->CloneTo(pTarget,
6570 srcVar,
6571 pNewParent,
6572 progress2.asOutParam());
6573 if (FAILED(rc)) throw rc;
6574
6575 /* Wait until the asynchrony process has finished. */
6576 srcLock.release();
6577 rc = pTask->pProgress->WaitForAsyncProgressCompletion(progress2);
6578 srcLock.acquire();
6579 if (FAILED(rc)) throw rc;
6580
6581 /* Check the result of the asynchrony process. */
6582 LONG iRc;
6583 rc = progress2->COMGETTER(ResultCode)(&iRc);
6584 if (FAILED(rc)) throw rc;
6585 if (FAILED(iRc))
6586 {
6587 /* If the thread of the progress object has an error, then
6588 * retrieve the error info from there, or it'll be lost. */
6589 ProgressErrorInfo info(progress2);
6590 throw setError(iRc, Utf8Str(info.getText()).c_str());
6591 }
6592
6593 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pTarget));
6594
6595 /* Remember created medias. */
6596 newMedias.append(pTarget);
6597 /* This medium becomes the parent of the next medium in the
6598 * chain. */
6599 pNewParent = pTarget;
6600 }
6601 }
6602
6603 /* Create diffs for the last image chain. */
6604 if (mtc.fCreateDiffs)
6605 {
6606 Bstr bstrSrcId;
6607 rc = pNewParent->COMGETTER(Id)(bstrSrcId.asOutParam());
6608 if (FAILED(rc)) throw rc;
6609 GuidList *pllRegistriesThatNeedSaving;
6610 ComObjPtr<Medium> diff;
6611 diff.createObject();
6612 rc = diff->init(mParent,
6613 pNewParent->getPreferredDiffFormat(),
6614 strTrgSnapshotFolder,
6615 pTask->pTrgMachine->mData->mUuid,
6616 NULL); // pllRegistriesThatNeedSaving
6617 if (FAILED(rc)) throw rc;
6618 MediumLockList *pMediumLockList(new MediumLockList()); /* todo: deleteeeeeeeee */
6619 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
6620 true /* fMediumLockWrite */,
6621 pNewParent,
6622 *pMediumLockList);
6623 if (FAILED(rc)) throw rc;
6624 rc = pMediumLockList->Lock();
6625 if (FAILED(rc)) throw rc;
6626 rc = pNewParent->createDiffStorage(diff, MediumVariant_Standard,
6627 pMediumLockList,
6628 NULL /* aProgress */,
6629 true /* aWait */,
6630 NULL); // pllRegistriesThatNeedSaving
6631 delete pMediumLockList;
6632 if (FAILED(rc)) throw rc;
6633 pNewParent = diff;
6634 }
6635 Bstr bstrSrcId;
6636 rc = mtc.chain.first().pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
6637 if (FAILED(rc)) throw rc;
6638 Bstr bstrTrgId;
6639 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
6640 if (FAILED(rc)) throw rc;
6641 /* We have to patch the configuration, so it contains the new
6642 * medium uuid instead of the old one. */
6643 cloneUpdateStorageLists(pTrgMCF->storageMachine.llStorageControllers, bstrSrcId, bstrTrgId);
6644 cloneUpdateSnapshotStorageLists(pTrgMCF->llFirstSnapshot, bstrSrcId, bstrTrgId);
6645 }
6646 /* Clone all save state files. */
6647 for (size_t i = 0; i < pTask->llSaveStateFiles.size(); ++i)
6648 {
6649 Machine::CloneVMTask::SaveStateTask sst = pTask->llSaveStateFiles.at(i);
6650 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%s", strTrgSnapshotFolder.c_str(), RTPathFilename(sst.strSaveStateFile.c_str()));
6651
6652 /* Move to next sub-operation. */
6653 rc = pTask->pProgress->SetNextOperation(BstrFmt(tr("Copy save state file '%s' ..."), RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.cbSize);
6654 if (FAILED(rc)) throw rc;
6655 /* Copy the file only if it was not copied already. */
6656 if (!newFiles.contains(strTrgSaveState.c_str()))
6657 {
6658 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0, cloneCopyStateFileProgress, &pTask->pProgress);
6659 if (RT_FAILURE(vrc))
6660 throw setError(VBOX_E_IPRT_ERROR,
6661 tr("Could not copy state file '%s' to '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
6662 newFiles.append(strTrgSaveState);
6663 }
6664 /* Update the path in the configuration either for the current
6665 * machine state or the snapshots. */
6666 if (sst.snapshotUuid.isEmpty())
6667 pTrgMCF->strStateFile = strTrgSaveState;
6668 else
6669 cloneUpdateStateFile(pTrgMCF->llFirstSnapshot, sst.snapshotUuid, strTrgSaveState);
6670 }
6671
6672 if (false)
6673// if (!pTask->pOldMachineState.isNull())
6674 {
6675 SafeIfaceArray<IMediumAttachment> sfaAttachments;
6676 rc = pTask->pOldMachineState->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
6677 if (FAILED(rc)) throw rc;
6678 for (size_t a = 0; a < sfaAttachments.size(); ++a)
6679 {
6680 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
6681 DeviceType_T type;
6682 rc = pAtt->COMGETTER(Type)(&type);
6683 if (FAILED(rc)) throw rc;
6684
6685 /* Only harddisk's are of interest. */
6686 if (type != DeviceType_HardDisk)
6687 continue;
6688
6689 /* Valid medium attached? */
6690 ComPtr<IMedium> pSrcMedium;
6691 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
6692 if (FAILED(rc)) throw rc;
6693 if (pSrcMedium.isNull())
6694 continue;
6695
6696// ComObjPtr<Medium> pMedium = static_cast<Medium*>((IMedium*)pSrcMedium);
6697// ComObjPtr<Medium> diff;
6698// diff.createObject();
6699 // store this diff in the same registry as the parent
6700// Guid uuidRegistryParent;
6701// if (!medium->getFirstRegistryMachineId(uuidRegistryParent))
6702// {
6703 // parent image has no registry: this can happen if we're attaching a new immutable
6704 // image that has not yet been attached (medium then points to the base and we're
6705 // creating the diff image for the immutable, and the parent is not yet registered);
6706 // put the parent in the machine registry then
6707// addMediumToRegistry(medium, llRegistriesThatNeedSaving, &uuidRegistryParent);
6708// }
6709// rc = diff->init(mParent,
6710// pMedium->getPreferredDiffFormat(),
6711// strFullSnapshotFolder.append(RTPATH_SLASH_STR),
6712// uuidRegistryParent,
6713// pllRegistriesThatNeedSaving);
6714// if (FAILED(rc)) throw rc;
6715//
6716// rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
6717// pMediumLockList,
6718// NULL /* aProgress */,
6719// true /* aWait */,
6720// pllRegistriesThatNeedSaving);
6721 }
6722 }
6723
6724 {
6725 rc = pTask->pProgress->SetNextOperation(BstrFmt(tr("Create Machine Clone '%s' ..."), pTrgMCF->machineUserData.strName.c_str()).raw(), 1);
6726 if (FAILED(rc)) throw rc;
6727 /* After modifying the new machine config, we can copy the stuff
6728 * over to the new machine. The machine have to be mutable for
6729 * this. */
6730 rc = pTask->pTrgMachine->checkStateDependency(MutableStateDep);
6731 if (FAILED(rc)) throw rc;
6732 rc = pTask->pTrgMachine->loadMachineDataFromSettings(*pTrgMCF,
6733 &pTask->pTrgMachine->mData->mUuid);
6734 if (FAILED(rc)) throw rc;
6735 }
6736
6737 /* The medias are created before the machine was there. We have to make
6738 * sure the new medias know of there new parent or we get in trouble
6739 * when the media registry is saved for this VM, especially in case of
6740 * difference image chain's. See VirtualBox::saveMediaRegistry.*/
6741// for (size_t i = 0; i < newBaseMedias.size(); ++i)
6742// {
6743// rc = newBaseMedias.at(i)->addRegistry(pTask->pTrgMachine->mData->mUuid, true /* fRecursive */);
6744// if (FAILED(rc)) throw rc;
6745// }
6746
6747 /* Now save the new configuration to disk. */
6748 rc = pTask->pTrgMachine->SaveSettings();
6749 if (FAILED(rc)) throw rc;
6750 }
6751 catch(HRESULT rc2)
6752 {
6753 rc = rc2;
6754 }
6755 catch (...)
6756 {
6757 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
6758 }
6759
6760 /* Cleanup on failure (CANCEL also) */
6761 if (FAILED(rc))
6762 {
6763 int vrc = VINF_SUCCESS;
6764 /* Delete all created files. */
6765 for (size_t i = 0; i < newFiles.size(); ++i)
6766 {
6767 vrc = RTFileDelete(newFiles.at(i).c_str());
6768 if (RT_FAILURE(vrc))
6769 rc = setError(VBOX_E_IPRT_ERROR, tr("Could not delete file '%s' (%Rrc)"), newFiles.at(i).c_str(), vrc);
6770 }
6771 /* Delete all already created medias. (Reverse, cause there could be
6772 * parent->child relations.) */
6773 for (size_t i = newMedias.size(); i > 0; --i)
6774 {
6775 ComObjPtr<Medium> &pMedium = newMedias.at(i - 1);
6776 AutoCaller mac(pMedium);
6777 if (FAILED(mac.rc())) { continue; rc = mac.rc(); }
6778 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
6779 bool fFile = pMedium->isMediumFormatFile();
6780 Utf8Str strLoc = pMedium->getLocationFull();
6781 mlock.release();
6782 /* Close the medium. If this succeed, delete it finally from the
6783 * disk. */
6784 rc = pMedium->close(NULL, mac);
6785 if (FAILED(rc)) continue;
6786 if (fFile)
6787 {
6788 vrc = RTFileDelete(strLoc.c_str());
6789 if (RT_FAILURE(vrc))
6790 rc = setError(VBOX_E_IPRT_ERROR, tr("Could not delete file '%s' (%Rrc)"), strLoc.c_str(), vrc);
6791 }
6792 }
6793 /* Delete the machine folder when not empty. */
6794 RTDirRemove(strTrgMachineFolder.c_str());
6795 }
6796
6797 return rc;
6798}
6799
6800// public methods for internal purposes
6801/////////////////////////////////////////////////////////////////////////////
6802
6803/**
6804 * Adds the given IsModified_* flag to the dirty flags of the machine.
6805 * This must be called either during loadSettings or under the machine write lock.
6806 * @param fl
6807 */
6808void Machine::setModified(uint32_t fl)
6809{
6810 mData->flModifications |= fl;
6811}
6812
6813/**
6814 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
6815 * care of the write locking.
6816 *
6817 * @param fModifications The flag to add.
6818 */
6819void Machine::setModifiedLock(uint32_t fModification)
6820{
6821 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6822 mData->flModifications |= fModification;
6823}
6824
6825/**
6826 * Saves the registry entry of this machine to the given configuration node.
6827 *
6828 * @param aEntryNode Node to save the registry entry to.
6829 *
6830 * @note locks this object for reading.
6831 */
6832HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
6833{
6834 AutoLimitedCaller autoCaller(this);
6835 AssertComRCReturnRC(autoCaller.rc());
6836
6837 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6838
6839 data.uuid = mData->mUuid;
6840 data.strSettingsFile = mData->m_strConfigFile;
6841
6842 return S_OK;
6843}
6844
6845/**
6846 * Calculates the absolute path of the given path taking the directory of the
6847 * machine settings file as the current directory.
6848 *
6849 * @param aPath Path to calculate the absolute path for.
6850 * @param aResult Where to put the result (used only on success, can be the
6851 * same Utf8Str instance as passed in @a aPath).
6852 * @return IPRT result.
6853 *
6854 * @note Locks this object for reading.
6855 */
6856int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
6857{
6858 AutoCaller autoCaller(this);
6859 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6860
6861 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6862
6863 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
6864
6865 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
6866
6867 strSettingsDir.stripFilename();
6868 char folder[RTPATH_MAX];
6869 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
6870 if (RT_SUCCESS(vrc))
6871 aResult = folder;
6872
6873 return vrc;
6874}
6875
6876/**
6877 * Copies strSource to strTarget, making it relative to the machine folder
6878 * if it is a subdirectory thereof, or simply copying it otherwise.
6879 *
6880 * @param strSource Path to evaluate and copy.
6881 * @param strTarget Buffer to receive target path.
6882 *
6883 * @note Locks this object for reading.
6884 */
6885void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6886 Utf8Str &strTarget)
6887{
6888 AutoCaller autoCaller(this);
6889 AssertComRCReturn(autoCaller.rc(), (void)0);
6890
6891 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6892
6893 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6894 // use strTarget as a temporary buffer to hold the machine settings dir
6895 strTarget = mData->m_strConfigFileFull;
6896 strTarget.stripFilename();
6897 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6898 {
6899 // is relative: then append what's left
6900 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6901 // for empty paths (only possible for subdirs) use "." to avoid
6902 // triggering default settings for not present config attributes.
6903 if (strTarget.isEmpty())
6904 strTarget = ".";
6905 }
6906 else
6907 // is not relative: then overwrite
6908 strTarget = strSource;
6909}
6910
6911/**
6912 * Returns the full path to the machine's log folder in the
6913 * \a aLogFolder argument.
6914 */
6915void Machine::getLogFolder(Utf8Str &aLogFolder)
6916{
6917 AutoCaller autoCaller(this);
6918 AssertComRCReturnVoid(autoCaller.rc());
6919
6920 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6921
6922 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6923 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6924 aLogFolder.append(RTPATH_DELIMITER);
6925 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6926}
6927
6928/**
6929 * Returns the full path to the machine's log file for an given index.
6930 */
6931Utf8Str Machine::queryLogFilename(ULONG idx)
6932{
6933 Utf8Str logFolder;
6934 getLogFolder(logFolder);
6935 Assert(logFolder.length());
6936 Utf8Str log;
6937 if (idx == 0)
6938 log = Utf8StrFmt("%s%cVBox.log",
6939 logFolder.c_str(), RTPATH_DELIMITER);
6940 else
6941 log = Utf8StrFmt("%s%cVBox.log.%d",
6942 logFolder.c_str(), RTPATH_DELIMITER, idx);
6943 return log;
6944}
6945
6946/**
6947 * Composes a unique saved state filename based on the current system time. The filename is
6948 * granular to the second so this will work so long as no more than one snapshot is taken on
6949 * a machine per second.
6950 *
6951 * Before version 4.1, we used this formula for saved state files:
6952 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6953 * which no longer works because saved state files can now be shared between the saved state of the
6954 * "saved" machine and an online snapshot, and the following would cause problems:
6955 * 1) save machine
6956 * 2) create online snapshot from that machine state --> reusing saved state file
6957 * 3) save machine again --> filename would be reused, breaking the online snapshot
6958 *
6959 * So instead we now use a timestamp.
6960 *
6961 * @param str
6962 */
6963void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6964{
6965 AutoCaller autoCaller(this);
6966 AssertComRCReturnVoid(autoCaller.rc());
6967
6968 {
6969 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6970 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6971 }
6972
6973 RTTIMESPEC ts;
6974 RTTimeNow(&ts);
6975 RTTIME time;
6976 RTTimeExplode(&time, &ts);
6977
6978 strStateFilePath += RTPATH_DELIMITER;
6979 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
6980 time.i32Year, time.u8Month, time.u8MonthDay,
6981 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
6982}
6983
6984/**
6985 * @note Locks this object for writing, calls the client process
6986 * (inside the lock).
6987 */
6988HRESULT Machine::launchVMProcess(IInternalSessionControl *aControl,
6989 const Utf8Str &strType,
6990 const Utf8Str &strEnvironment,
6991 ProgressProxy *aProgress)
6992{
6993 LogFlowThisFuncEnter();
6994
6995 AssertReturn(aControl, E_FAIL);
6996 AssertReturn(aProgress, E_FAIL);
6997
6998 AutoCaller autoCaller(this);
6999 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7000
7001 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7002
7003 if (!mData->mRegistered)
7004 return setError(E_UNEXPECTED,
7005 tr("The machine '%s' is not registered"),
7006 mUserData->s.strName.c_str());
7007
7008 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
7009
7010 if ( mData->mSession.mState == SessionState_Locked
7011 || mData->mSession.mState == SessionState_Spawning
7012 || mData->mSession.mState == SessionState_Unlocking)
7013 return setError(VBOX_E_INVALID_OBJECT_STATE,
7014 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
7015 mUserData->s.strName.c_str());
7016
7017 /* may not be busy */
7018 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
7019
7020 /* get the path to the executable */
7021 char szPath[RTPATH_MAX];
7022 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
7023 size_t sz = strlen(szPath);
7024 szPath[sz++] = RTPATH_DELIMITER;
7025 szPath[sz] = 0;
7026 char *cmd = szPath + sz;
7027 sz = RTPATH_MAX - sz;
7028
7029 int vrc = VINF_SUCCESS;
7030 RTPROCESS pid = NIL_RTPROCESS;
7031
7032 RTENV env = RTENV_DEFAULT;
7033
7034 if (!strEnvironment.isEmpty())
7035 {
7036 char *newEnvStr = NULL;
7037
7038 do
7039 {
7040 /* clone the current environment */
7041 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
7042 AssertRCBreakStmt(vrc2, vrc = vrc2);
7043
7044 newEnvStr = RTStrDup(strEnvironment.c_str());
7045 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
7046
7047 /* put new variables to the environment
7048 * (ignore empty variable names here since RTEnv API
7049 * intentionally doesn't do that) */
7050 char *var = newEnvStr;
7051 for (char *p = newEnvStr; *p; ++p)
7052 {
7053 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
7054 {
7055 *p = '\0';
7056 if (*var)
7057 {
7058 char *val = strchr(var, '=');
7059 if (val)
7060 {
7061 *val++ = '\0';
7062 vrc2 = RTEnvSetEx(env, var, val);
7063 }
7064 else
7065 vrc2 = RTEnvUnsetEx(env, var);
7066 if (RT_FAILURE(vrc2))
7067 break;
7068 }
7069 var = p + 1;
7070 }
7071 }
7072 if (RT_SUCCESS(vrc2) && *var)
7073 vrc2 = RTEnvPutEx(env, var);
7074
7075 AssertRCBreakStmt(vrc2, vrc = vrc2);
7076 }
7077 while (0);
7078
7079 if (newEnvStr != NULL)
7080 RTStrFree(newEnvStr);
7081 }
7082
7083 /* Qt is default */
7084#ifdef VBOX_WITH_QTGUI
7085 if (strType == "gui" || strType == "GUI/Qt")
7086 {
7087# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
7088 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
7089# else
7090 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
7091# endif
7092 Assert(sz >= sizeof(VirtualBox_exe));
7093 strcpy(cmd, VirtualBox_exe);
7094
7095 Utf8Str idStr = mData->mUuid.toString();
7096 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
7097 vrc = RTProcCreate(szPath, args, env, 0, &pid);
7098 }
7099#else /* !VBOX_WITH_QTGUI */
7100 if (0)
7101 ;
7102#endif /* VBOX_WITH_QTGUI */
7103
7104 else
7105
7106#ifdef VBOX_WITH_VBOXSDL
7107 if (strType == "sdl" || strType == "GUI/SDL")
7108 {
7109 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
7110 Assert(sz >= sizeof(VBoxSDL_exe));
7111 strcpy(cmd, VBoxSDL_exe);
7112
7113 Utf8Str idStr = mData->mUuid.toString();
7114 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
7115 fprintf(stderr, "SDL=%s\n", szPath);
7116 vrc = RTProcCreate(szPath, args, env, 0, &pid);
7117 }
7118#else /* !VBOX_WITH_VBOXSDL */
7119 if (0)
7120 ;
7121#endif /* !VBOX_WITH_VBOXSDL */
7122
7123 else
7124
7125#ifdef VBOX_WITH_HEADLESS
7126 if ( strType == "headless"
7127 || strType == "capture"
7128 || strType == "vrdp" /* Deprecated. Same as headless. */
7129 )
7130 {
7131 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
7132 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
7133 * and a VM works even if the server has not been installed.
7134 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
7135 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
7136 * differently in 4.0 and 3.x.
7137 */
7138 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
7139 Assert(sz >= sizeof(VBoxHeadless_exe));
7140 strcpy(cmd, VBoxHeadless_exe);
7141
7142 Utf8Str idStr = mData->mUuid.toString();
7143 /* Leave space for "--capture" arg. */
7144 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
7145 "--startvm", idStr.c_str(),
7146 "--vrde", "config",
7147 0, /* For "--capture". */
7148 0 };
7149 if (strType == "capture")
7150 {
7151 unsigned pos = RT_ELEMENTS(args) - 2;
7152 args[pos] = "--capture";
7153 }
7154 vrc = RTProcCreate(szPath, args, env, 0, &pid);
7155 }
7156#else /* !VBOX_WITH_HEADLESS */
7157 if (0)
7158 ;
7159#endif /* !VBOX_WITH_HEADLESS */
7160 else
7161 {
7162 RTEnvDestroy(env);
7163 return setError(E_INVALIDARG,
7164 tr("Invalid session type: '%s'"),
7165 strType.c_str());
7166 }
7167
7168 RTEnvDestroy(env);
7169
7170 if (RT_FAILURE(vrc))
7171 return setError(VBOX_E_IPRT_ERROR,
7172 tr("Could not launch a process for the machine '%s' (%Rrc)"),
7173 mUserData->s.strName.c_str(), vrc);
7174
7175 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
7176
7177 /*
7178 * Note that we don't leave the lock here before calling the client,
7179 * because it doesn't need to call us back if called with a NULL argument.
7180 * Leaving the lock here is dangerous because we didn't prepare the
7181 * launch data yet, but the client we've just started may happen to be
7182 * too fast and call openSession() that will fail (because of PID, etc.),
7183 * so that the Machine will never get out of the Spawning session state.
7184 */
7185
7186 /* inform the session that it will be a remote one */
7187 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
7188 HRESULT rc = aControl->AssignMachine(NULL);
7189 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
7190
7191 if (FAILED(rc))
7192 {
7193 /* restore the session state */
7194 mData->mSession.mState = SessionState_Unlocked;
7195 /* The failure may occur w/o any error info (from RPC), so provide one */
7196 return setError(VBOX_E_VM_ERROR,
7197 tr("Failed to assign the machine to the session (%Rrc)"), rc);
7198 }
7199
7200 /* attach launch data to the machine */
7201 Assert(mData->mSession.mPid == NIL_RTPROCESS);
7202 mData->mSession.mRemoteControls.push_back (aControl);
7203 mData->mSession.mProgress = aProgress;
7204 mData->mSession.mPid = pid;
7205 mData->mSession.mState = SessionState_Spawning;
7206 mData->mSession.mType = strType;
7207
7208 LogFlowThisFuncLeave();
7209 return S_OK;
7210}
7211
7212/**
7213 * Returns @c true if the given machine has an open direct session and returns
7214 * the session machine instance and additional session data (on some platforms)
7215 * if so.
7216 *
7217 * Note that when the method returns @c false, the arguments remain unchanged.
7218 *
7219 * @param aMachine Session machine object.
7220 * @param aControl Direct session control object (optional).
7221 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
7222 *
7223 * @note locks this object for reading.
7224 */
7225#if defined(RT_OS_WINDOWS)
7226bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7227 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7228 HANDLE *aIPCSem /*= NULL*/,
7229 bool aAllowClosing /*= false*/)
7230#elif defined(RT_OS_OS2)
7231bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7232 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7233 HMTX *aIPCSem /*= NULL*/,
7234 bool aAllowClosing /*= false*/)
7235#else
7236bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
7237 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
7238 bool aAllowClosing /*= false*/)
7239#endif
7240{
7241 AutoLimitedCaller autoCaller(this);
7242 AssertComRCReturn(autoCaller.rc(), false);
7243
7244 /* just return false for inaccessible machines */
7245 if (autoCaller.state() != Ready)
7246 return false;
7247
7248 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7249
7250 if ( mData->mSession.mState == SessionState_Locked
7251 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
7252 )
7253 {
7254 AssertReturn(!mData->mSession.mMachine.isNull(), false);
7255
7256 aMachine = mData->mSession.mMachine;
7257
7258 if (aControl != NULL)
7259 *aControl = mData->mSession.mDirectControl;
7260
7261#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7262 /* Additional session data */
7263 if (aIPCSem != NULL)
7264 *aIPCSem = aMachine->mIPCSem;
7265#endif
7266 return true;
7267 }
7268
7269 return false;
7270}
7271
7272/**
7273 * Returns @c true if the given machine has an spawning direct session and
7274 * returns and additional session data (on some platforms) if so.
7275 *
7276 * Note that when the method returns @c false, the arguments remain unchanged.
7277 *
7278 * @param aPID PID of the spawned direct session process.
7279 *
7280 * @note locks this object for reading.
7281 */
7282#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7283bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
7284#else
7285bool Machine::isSessionSpawning()
7286#endif
7287{
7288 AutoLimitedCaller autoCaller(this);
7289 AssertComRCReturn(autoCaller.rc(), false);
7290
7291 /* just return false for inaccessible machines */
7292 if (autoCaller.state() != Ready)
7293 return false;
7294
7295 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7296
7297 if (mData->mSession.mState == SessionState_Spawning)
7298 {
7299#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7300 /* Additional session data */
7301 if (aPID != NULL)
7302 {
7303 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
7304 *aPID = mData->mSession.mPid;
7305 }
7306#endif
7307 return true;
7308 }
7309
7310 return false;
7311}
7312
7313/**
7314 * Called from the client watcher thread to check for unexpected client process
7315 * death during Session_Spawning state (e.g. before it successfully opened a
7316 * direct session).
7317 *
7318 * On Win32 and on OS/2, this method is called only when we've got the
7319 * direct client's process termination notification, so it always returns @c
7320 * true.
7321 *
7322 * On other platforms, this method returns @c true if the client process is
7323 * terminated and @c false if it's still alive.
7324 *
7325 * @note Locks this object for writing.
7326 */
7327bool Machine::checkForSpawnFailure()
7328{
7329 AutoCaller autoCaller(this);
7330 if (!autoCaller.isOk())
7331 {
7332 /* nothing to do */
7333 LogFlowThisFunc(("Already uninitialized!\n"));
7334 return true;
7335 }
7336
7337 /* VirtualBox::addProcessToReap() needs a write lock */
7338 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
7339
7340 if (mData->mSession.mState != SessionState_Spawning)
7341 {
7342 /* nothing to do */
7343 LogFlowThisFunc(("Not spawning any more!\n"));
7344 return true;
7345 }
7346
7347 HRESULT rc = S_OK;
7348
7349#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
7350
7351 /* the process was already unexpectedly terminated, we just need to set an
7352 * error and finalize session spawning */
7353 rc = setError(E_FAIL,
7354 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
7355 getName().c_str());
7356#else
7357
7358 /* PID not yet initialized, skip check. */
7359 if (mData->mSession.mPid == NIL_RTPROCESS)
7360 return false;
7361
7362 RTPROCSTATUS status;
7363 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
7364 &status);
7365
7366 if (vrc != VERR_PROCESS_RUNNING)
7367 {
7368 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
7369 rc = setError(E_FAIL,
7370 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
7371 getName().c_str(), status.iStatus);
7372 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
7373 rc = setError(E_FAIL,
7374 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
7375 getName().c_str(), status.iStatus);
7376 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
7377 rc = setError(E_FAIL,
7378 tr("The virtual machine '%s' has terminated abnormally"),
7379 getName().c_str(), status.iStatus);
7380 else
7381 rc = setError(E_FAIL,
7382 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
7383 getName().c_str(), rc);
7384 }
7385
7386#endif
7387
7388 if (FAILED(rc))
7389 {
7390 /* Close the remote session, remove the remote control from the list
7391 * and reset session state to Closed (@note keep the code in sync with
7392 * the relevant part in checkForSpawnFailure()). */
7393
7394 Assert(mData->mSession.mRemoteControls.size() == 1);
7395 if (mData->mSession.mRemoteControls.size() == 1)
7396 {
7397 ErrorInfoKeeper eik;
7398 mData->mSession.mRemoteControls.front()->Uninitialize();
7399 }
7400
7401 mData->mSession.mRemoteControls.clear();
7402 mData->mSession.mState = SessionState_Unlocked;
7403
7404 /* finalize the progress after setting the state */
7405 if (!mData->mSession.mProgress.isNull())
7406 {
7407 mData->mSession.mProgress->notifyComplete(rc);
7408 mData->mSession.mProgress.setNull();
7409 }
7410
7411 mParent->addProcessToReap(mData->mSession.mPid);
7412 mData->mSession.mPid = NIL_RTPROCESS;
7413
7414 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
7415 return true;
7416 }
7417
7418 return false;
7419}
7420
7421/**
7422 * Checks whether the machine can be registered. If so, commits and saves
7423 * all settings.
7424 *
7425 * @note Must be called from mParent's write lock. Locks this object and
7426 * children for writing.
7427 */
7428HRESULT Machine::prepareRegister()
7429{
7430 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
7431
7432 AutoLimitedCaller autoCaller(this);
7433 AssertComRCReturnRC(autoCaller.rc());
7434
7435 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7436
7437 /* wait for state dependents to drop to zero */
7438 ensureNoStateDependencies();
7439
7440 if (!mData->mAccessible)
7441 return setError(VBOX_E_INVALID_OBJECT_STATE,
7442 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
7443 mUserData->s.strName.c_str(),
7444 mData->mUuid.toString().c_str());
7445
7446 AssertReturn(autoCaller.state() == Ready, E_FAIL);
7447
7448 if (mData->mRegistered)
7449 return setError(VBOX_E_INVALID_OBJECT_STATE,
7450 tr("The machine '%s' with UUID {%s} is already registered"),
7451 mUserData->s.strName.c_str(),
7452 mData->mUuid.toString().c_str());
7453
7454 HRESULT rc = S_OK;
7455
7456 // Ensure the settings are saved. If we are going to be registered and
7457 // no config file exists yet, create it by calling saveSettings() too.
7458 if ( (mData->flModifications)
7459 || (!mData->pMachineConfigFile->fileExists())
7460 )
7461 {
7462 rc = saveSettings(NULL);
7463 // no need to check whether VirtualBox.xml needs saving too since
7464 // we can't have a machine XML file rename pending
7465 if (FAILED(rc)) return rc;
7466 }
7467
7468 /* more config checking goes here */
7469
7470 if (SUCCEEDED(rc))
7471 {
7472 /* we may have had implicit modifications we want to fix on success */
7473 commit();
7474
7475 mData->mRegistered = true;
7476 }
7477 else
7478 {
7479 /* we may have had implicit modifications we want to cancel on failure*/
7480 rollback(false /* aNotify */);
7481 }
7482
7483 return rc;
7484}
7485
7486/**
7487 * Increases the number of objects dependent on the machine state or on the
7488 * registered state. Guarantees that these two states will not change at least
7489 * until #releaseStateDependency() is called.
7490 *
7491 * Depending on the @a aDepType value, additional state checks may be made.
7492 * These checks will set extended error info on failure. See
7493 * #checkStateDependency() for more info.
7494 *
7495 * If this method returns a failure, the dependency is not added and the caller
7496 * is not allowed to rely on any particular machine state or registration state
7497 * value and may return the failed result code to the upper level.
7498 *
7499 * @param aDepType Dependency type to add.
7500 * @param aState Current machine state (NULL if not interested).
7501 * @param aRegistered Current registered state (NULL if not interested).
7502 *
7503 * @note Locks this object for writing.
7504 */
7505HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
7506 MachineState_T *aState /* = NULL */,
7507 BOOL *aRegistered /* = NULL */)
7508{
7509 AutoCaller autoCaller(this);
7510 AssertComRCReturnRC(autoCaller.rc());
7511
7512 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7513
7514 HRESULT rc = checkStateDependency(aDepType);
7515 if (FAILED(rc)) return rc;
7516
7517 {
7518 if (mData->mMachineStateChangePending != 0)
7519 {
7520 /* ensureNoStateDependencies() is waiting for state dependencies to
7521 * drop to zero so don't add more. It may make sense to wait a bit
7522 * and retry before reporting an error (since the pending state
7523 * transition should be really quick) but let's just assert for
7524 * now to see if it ever happens on practice. */
7525
7526 AssertFailed();
7527
7528 return setError(E_ACCESSDENIED,
7529 tr("Machine state change is in progress. Please retry the operation later."));
7530 }
7531
7532 ++mData->mMachineStateDeps;
7533 Assert(mData->mMachineStateDeps != 0 /* overflow */);
7534 }
7535
7536 if (aState)
7537 *aState = mData->mMachineState;
7538 if (aRegistered)
7539 *aRegistered = mData->mRegistered;
7540
7541 return S_OK;
7542}
7543
7544/**
7545 * Decreases the number of objects dependent on the machine state.
7546 * Must always complete the #addStateDependency() call after the state
7547 * dependency is no more necessary.
7548 */
7549void Machine::releaseStateDependency()
7550{
7551 AutoCaller autoCaller(this);
7552 AssertComRCReturnVoid(autoCaller.rc());
7553
7554 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7555
7556 /* releaseStateDependency() w/o addStateDependency()? */
7557 AssertReturnVoid(mData->mMachineStateDeps != 0);
7558 -- mData->mMachineStateDeps;
7559
7560 if (mData->mMachineStateDeps == 0)
7561 {
7562 /* inform ensureNoStateDependencies() that there are no more deps */
7563 if (mData->mMachineStateChangePending != 0)
7564 {
7565 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
7566 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
7567 }
7568 }
7569}
7570
7571// protected methods
7572/////////////////////////////////////////////////////////////////////////////
7573
7574/**
7575 * Performs machine state checks based on the @a aDepType value. If a check
7576 * fails, this method will set extended error info, otherwise it will return
7577 * S_OK. It is supposed, that on failure, the caller will immediately return
7578 * the return value of this method to the upper level.
7579 *
7580 * When @a aDepType is AnyStateDep, this method always returns S_OK.
7581 *
7582 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
7583 * current state of this machine object allows to change settings of the
7584 * machine (i.e. the machine is not registered, or registered but not running
7585 * and not saved). It is useful to call this method from Machine setters
7586 * before performing any change.
7587 *
7588 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
7589 * as for MutableStateDep except that if the machine is saved, S_OK is also
7590 * returned. This is useful in setters which allow changing machine
7591 * properties when it is in the saved state.
7592 *
7593 * @param aDepType Dependency type to check.
7594 *
7595 * @note Non Machine based classes should use #addStateDependency() and
7596 * #releaseStateDependency() methods or the smart AutoStateDependency
7597 * template.
7598 *
7599 * @note This method must be called from under this object's read or write
7600 * lock.
7601 */
7602HRESULT Machine::checkStateDependency(StateDependency aDepType)
7603{
7604 switch (aDepType)
7605 {
7606 case AnyStateDep:
7607 {
7608 break;
7609 }
7610 case MutableStateDep:
7611 {
7612 if ( mData->mRegistered
7613 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
7614 || ( mData->mMachineState != MachineState_Paused
7615 && mData->mMachineState != MachineState_Running
7616 && mData->mMachineState != MachineState_Aborted
7617 && mData->mMachineState != MachineState_Teleported
7618 && mData->mMachineState != MachineState_PoweredOff
7619 )
7620 )
7621 )
7622 return setError(VBOX_E_INVALID_VM_STATE,
7623 tr("The machine is not mutable (state is %s)"),
7624 Global::stringifyMachineState(mData->mMachineState));
7625 break;
7626 }
7627 case MutableOrSavedStateDep:
7628 {
7629 if ( mData->mRegistered
7630 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
7631 || ( mData->mMachineState != MachineState_Paused
7632 && mData->mMachineState != MachineState_Running
7633 && mData->mMachineState != MachineState_Aborted
7634 && mData->mMachineState != MachineState_Teleported
7635 && mData->mMachineState != MachineState_Saved
7636 && mData->mMachineState != MachineState_PoweredOff
7637 )
7638 )
7639 )
7640 return setError(VBOX_E_INVALID_VM_STATE,
7641 tr("The machine is not mutable (state is %s)"),
7642 Global::stringifyMachineState(mData->mMachineState));
7643 break;
7644 }
7645 }
7646
7647 return S_OK;
7648}
7649
7650/**
7651 * Helper to initialize all associated child objects and allocate data
7652 * structures.
7653 *
7654 * This method must be called as a part of the object's initialization procedure
7655 * (usually done in the #init() method).
7656 *
7657 * @note Must be called only from #init() or from #registeredInit().
7658 */
7659HRESULT Machine::initDataAndChildObjects()
7660{
7661 AutoCaller autoCaller(this);
7662 AssertComRCReturnRC(autoCaller.rc());
7663 AssertComRCReturn(autoCaller.state() == InInit ||
7664 autoCaller.state() == Limited, E_FAIL);
7665
7666 AssertReturn(!mData->mAccessible, E_FAIL);
7667
7668 /* allocate data structures */
7669 mSSData.allocate();
7670 mUserData.allocate();
7671 mHWData.allocate();
7672 mMediaData.allocate();
7673 mStorageControllers.allocate();
7674
7675 /* initialize mOSTypeId */
7676 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
7677
7678 /* create associated BIOS settings object */
7679 unconst(mBIOSSettings).createObject();
7680 mBIOSSettings->init(this);
7681
7682 /* create an associated VRDE object (default is disabled) */
7683 unconst(mVRDEServer).createObject();
7684 mVRDEServer->init(this);
7685
7686 /* create associated serial port objects */
7687 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7688 {
7689 unconst(mSerialPorts[slot]).createObject();
7690 mSerialPorts[slot]->init(this, slot);
7691 }
7692
7693 /* create associated parallel port objects */
7694 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7695 {
7696 unconst(mParallelPorts[slot]).createObject();
7697 mParallelPorts[slot]->init(this, slot);
7698 }
7699
7700 /* create the audio adapter object (always present, default is disabled) */
7701 unconst(mAudioAdapter).createObject();
7702 mAudioAdapter->init(this);
7703
7704 /* create the USB controller object (always present, default is disabled) */
7705 unconst(mUSBController).createObject();
7706 mUSBController->init(this);
7707
7708 /* create associated network adapter objects */
7709 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
7710 {
7711 unconst(mNetworkAdapters[slot]).createObject();
7712 mNetworkAdapters[slot]->init(this, slot);
7713 }
7714
7715 /* create the bandwidth control */
7716 unconst(mBandwidthControl).createObject();
7717 mBandwidthControl->init(this);
7718
7719 return S_OK;
7720}
7721
7722/**
7723 * Helper to uninitialize all associated child objects and to free all data
7724 * structures.
7725 *
7726 * This method must be called as a part of the object's uninitialization
7727 * procedure (usually done in the #uninit() method).
7728 *
7729 * @note Must be called only from #uninit() or from #registeredInit().
7730 */
7731void Machine::uninitDataAndChildObjects()
7732{
7733 AutoCaller autoCaller(this);
7734 AssertComRCReturnVoid(autoCaller.rc());
7735 AssertComRCReturnVoid( autoCaller.state() == InUninit
7736 || autoCaller.state() == Limited);
7737
7738 /* tell all our other child objects we've been uninitialized */
7739 if (mBandwidthControl)
7740 {
7741 mBandwidthControl->uninit();
7742 unconst(mBandwidthControl).setNull();
7743 }
7744
7745 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
7746 {
7747 if (mNetworkAdapters[slot])
7748 {
7749 mNetworkAdapters[slot]->uninit();
7750 unconst(mNetworkAdapters[slot]).setNull();
7751 }
7752 }
7753
7754 if (mUSBController)
7755 {
7756 mUSBController->uninit();
7757 unconst(mUSBController).setNull();
7758 }
7759
7760 if (mAudioAdapter)
7761 {
7762 mAudioAdapter->uninit();
7763 unconst(mAudioAdapter).setNull();
7764 }
7765
7766 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7767 {
7768 if (mParallelPorts[slot])
7769 {
7770 mParallelPorts[slot]->uninit();
7771 unconst(mParallelPorts[slot]).setNull();
7772 }
7773 }
7774
7775 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7776 {
7777 if (mSerialPorts[slot])
7778 {
7779 mSerialPorts[slot]->uninit();
7780 unconst(mSerialPorts[slot]).setNull();
7781 }
7782 }
7783
7784 if (mVRDEServer)
7785 {
7786 mVRDEServer->uninit();
7787 unconst(mVRDEServer).setNull();
7788 }
7789
7790 if (mBIOSSettings)
7791 {
7792 mBIOSSettings->uninit();
7793 unconst(mBIOSSettings).setNull();
7794 }
7795
7796 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
7797 * instance is uninitialized; SessionMachine instances refer to real
7798 * Machine hard disks). This is necessary for a clean re-initialization of
7799 * the VM after successfully re-checking the accessibility state. Note
7800 * that in case of normal Machine or SnapshotMachine uninitialization (as
7801 * a result of unregistering or deleting the snapshot), outdated hard
7802 * disk attachments will already be uninitialized and deleted, so this
7803 * code will not affect them. */
7804 if ( !!mMediaData
7805 && (!isSessionMachine())
7806 )
7807 {
7808 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7809 it != mMediaData->mAttachments.end();
7810 ++it)
7811 {
7812 ComObjPtr<Medium> hd = (*it)->getMedium();
7813 if (hd.isNull())
7814 continue;
7815 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
7816 AssertComRC(rc);
7817 }
7818 }
7819
7820 if (!isSessionMachine() && !isSnapshotMachine())
7821 {
7822 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
7823 if (mData->mFirstSnapshot)
7824 {
7825 // snapshots tree is protected by media write lock; strictly
7826 // this isn't necessary here since we're deleting the entire
7827 // machine, but otherwise we assert in Snapshot::uninit()
7828 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7829 mData->mFirstSnapshot->uninit();
7830 mData->mFirstSnapshot.setNull();
7831 }
7832
7833 mData->mCurrentSnapshot.setNull();
7834 }
7835
7836 /* free data structures (the essential mData structure is not freed here
7837 * since it may be still in use) */
7838 mMediaData.free();
7839 mStorageControllers.free();
7840 mHWData.free();
7841 mUserData.free();
7842 mSSData.free();
7843}
7844
7845/**
7846 * Returns a pointer to the Machine object for this machine that acts like a
7847 * parent for complex machine data objects such as shared folders, etc.
7848 *
7849 * For primary Machine objects and for SnapshotMachine objects, returns this
7850 * object's pointer itself. For SessionMachine objects, returns the peer
7851 * (primary) machine pointer.
7852 */
7853Machine* Machine::getMachine()
7854{
7855 if (isSessionMachine())
7856 return (Machine*)mPeer;
7857 return this;
7858}
7859
7860/**
7861 * Makes sure that there are no machine state dependents. If necessary, waits
7862 * for the number of dependents to drop to zero.
7863 *
7864 * Make sure this method is called from under this object's write lock to
7865 * guarantee that no new dependents may be added when this method returns
7866 * control to the caller.
7867 *
7868 * @note Locks this object for writing. The lock will be released while waiting
7869 * (if necessary).
7870 *
7871 * @warning To be used only in methods that change the machine state!
7872 */
7873void Machine::ensureNoStateDependencies()
7874{
7875 AssertReturnVoid(isWriteLockOnCurrentThread());
7876
7877 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7878
7879 /* Wait for all state dependents if necessary */
7880 if (mData->mMachineStateDeps != 0)
7881 {
7882 /* lazy semaphore creation */
7883 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
7884 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
7885
7886 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
7887 mData->mMachineStateDeps));
7888
7889 ++mData->mMachineStateChangePending;
7890
7891 /* reset the semaphore before waiting, the last dependent will signal
7892 * it */
7893 RTSemEventMultiReset(mData->mMachineStateDepsSem);
7894
7895 alock.leave();
7896
7897 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
7898
7899 alock.enter();
7900
7901 -- mData->mMachineStateChangePending;
7902 }
7903}
7904
7905/**
7906 * Changes the machine state and informs callbacks.
7907 *
7908 * This method is not intended to fail so it either returns S_OK or asserts (and
7909 * returns a failure).
7910 *
7911 * @note Locks this object for writing.
7912 */
7913HRESULT Machine::setMachineState(MachineState_T aMachineState)
7914{
7915 LogFlowThisFuncEnter();
7916 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
7917
7918 AutoCaller autoCaller(this);
7919 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7920
7921 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7922
7923 /* wait for state dependents to drop to zero */
7924 ensureNoStateDependencies();
7925
7926 if (mData->mMachineState != aMachineState)
7927 {
7928 mData->mMachineState = aMachineState;
7929
7930 RTTimeNow(&mData->mLastStateChange);
7931
7932 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7933 }
7934
7935 LogFlowThisFuncLeave();
7936 return S_OK;
7937}
7938
7939/**
7940 * Searches for a shared folder with the given logical name
7941 * in the collection of shared folders.
7942 *
7943 * @param aName logical name of the shared folder
7944 * @param aSharedFolder where to return the found object
7945 * @param aSetError whether to set the error info if the folder is
7946 * not found
7947 * @return
7948 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7949 *
7950 * @note
7951 * must be called from under the object's lock!
7952 */
7953HRESULT Machine::findSharedFolder(const Utf8Str &aName,
7954 ComObjPtr<SharedFolder> &aSharedFolder,
7955 bool aSetError /* = false */)
7956{
7957 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
7958 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7959 it != mHWData->mSharedFolders.end();
7960 ++it)
7961 {
7962 SharedFolder *pSF = *it;
7963 AutoCaller autoCaller(pSF);
7964 if (pSF->getName() == aName)
7965 {
7966 aSharedFolder = pSF;
7967 rc = S_OK;
7968 break;
7969 }
7970 }
7971
7972 if (aSetError && FAILED(rc))
7973 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
7974
7975 return rc;
7976}
7977
7978/**
7979 * Initializes all machine instance data from the given settings structures
7980 * from XML. The exception is the machine UUID which needs special handling
7981 * depending on the caller's use case, so the caller needs to set that herself.
7982 *
7983 * This gets called in several contexts during machine initialization:
7984 *
7985 * -- When machine XML exists on disk already and needs to be loaded into memory,
7986 * for example, from registeredInit() to load all registered machines on
7987 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7988 * attached to the machine should be part of some media registry already.
7989 *
7990 * -- During OVF import, when a machine config has been constructed from an
7991 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7992 * ensure that the media listed as attachments in the config (which have
7993 * been imported from the OVF) receive the correct registry ID.
7994 *
7995 * -- During VM cloning.
7996 *
7997 * @param config Machine settings from XML.
7998 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7999 * @return
8000 */
8001HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
8002 const Guid *puuidRegistry)
8003{
8004 // copy name, description, OS type, teleporter, UTC etc.
8005 mUserData->s = config.machineUserData;
8006
8007 // look up the object by Id to check it is valid
8008 ComPtr<IGuestOSType> guestOSType;
8009 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
8010 guestOSType.asOutParam());
8011 if (FAILED(rc)) return rc;
8012
8013 // stateFile (optional)
8014 if (config.strStateFile.isEmpty())
8015 mSSData->strStateFilePath.setNull();
8016 else
8017 {
8018 Utf8Str stateFilePathFull(config.strStateFile);
8019 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
8020 if (RT_FAILURE(vrc))
8021 return setError(E_FAIL,
8022 tr("Invalid saved state file path '%s' (%Rrc)"),
8023 config.strStateFile.c_str(),
8024 vrc);
8025 mSSData->strStateFilePath = stateFilePathFull;
8026 }
8027
8028 // snapshot folder needs special processing so set it again
8029 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
8030 if (FAILED(rc)) return rc;
8031
8032 /* currentStateModified (optional, default is true) */
8033 mData->mCurrentStateModified = config.fCurrentStateModified;
8034
8035 mData->mLastStateChange = config.timeLastStateChange;
8036
8037 /*
8038 * note: all mUserData members must be assigned prior this point because
8039 * we need to commit changes in order to let mUserData be shared by all
8040 * snapshot machine instances.
8041 */
8042 mUserData.commitCopy();
8043
8044 // machine registry, if present (must be loaded before snapshots)
8045 if (config.canHaveOwnMediaRegistry())
8046 {
8047 // determine machine folder
8048 Utf8Str strMachineFolder = getSettingsFileFull();
8049 strMachineFolder.stripFilename();
8050 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
8051 config.mediaRegistry,
8052 strMachineFolder);
8053 if (FAILED(rc)) return rc;
8054 }
8055
8056 /* Snapshot node (optional) */
8057 size_t cRootSnapshots;
8058 if ((cRootSnapshots = config.llFirstSnapshot.size()))
8059 {
8060 // there must be only one root snapshot
8061 Assert(cRootSnapshots == 1);
8062
8063 const settings::Snapshot &snap = config.llFirstSnapshot.front();
8064
8065 rc = loadSnapshot(snap,
8066 config.uuidCurrentSnapshot,
8067 NULL); // no parent == first snapshot
8068 if (FAILED(rc)) return rc;
8069 }
8070
8071 // hardware data
8072 rc = loadHardware(config.hardwareMachine);
8073 if (FAILED(rc)) return rc;
8074
8075 // load storage controllers
8076 rc = loadStorageControllers(config.storageMachine,
8077 puuidRegistry,
8078 NULL /* puuidSnapshot */);
8079 if (FAILED(rc)) return rc;
8080
8081 /*
8082 * NOTE: the assignment below must be the last thing to do,
8083 * otherwise it will be not possible to change the settings
8084 * somewhere in the code above because all setters will be
8085 * blocked by checkStateDependency(MutableStateDep).
8086 */
8087
8088 /* set the machine state to Aborted or Saved when appropriate */
8089 if (config.fAborted)
8090 {
8091 Assert(!mSSData->strStateFilePath.isEmpty());
8092 mSSData->strStateFilePath.setNull();
8093
8094 /* no need to use setMachineState() during init() */
8095 mData->mMachineState = MachineState_Aborted;
8096 }
8097 else if (!mSSData->strStateFilePath.isEmpty())
8098 {
8099 /* no need to use setMachineState() during init() */
8100 mData->mMachineState = MachineState_Saved;
8101 }
8102
8103 // after loading settings, we are no longer different from the XML on disk
8104 mData->flModifications = 0;
8105
8106 return S_OK;
8107}
8108
8109/**
8110 * Recursively loads all snapshots starting from the given.
8111 *
8112 * @param aNode <Snapshot> node.
8113 * @param aCurSnapshotId Current snapshot ID from the settings file.
8114 * @param aParentSnapshot Parent snapshot.
8115 */
8116HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
8117 const Guid &aCurSnapshotId,
8118 Snapshot *aParentSnapshot)
8119{
8120 AssertReturn(!isSnapshotMachine(), E_FAIL);
8121 AssertReturn(!isSessionMachine(), E_FAIL);
8122
8123 HRESULT rc = S_OK;
8124
8125 Utf8Str strStateFile;
8126 if (!data.strStateFile.isEmpty())
8127 {
8128 /* optional */
8129 strStateFile = data.strStateFile;
8130 int vrc = calculateFullPath(strStateFile, strStateFile);
8131 if (RT_FAILURE(vrc))
8132 return setError(E_FAIL,
8133 tr("Invalid saved state file path '%s' (%Rrc)"),
8134 strStateFile.c_str(),
8135 vrc);
8136 }
8137
8138 /* create a snapshot machine object */
8139 ComObjPtr<SnapshotMachine> pSnapshotMachine;
8140 pSnapshotMachine.createObject();
8141 rc = pSnapshotMachine->init(this,
8142 data.hardware,
8143 data.storage,
8144 data.uuid.ref(),
8145 strStateFile);
8146 if (FAILED(rc)) return rc;
8147
8148 /* create a snapshot object */
8149 ComObjPtr<Snapshot> pSnapshot;
8150 pSnapshot.createObject();
8151 /* initialize the snapshot */
8152 rc = pSnapshot->init(mParent, // VirtualBox object
8153 data.uuid,
8154 data.strName,
8155 data.strDescription,
8156 data.timestamp,
8157 pSnapshotMachine,
8158 aParentSnapshot);
8159 if (FAILED(rc)) return rc;
8160
8161 /* memorize the first snapshot if necessary */
8162 if (!mData->mFirstSnapshot)
8163 mData->mFirstSnapshot = pSnapshot;
8164
8165 /* memorize the current snapshot when appropriate */
8166 if ( !mData->mCurrentSnapshot
8167 && pSnapshot->getId() == aCurSnapshotId
8168 )
8169 mData->mCurrentSnapshot = pSnapshot;
8170
8171 // now create the children
8172 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
8173 it != data.llChildSnapshots.end();
8174 ++it)
8175 {
8176 const settings::Snapshot &childData = *it;
8177 // recurse
8178 rc = loadSnapshot(childData,
8179 aCurSnapshotId,
8180 pSnapshot); // parent = the one we created above
8181 if (FAILED(rc)) return rc;
8182 }
8183
8184 return rc;
8185}
8186
8187/**
8188 * @param aNode <Hardware> node.
8189 */
8190HRESULT Machine::loadHardware(const settings::Hardware &data)
8191{
8192 AssertReturn(!isSessionMachine(), E_FAIL);
8193
8194 HRESULT rc = S_OK;
8195
8196 try
8197 {
8198 /* The hardware version attribute (optional). */
8199 mHWData->mHWVersion = data.strVersion;
8200 mHWData->mHardwareUUID = data.uuid;
8201
8202 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
8203 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
8204 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
8205 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
8206 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
8207 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
8208 mHWData->mPAEEnabled = data.fPAE;
8209 mHWData->mSyntheticCpu = data.fSyntheticCpu;
8210
8211 mHWData->mCPUCount = data.cCPUs;
8212 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
8213 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
8214
8215 // cpu
8216 if (mHWData->mCPUHotPlugEnabled)
8217 {
8218 for (settings::CpuList::const_iterator it = data.llCpus.begin();
8219 it != data.llCpus.end();
8220 ++it)
8221 {
8222 const settings::Cpu &cpu = *it;
8223
8224 mHWData->mCPUAttached[cpu.ulId] = true;
8225 }
8226 }
8227
8228 // cpuid leafs
8229 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
8230 it != data.llCpuIdLeafs.end();
8231 ++it)
8232 {
8233 const settings::CpuIdLeaf &leaf = *it;
8234
8235 switch (leaf.ulId)
8236 {
8237 case 0x0:
8238 case 0x1:
8239 case 0x2:
8240 case 0x3:
8241 case 0x4:
8242 case 0x5:
8243 case 0x6:
8244 case 0x7:
8245 case 0x8:
8246 case 0x9:
8247 case 0xA:
8248 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
8249 break;
8250
8251 case 0x80000000:
8252 case 0x80000001:
8253 case 0x80000002:
8254 case 0x80000003:
8255 case 0x80000004:
8256 case 0x80000005:
8257 case 0x80000006:
8258 case 0x80000007:
8259 case 0x80000008:
8260 case 0x80000009:
8261 case 0x8000000A:
8262 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
8263 break;
8264
8265 default:
8266 /* just ignore */
8267 break;
8268 }
8269 }
8270
8271 mHWData->mMemorySize = data.ulMemorySizeMB;
8272 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
8273
8274 // boot order
8275 for (size_t i = 0;
8276 i < RT_ELEMENTS(mHWData->mBootOrder);
8277 i++)
8278 {
8279 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
8280 if (it == data.mapBootOrder.end())
8281 mHWData->mBootOrder[i] = DeviceType_Null;
8282 else
8283 mHWData->mBootOrder[i] = it->second;
8284 }
8285
8286 mHWData->mVRAMSize = data.ulVRAMSizeMB;
8287 mHWData->mMonitorCount = data.cMonitors;
8288 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
8289 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
8290 mHWData->mFirmwareType = data.firmwareType;
8291 mHWData->mPointingHidType = data.pointingHidType;
8292 mHWData->mKeyboardHidType = data.keyboardHidType;
8293 mHWData->mChipsetType = data.chipsetType;
8294 mHWData->mHpetEnabled = data.fHpetEnabled;
8295
8296 /* VRDEServer */
8297 rc = mVRDEServer->loadSettings(data.vrdeSettings);
8298 if (FAILED(rc)) return rc;
8299
8300 /* BIOS */
8301 rc = mBIOSSettings->loadSettings(data.biosSettings);
8302 if (FAILED(rc)) return rc;
8303
8304 // Bandwidth control (must come before network adapters)
8305 rc = mBandwidthControl->loadSettings(data.ioSettings);
8306 if (FAILED(rc)) return rc;
8307
8308 /* USB Controller */
8309 rc = mUSBController->loadSettings(data.usbController);
8310 if (FAILED(rc)) return rc;
8311
8312 // network adapters
8313 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
8314 it != data.llNetworkAdapters.end();
8315 ++it)
8316 {
8317 const settings::NetworkAdapter &nic = *it;
8318
8319 /* slot unicity is guaranteed by XML Schema */
8320 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
8321 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
8322 if (FAILED(rc)) return rc;
8323 }
8324
8325 // serial ports
8326 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
8327 it != data.llSerialPorts.end();
8328 ++it)
8329 {
8330 const settings::SerialPort &s = *it;
8331
8332 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
8333 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
8334 if (FAILED(rc)) return rc;
8335 }
8336
8337 // parallel ports (optional)
8338 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
8339 it != data.llParallelPorts.end();
8340 ++it)
8341 {
8342 const settings::ParallelPort &p = *it;
8343
8344 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
8345 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
8346 if (FAILED(rc)) return rc;
8347 }
8348
8349 /* AudioAdapter */
8350 rc = mAudioAdapter->loadSettings(data.audioAdapter);
8351 if (FAILED(rc)) return rc;
8352
8353 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
8354 it != data.llSharedFolders.end();
8355 ++it)
8356 {
8357 const settings::SharedFolder &sf = *it;
8358 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
8359 Bstr(sf.strHostPath).raw(),
8360 sf.fWritable, sf.fAutoMount);
8361 if (FAILED(rc)) return rc;
8362 }
8363
8364 // Clipboard
8365 mHWData->mClipboardMode = data.clipboardMode;
8366
8367 // guest settings
8368 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
8369
8370 // IO settings
8371 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
8372 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
8373
8374 // Host PCI devices
8375 for (settings::HostPciDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
8376 it != data.pciAttachments.end();
8377 ++it)
8378 {
8379 const settings::HostPciDeviceAttachment &hpda = *it;
8380 ComObjPtr<PciDeviceAttachment> pda;
8381
8382 pda.createObject();
8383 pda->loadSettings(this, hpda);
8384 mHWData->mPciDeviceAssignments.push_back(pda);
8385 }
8386
8387#ifdef VBOX_WITH_GUEST_PROPS
8388 /* Guest properties (optional) */
8389 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
8390 it != data.llGuestProperties.end();
8391 ++it)
8392 {
8393 const settings::GuestProperty &prop = *it;
8394 uint32_t fFlags = guestProp::NILFLAG;
8395 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
8396 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
8397 mHWData->mGuestProperties.push_back(property);
8398 }
8399
8400 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
8401#endif /* VBOX_WITH_GUEST_PROPS defined */
8402 }
8403 catch(std::bad_alloc &)
8404 {
8405 return E_OUTOFMEMORY;
8406 }
8407
8408 AssertComRC(rc);
8409 return rc;
8410}
8411
8412/**
8413 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
8414 *
8415 * @param data
8416 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
8417 * @param puuidSnapshot
8418 * @return
8419 */
8420HRESULT Machine::loadStorageControllers(const settings::Storage &data,
8421 const Guid *puuidRegistry,
8422 const Guid *puuidSnapshot)
8423{
8424 AssertReturn(!isSessionMachine(), E_FAIL);
8425
8426 HRESULT rc = S_OK;
8427
8428 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
8429 it != data.llStorageControllers.end();
8430 ++it)
8431 {
8432 const settings::StorageController &ctlData = *it;
8433
8434 ComObjPtr<StorageController> pCtl;
8435 /* Try to find one with the name first. */
8436 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
8437 if (SUCCEEDED(rc))
8438 return setError(VBOX_E_OBJECT_IN_USE,
8439 tr("Storage controller named '%s' already exists"),
8440 ctlData.strName.c_str());
8441
8442 pCtl.createObject();
8443 rc = pCtl->init(this,
8444 ctlData.strName,
8445 ctlData.storageBus,
8446 ctlData.ulInstance,
8447 ctlData.fBootable);
8448 if (FAILED(rc)) return rc;
8449
8450 mStorageControllers->push_back(pCtl);
8451
8452 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
8453 if (FAILED(rc)) return rc;
8454
8455 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
8456 if (FAILED(rc)) return rc;
8457
8458 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
8459 if (FAILED(rc)) return rc;
8460
8461 /* Set IDE emulation settings (only for AHCI controller). */
8462 if (ctlData.controllerType == StorageControllerType_IntelAhci)
8463 {
8464 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
8465 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
8466 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
8467 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
8468 )
8469 return rc;
8470 }
8471
8472 /* Load the attached devices now. */
8473 rc = loadStorageDevices(pCtl,
8474 ctlData,
8475 puuidRegistry,
8476 puuidSnapshot);
8477 if (FAILED(rc)) return rc;
8478 }
8479
8480 return S_OK;
8481}
8482
8483/**
8484 * Called from loadStorageControllers for a controller's devices.
8485 *
8486 * @param aStorageController
8487 * @param data
8488 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
8489 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
8490 * @return
8491 */
8492HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
8493 const settings::StorageController &data,
8494 const Guid *puuidRegistry,
8495 const Guid *puuidSnapshot)
8496{
8497 HRESULT rc = S_OK;
8498
8499 /* paranoia: detect duplicate attachments */
8500 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
8501 it != data.llAttachedDevices.end();
8502 ++it)
8503 {
8504 const settings::AttachedDevice &ad = *it;
8505
8506 for (settings::AttachedDevicesList::const_iterator it2 = it;
8507 it2 != data.llAttachedDevices.end();
8508 ++it2)
8509 {
8510 if (it == it2)
8511 continue;
8512
8513 const settings::AttachedDevice &ad2 = *it2;
8514
8515 if ( ad.lPort == ad2.lPort
8516 && ad.lDevice == ad2.lDevice)
8517 {
8518 return setError(E_FAIL,
8519 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
8520 aStorageController->getName().c_str(),
8521 ad.lPort,
8522 ad.lDevice,
8523 mUserData->s.strName.c_str());
8524 }
8525 }
8526 }
8527
8528 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
8529 it != data.llAttachedDevices.end();
8530 ++it)
8531 {
8532 const settings::AttachedDevice &dev = *it;
8533 ComObjPtr<Medium> medium;
8534
8535 switch (dev.deviceType)
8536 {
8537 case DeviceType_Floppy:
8538 case DeviceType_DVD:
8539 if (dev.strHostDriveSrc.isNotEmpty())
8540 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
8541 else
8542 rc = mParent->findRemoveableMedium(dev.deviceType,
8543 dev.uuid,
8544 false /* fRefresh */,
8545 false /* aSetError */,
8546 medium);
8547 if (rc == VBOX_E_OBJECT_NOT_FOUND)
8548 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
8549 rc = S_OK;
8550 break;
8551
8552 case DeviceType_HardDisk:
8553 {
8554 /* find a hard disk by UUID */
8555 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
8556 if (FAILED(rc))
8557 {
8558 if (isSnapshotMachine())
8559 {
8560 // wrap another error message around the "cannot find hard disk" set by findHardDisk
8561 // so the user knows that the bad disk is in a snapshot somewhere
8562 com::ErrorInfo info;
8563 return setError(E_FAIL,
8564 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
8565 puuidSnapshot->raw(),
8566 info.getText().raw());
8567 }
8568 else
8569 return rc;
8570 }
8571
8572 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
8573
8574 if (medium->getType() == MediumType_Immutable)
8575 {
8576 if (isSnapshotMachine())
8577 return setError(E_FAIL,
8578 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
8579 "of the virtual machine '%s' ('%s')"),
8580 medium->getLocationFull().c_str(),
8581 dev.uuid.raw(),
8582 puuidSnapshot->raw(),
8583 mUserData->s.strName.c_str(),
8584 mData->m_strConfigFileFull.c_str());
8585
8586 return setError(E_FAIL,
8587 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
8588 medium->getLocationFull().c_str(),
8589 dev.uuid.raw(),
8590 mUserData->s.strName.c_str(),
8591 mData->m_strConfigFileFull.c_str());
8592 }
8593
8594 if (medium->getType() == MediumType_MultiAttach)
8595 {
8596 if (isSnapshotMachine())
8597 return setError(E_FAIL,
8598 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
8599 "of the virtual machine '%s' ('%s')"),
8600 medium->getLocationFull().c_str(),
8601 dev.uuid.raw(),
8602 puuidSnapshot->raw(),
8603 mUserData->s.strName.c_str(),
8604 mData->m_strConfigFileFull.c_str());
8605
8606 return setError(E_FAIL,
8607 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
8608 medium->getLocationFull().c_str(),
8609 dev.uuid.raw(),
8610 mUserData->s.strName.c_str(),
8611 mData->m_strConfigFileFull.c_str());
8612 }
8613
8614 if ( !isSnapshotMachine()
8615 && medium->getChildren().size() != 0
8616 )
8617 return setError(E_FAIL,
8618 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
8619 "because it has %d differencing child hard disks"),
8620 medium->getLocationFull().c_str(),
8621 dev.uuid.raw(),
8622 mUserData->s.strName.c_str(),
8623 mData->m_strConfigFileFull.c_str(),
8624 medium->getChildren().size());
8625
8626 if (findAttachment(mMediaData->mAttachments,
8627 medium))
8628 return setError(E_FAIL,
8629 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
8630 medium->getLocationFull().c_str(),
8631 dev.uuid.raw(),
8632 mUserData->s.strName.c_str(),
8633 mData->m_strConfigFileFull.c_str());
8634
8635 break;
8636 }
8637
8638 default:
8639 return setError(E_FAIL,
8640 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
8641 medium->getLocationFull().c_str(),
8642 mUserData->s.strName.c_str(),
8643 mData->m_strConfigFileFull.c_str());
8644 }
8645
8646 if (FAILED(rc))
8647 break;
8648
8649 /* Bandwidth groups are loaded at this point. */
8650 ComObjPtr<BandwidthGroup> pBwGroup;
8651
8652 if (!dev.strBwGroup.isEmpty())
8653 {
8654 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
8655 if (FAILED(rc))
8656 return setError(E_FAIL,
8657 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
8658 medium->getLocationFull().c_str(),
8659 dev.strBwGroup.c_str(),
8660 mUserData->s.strName.c_str(),
8661 mData->m_strConfigFileFull.c_str());
8662 pBwGroup->reference();
8663 }
8664
8665 const Bstr controllerName = aStorageController->getName();
8666 ComObjPtr<MediumAttachment> pAttachment;
8667 pAttachment.createObject();
8668 rc = pAttachment->init(this,
8669 medium,
8670 controllerName,
8671 dev.lPort,
8672 dev.lDevice,
8673 dev.deviceType,
8674 dev.fPassThrough,
8675 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
8676 if (FAILED(rc)) break;
8677
8678 /* associate the medium with this machine and snapshot */
8679 if (!medium.isNull())
8680 {
8681 AutoCaller medCaller(medium);
8682 if (FAILED(medCaller.rc())) return medCaller.rc();
8683 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
8684
8685 if (isSnapshotMachine())
8686 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
8687 else
8688 rc = medium->addBackReference(mData->mUuid);
8689 /* If the medium->addBackReference fails it sets an appropriate
8690 * error message, so no need to do any guesswork here. */
8691
8692 if (puuidRegistry)
8693 // caller wants registry ID to be set on all attached media (OVF import case)
8694 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
8695 }
8696
8697 if (FAILED(rc))
8698 break;
8699
8700 /* back up mMediaData to let registeredInit() properly rollback on failure
8701 * (= limited accessibility) */
8702 setModified(IsModified_Storage);
8703 mMediaData.backup();
8704 mMediaData->mAttachments.push_back(pAttachment);
8705 }
8706
8707 return rc;
8708}
8709
8710/**
8711 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
8712 *
8713 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
8714 * @param aSnapshot where to return the found snapshot
8715 * @param aSetError true to set extended error info on failure
8716 */
8717HRESULT Machine::findSnapshotById(const Guid &aId,
8718 ComObjPtr<Snapshot> &aSnapshot,
8719 bool aSetError /* = false */)
8720{
8721 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8722
8723 if (!mData->mFirstSnapshot)
8724 {
8725 if (aSetError)
8726 return setError(E_FAIL, tr("This machine does not have any snapshots"));
8727 return E_FAIL;
8728 }
8729
8730 if (aId.isEmpty())
8731 aSnapshot = mData->mFirstSnapshot;
8732 else
8733 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
8734
8735 if (!aSnapshot)
8736 {
8737 if (aSetError)
8738 return setError(E_FAIL,
8739 tr("Could not find a snapshot with UUID {%s}"),
8740 aId.toString().c_str());
8741 return E_FAIL;
8742 }
8743
8744 return S_OK;
8745}
8746
8747/**
8748 * Returns the snapshot with the given name or fails of no such snapshot.
8749 *
8750 * @param aName snapshot name to find
8751 * @param aSnapshot where to return the found snapshot
8752 * @param aSetError true to set extended error info on failure
8753 */
8754HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
8755 ComObjPtr<Snapshot> &aSnapshot,
8756 bool aSetError /* = false */)
8757{
8758 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
8759
8760 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8761
8762 if (!mData->mFirstSnapshot)
8763 {
8764 if (aSetError)
8765 return setError(VBOX_E_OBJECT_NOT_FOUND,
8766 tr("This machine does not have any snapshots"));
8767 return VBOX_E_OBJECT_NOT_FOUND;
8768 }
8769
8770 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
8771
8772 if (!aSnapshot)
8773 {
8774 if (aSetError)
8775 return setError(VBOX_E_OBJECT_NOT_FOUND,
8776 tr("Could not find a snapshot named '%s'"), strName.c_str());
8777 return VBOX_E_OBJECT_NOT_FOUND;
8778 }
8779
8780 return S_OK;
8781}
8782
8783/**
8784 * Returns a storage controller object with the given name.
8785 *
8786 * @param aName storage controller name to find
8787 * @param aStorageController where to return the found storage controller
8788 * @param aSetError true to set extended error info on failure
8789 */
8790HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
8791 ComObjPtr<StorageController> &aStorageController,
8792 bool aSetError /* = false */)
8793{
8794 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
8795
8796 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8797 it != mStorageControllers->end();
8798 ++it)
8799 {
8800 if ((*it)->getName() == aName)
8801 {
8802 aStorageController = (*it);
8803 return S_OK;
8804 }
8805 }
8806
8807 if (aSetError)
8808 return setError(VBOX_E_OBJECT_NOT_FOUND,
8809 tr("Could not find a storage controller named '%s'"),
8810 aName.c_str());
8811 return VBOX_E_OBJECT_NOT_FOUND;
8812}
8813
8814HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
8815 MediaData::AttachmentList &atts)
8816{
8817 AutoCaller autoCaller(this);
8818 if (FAILED(autoCaller.rc())) return autoCaller.rc();
8819
8820 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8821
8822 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
8823 it != mMediaData->mAttachments.end();
8824 ++it)
8825 {
8826 const ComObjPtr<MediumAttachment> &pAtt = *it;
8827
8828 // should never happen, but deal with NULL pointers in the list.
8829 AssertStmt(!pAtt.isNull(), continue);
8830
8831 // getControllerName() needs caller+read lock
8832 AutoCaller autoAttCaller(pAtt);
8833 if (FAILED(autoAttCaller.rc()))
8834 {
8835 atts.clear();
8836 return autoAttCaller.rc();
8837 }
8838 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
8839
8840 if (pAtt->getControllerName() == aName)
8841 atts.push_back(pAtt);
8842 }
8843
8844 return S_OK;
8845}
8846
8847/**
8848 * Helper for #saveSettings. Cares about renaming the settings directory and
8849 * file if the machine name was changed and about creating a new settings file
8850 * if this is a new machine.
8851 *
8852 * @note Must be never called directly but only from #saveSettings().
8853 */
8854HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
8855{
8856 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8857
8858 HRESULT rc = S_OK;
8859
8860 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
8861
8862 /* attempt to rename the settings file if machine name is changed */
8863 if ( mUserData->s.fNameSync
8864 && mUserData.isBackedUp()
8865 && mUserData.backedUpData()->s.strName != mUserData->s.strName
8866 )
8867 {
8868 bool dirRenamed = false;
8869 bool fileRenamed = false;
8870
8871 Utf8Str configFile, newConfigFile;
8872 Utf8Str configFilePrev, newConfigFilePrev;
8873 Utf8Str configDir, newConfigDir;
8874
8875 do
8876 {
8877 int vrc = VINF_SUCCESS;
8878
8879 Utf8Str name = mUserData.backedUpData()->s.strName;
8880 Utf8Str newName = mUserData->s.strName;
8881
8882 configFile = mData->m_strConfigFileFull;
8883
8884 /* first, rename the directory if it matches the machine name */
8885 configDir = configFile;
8886 configDir.stripFilename();
8887 newConfigDir = configDir;
8888 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8889 {
8890 newConfigDir.stripFilename();
8891 newConfigDir.append(RTPATH_DELIMITER);
8892 newConfigDir.append(newName);
8893 /* new dir and old dir cannot be equal here because of 'if'
8894 * above and because name != newName */
8895 Assert(configDir != newConfigDir);
8896 if (!fSettingsFileIsNew)
8897 {
8898 /* perform real rename only if the machine is not new */
8899 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8900 if (RT_FAILURE(vrc))
8901 {
8902 rc = setError(E_FAIL,
8903 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8904 configDir.c_str(),
8905 newConfigDir.c_str(),
8906 vrc);
8907 break;
8908 }
8909 dirRenamed = true;
8910 }
8911 }
8912
8913 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8914 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8915
8916 /* then try to rename the settings file itself */
8917 if (newConfigFile != configFile)
8918 {
8919 /* get the path to old settings file in renamed directory */
8920 configFile = Utf8StrFmt("%s%c%s",
8921 newConfigDir.c_str(),
8922 RTPATH_DELIMITER,
8923 RTPathFilename(configFile.c_str()));
8924 if (!fSettingsFileIsNew)
8925 {
8926 /* perform real rename only if the machine is not new */
8927 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8928 if (RT_FAILURE(vrc))
8929 {
8930 rc = setError(E_FAIL,
8931 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8932 configFile.c_str(),
8933 newConfigFile.c_str(),
8934 vrc);
8935 break;
8936 }
8937 fileRenamed = true;
8938 configFilePrev = configFile;
8939 configFilePrev += "-prev";
8940 newConfigFilePrev = newConfigFile;
8941 newConfigFilePrev += "-prev";
8942 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
8943 }
8944 }
8945
8946 // update m_strConfigFileFull amd mConfigFile
8947 mData->m_strConfigFileFull = newConfigFile;
8948 // compute the relative path too
8949 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8950
8951 // store the old and new so that VirtualBox::saveSettings() can update
8952 // the media registry
8953 if ( mData->mRegistered
8954 && configDir != newConfigDir)
8955 {
8956 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8957
8958 if (pfNeedsGlobalSaveSettings)
8959 *pfNeedsGlobalSaveSettings = true;
8960 }
8961
8962 // in the saved state file path, replace the old directory with the new directory
8963 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8964 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8965
8966 // and do the same thing for the saved state file paths of all the online snapshots
8967 if (mData->mFirstSnapshot)
8968 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8969 newConfigDir.c_str());
8970 }
8971 while (0);
8972
8973 if (FAILED(rc))
8974 {
8975 /* silently try to rename everything back */
8976 if (fileRenamed)
8977 {
8978 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
8979 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8980 }
8981 if (dirRenamed)
8982 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8983 }
8984
8985 if (FAILED(rc)) return rc;
8986 }
8987
8988 if (fSettingsFileIsNew)
8989 {
8990 /* create a virgin config file */
8991 int vrc = VINF_SUCCESS;
8992
8993 /* ensure the settings directory exists */
8994 Utf8Str path(mData->m_strConfigFileFull);
8995 path.stripFilename();
8996 if (!RTDirExists(path.c_str()))
8997 {
8998 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8999 if (RT_FAILURE(vrc))
9000 {
9001 return setError(E_FAIL,
9002 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
9003 path.c_str(),
9004 vrc);
9005 }
9006 }
9007
9008 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
9009 path = Utf8Str(mData->m_strConfigFileFull);
9010 RTFILE f = NIL_RTFILE;
9011 vrc = RTFileOpen(&f, path.c_str(),
9012 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
9013 if (RT_FAILURE(vrc))
9014 return setError(E_FAIL,
9015 tr("Could not create the settings file '%s' (%Rrc)"),
9016 path.c_str(),
9017 vrc);
9018 RTFileClose(f);
9019 }
9020
9021 return rc;
9022}
9023
9024/**
9025 * Saves and commits machine data, user data and hardware data.
9026 *
9027 * Note that on failure, the data remains uncommitted.
9028 *
9029 * @a aFlags may combine the following flags:
9030 *
9031 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
9032 * Used when saving settings after an operation that makes them 100%
9033 * correspond to the settings from the current snapshot.
9034 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
9035 * #isReallyModified() returns false. This is necessary for cases when we
9036 * change machine data directly, not through the backup()/commit() mechanism.
9037 * - SaveS_Force: settings will be saved without doing a deep compare of the
9038 * settings structures. This is used when this is called because snapshots
9039 * have changed to avoid the overhead of the deep compare.
9040 *
9041 * @note Must be called from under this object's write lock. Locks children for
9042 * writing.
9043 *
9044 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
9045 * initialized to false and that will be set to true by this function if
9046 * the caller must invoke VirtualBox::saveSettings() because the global
9047 * settings have changed. This will happen if a machine rename has been
9048 * saved and the global machine and media registries will therefore need
9049 * updating.
9050 */
9051HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
9052 int aFlags /*= 0*/)
9053{
9054 LogFlowThisFuncEnter();
9055
9056 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9057
9058 /* make sure child objects are unable to modify the settings while we are
9059 * saving them */
9060 ensureNoStateDependencies();
9061
9062 AssertReturn(!isSnapshotMachine(),
9063 E_FAIL);
9064
9065 HRESULT rc = S_OK;
9066 bool fNeedsWrite = false;
9067
9068 /* First, prepare to save settings. It will care about renaming the
9069 * settings directory and file if the machine name was changed and about
9070 * creating a new settings file if this is a new machine. */
9071 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
9072 if (FAILED(rc)) return rc;
9073
9074 // keep a pointer to the current settings structures
9075 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
9076 settings::MachineConfigFile *pNewConfig = NULL;
9077
9078 try
9079 {
9080 // make a fresh one to have everyone write stuff into
9081 pNewConfig = new settings::MachineConfigFile(NULL);
9082 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
9083
9084 // now go and copy all the settings data from COM to the settings structures
9085 // (this calles saveSettings() on all the COM objects in the machine)
9086 copyMachineDataToSettings(*pNewConfig);
9087
9088 if (aFlags & SaveS_ResetCurStateModified)
9089 {
9090 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
9091 mData->mCurrentStateModified = FALSE;
9092 fNeedsWrite = true; // always, no need to compare
9093 }
9094 else if (aFlags & SaveS_Force)
9095 {
9096 fNeedsWrite = true; // always, no need to compare
9097 }
9098 else
9099 {
9100 if (!mData->mCurrentStateModified)
9101 {
9102 // do a deep compare of the settings that we just saved with the settings
9103 // previously stored in the config file; this invokes MachineConfigFile::operator==
9104 // which does a deep compare of all the settings, which is expensive but less expensive
9105 // than writing out XML in vain
9106 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
9107
9108 // could still be modified if any settings changed
9109 mData->mCurrentStateModified = fAnySettingsChanged;
9110
9111 fNeedsWrite = fAnySettingsChanged;
9112 }
9113 else
9114 fNeedsWrite = true;
9115 }
9116
9117 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
9118
9119 if (fNeedsWrite)
9120 // now spit it all out!
9121 pNewConfig->write(mData->m_strConfigFileFull);
9122
9123 mData->pMachineConfigFile = pNewConfig;
9124 delete pOldConfig;
9125 commit();
9126
9127 // after saving settings, we are no longer different from the XML on disk
9128 mData->flModifications = 0;
9129 }
9130 catch (HRESULT err)
9131 {
9132 // we assume that error info is set by the thrower
9133 rc = err;
9134
9135 // restore old config
9136 delete pNewConfig;
9137 mData->pMachineConfigFile = pOldConfig;
9138 }
9139 catch (...)
9140 {
9141 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
9142 }
9143
9144 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
9145 {
9146 /* Fire the data change event, even on failure (since we've already
9147 * committed all data). This is done only for SessionMachines because
9148 * mutable Machine instances are always not registered (i.e. private
9149 * to the client process that creates them) and thus don't need to
9150 * inform callbacks. */
9151 if (isSessionMachine())
9152 mParent->onMachineDataChange(mData->mUuid);
9153 }
9154
9155 LogFlowThisFunc(("rc=%08X\n", rc));
9156 LogFlowThisFuncLeave();
9157 return rc;
9158}
9159
9160/**
9161 * Implementation for saving the machine settings into the given
9162 * settings::MachineConfigFile instance. This copies machine extradata
9163 * from the previous machine config file in the instance data, if any.
9164 *
9165 * This gets called from two locations:
9166 *
9167 * -- Machine::saveSettings(), during the regular XML writing;
9168 *
9169 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
9170 * exported to OVF and we write the VirtualBox proprietary XML
9171 * into a <vbox:Machine> tag.
9172 *
9173 * This routine fills all the fields in there, including snapshots, *except*
9174 * for the following:
9175 *
9176 * -- fCurrentStateModified. There is some special logic associated with that.
9177 *
9178 * The caller can then call MachineConfigFile::write() or do something else
9179 * with it.
9180 *
9181 * Caller must hold the machine lock!
9182 *
9183 * This throws XML errors and HRESULT, so the caller must have a catch block!
9184 */
9185void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
9186{
9187 // deep copy extradata
9188 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
9189
9190 config.uuid = mData->mUuid;
9191
9192 // copy name, description, OS type, teleport, UTC etc.
9193 config.machineUserData = mUserData->s;
9194
9195 if ( mData->mMachineState == MachineState_Saved
9196 || mData->mMachineState == MachineState_Restoring
9197 // when deleting a snapshot we may or may not have a saved state in the current state,
9198 // so let's not assert here please
9199 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
9200 || mData->mMachineState == MachineState_DeletingSnapshotOnline
9201 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
9202 && (!mSSData->strStateFilePath.isEmpty())
9203 )
9204 )
9205 {
9206 Assert(!mSSData->strStateFilePath.isEmpty());
9207 /* try to make the file name relative to the settings file dir */
9208 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
9209 }
9210 else
9211 {
9212 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
9213 config.strStateFile.setNull();
9214 }
9215
9216 if (mData->mCurrentSnapshot)
9217 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
9218 else
9219 config.uuidCurrentSnapshot.clear();
9220
9221 config.timeLastStateChange = mData->mLastStateChange;
9222 config.fAborted = (mData->mMachineState == MachineState_Aborted);
9223 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
9224
9225 HRESULT rc = saveHardware(config.hardwareMachine);
9226 if (FAILED(rc)) throw rc;
9227
9228 rc = saveStorageControllers(config.storageMachine);
9229 if (FAILED(rc)) throw rc;
9230
9231 // save machine's media registry if this is VirtualBox 4.0 or later
9232 if (config.canHaveOwnMediaRegistry())
9233 {
9234 // determine machine folder
9235 Utf8Str strMachineFolder = getSettingsFileFull();
9236 strMachineFolder.stripFilename();
9237 mParent->saveMediaRegistry(config.mediaRegistry,
9238 getId(), // only media with registry ID == machine UUID
9239 strMachineFolder);
9240 // this throws HRESULT
9241 }
9242
9243 // save snapshots
9244 rc = saveAllSnapshots(config);
9245 if (FAILED(rc)) throw rc;
9246}
9247
9248/**
9249 * Saves all snapshots of the machine into the given machine config file. Called
9250 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
9251 * @param config
9252 * @return
9253 */
9254HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
9255{
9256 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9257
9258 HRESULT rc = S_OK;
9259
9260 try
9261 {
9262 config.llFirstSnapshot.clear();
9263
9264 if (mData->mFirstSnapshot)
9265 {
9266 settings::Snapshot snapNew;
9267 config.llFirstSnapshot.push_back(snapNew);
9268
9269 // get reference to the fresh copy of the snapshot on the list and
9270 // work on that copy directly to avoid excessive copying later
9271 settings::Snapshot &snap = config.llFirstSnapshot.front();
9272
9273 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
9274 if (FAILED(rc)) throw rc;
9275 }
9276
9277// if (mType == IsSessionMachine)
9278// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
9279
9280 }
9281 catch (HRESULT err)
9282 {
9283 /* we assume that error info is set by the thrower */
9284 rc = err;
9285 }
9286 catch (...)
9287 {
9288 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
9289 }
9290
9291 return rc;
9292}
9293
9294/**
9295 * Saves the VM hardware configuration. It is assumed that the
9296 * given node is empty.
9297 *
9298 * @param aNode <Hardware> node to save the VM hardware configuration to.
9299 */
9300HRESULT Machine::saveHardware(settings::Hardware &data)
9301{
9302 HRESULT rc = S_OK;
9303
9304 try
9305 {
9306 /* The hardware version attribute (optional).
9307 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
9308 if ( mHWData->mHWVersion == "1"
9309 && mSSData->strStateFilePath.isEmpty()
9310 )
9311 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. */
9312
9313 data.strVersion = mHWData->mHWVersion;
9314 data.uuid = mHWData->mHardwareUUID;
9315
9316 // CPU
9317 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
9318 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
9319 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
9320 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
9321 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
9322 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
9323 data.fPAE = !!mHWData->mPAEEnabled;
9324 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
9325
9326 /* Standard and Extended CPUID leafs. */
9327 data.llCpuIdLeafs.clear();
9328 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
9329 {
9330 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
9331 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
9332 }
9333 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
9334 {
9335 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
9336 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
9337 }
9338
9339 data.cCPUs = mHWData->mCPUCount;
9340 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
9341 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
9342
9343 data.llCpus.clear();
9344 if (data.fCpuHotPlug)
9345 {
9346 for (unsigned idx = 0; idx < data.cCPUs; idx++)
9347 {
9348 if (mHWData->mCPUAttached[idx])
9349 {
9350 settings::Cpu cpu;
9351 cpu.ulId = idx;
9352 data.llCpus.push_back(cpu);
9353 }
9354 }
9355 }
9356
9357 // memory
9358 data.ulMemorySizeMB = mHWData->mMemorySize;
9359 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
9360
9361 // firmware
9362 data.firmwareType = mHWData->mFirmwareType;
9363
9364 // HID
9365 data.pointingHidType = mHWData->mPointingHidType;
9366 data.keyboardHidType = mHWData->mKeyboardHidType;
9367
9368 // chipset
9369 data.chipsetType = mHWData->mChipsetType;
9370
9371 // HPET
9372 data.fHpetEnabled = !!mHWData->mHpetEnabled;
9373
9374 // boot order
9375 data.mapBootOrder.clear();
9376 for (size_t i = 0;
9377 i < RT_ELEMENTS(mHWData->mBootOrder);
9378 ++i)
9379 data.mapBootOrder[i] = mHWData->mBootOrder[i];
9380
9381 // display
9382 data.ulVRAMSizeMB = mHWData->mVRAMSize;
9383 data.cMonitors = mHWData->mMonitorCount;
9384 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
9385 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
9386
9387 /* VRDEServer settings (optional) */
9388 rc = mVRDEServer->saveSettings(data.vrdeSettings);
9389 if (FAILED(rc)) throw rc;
9390
9391 /* BIOS (required) */
9392 rc = mBIOSSettings->saveSettings(data.biosSettings);
9393 if (FAILED(rc)) throw rc;
9394
9395 /* USB Controller (required) */
9396 rc = mUSBController->saveSettings(data.usbController);
9397 if (FAILED(rc)) throw rc;
9398
9399 /* Network adapters (required) */
9400 data.llNetworkAdapters.clear();
9401 for (ULONG slot = 0;
9402 slot < RT_ELEMENTS(mNetworkAdapters);
9403 ++slot)
9404 {
9405 settings::NetworkAdapter nic;
9406 nic.ulSlot = slot;
9407 rc = mNetworkAdapters[slot]->saveSettings(nic);
9408 if (FAILED(rc)) throw rc;
9409
9410 data.llNetworkAdapters.push_back(nic);
9411 }
9412
9413 /* Serial ports */
9414 data.llSerialPorts.clear();
9415 for (ULONG slot = 0;
9416 slot < RT_ELEMENTS(mSerialPorts);
9417 ++slot)
9418 {
9419 settings::SerialPort s;
9420 s.ulSlot = slot;
9421 rc = mSerialPorts[slot]->saveSettings(s);
9422 if (FAILED(rc)) return rc;
9423
9424 data.llSerialPorts.push_back(s);
9425 }
9426
9427 /* Parallel ports */
9428 data.llParallelPorts.clear();
9429 for (ULONG slot = 0;
9430 slot < RT_ELEMENTS(mParallelPorts);
9431 ++slot)
9432 {
9433 settings::ParallelPort p;
9434 p.ulSlot = slot;
9435 rc = mParallelPorts[slot]->saveSettings(p);
9436 if (FAILED(rc)) return rc;
9437
9438 data.llParallelPorts.push_back(p);
9439 }
9440
9441 /* Audio adapter */
9442 rc = mAudioAdapter->saveSettings(data.audioAdapter);
9443 if (FAILED(rc)) return rc;
9444
9445 /* Shared folders */
9446 data.llSharedFolders.clear();
9447 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
9448 it != mHWData->mSharedFolders.end();
9449 ++it)
9450 {
9451 SharedFolder *pSF = *it;
9452 AutoCaller sfCaller(pSF);
9453 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
9454 settings::SharedFolder sf;
9455 sf.strName = pSF->getName();
9456 sf.strHostPath = pSF->getHostPath();
9457 sf.fWritable = !!pSF->isWritable();
9458 sf.fAutoMount = !!pSF->isAutoMounted();
9459
9460 data.llSharedFolders.push_back(sf);
9461 }
9462
9463 // clipboard
9464 data.clipboardMode = mHWData->mClipboardMode;
9465
9466 /* Guest */
9467 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
9468
9469 // IO settings
9470 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
9471 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
9472
9473 /* BandwidthControl (required) */
9474 rc = mBandwidthControl->saveSettings(data.ioSettings);
9475 if (FAILED(rc)) throw rc;
9476
9477 /* Host PCI devices */
9478 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
9479 it != mHWData->mPciDeviceAssignments.end();
9480 ++it)
9481 {
9482 ComObjPtr<PciDeviceAttachment> pda = *it;
9483 settings::HostPciDeviceAttachment hpda;
9484
9485 rc = pda->saveSettings(hpda);
9486 if (FAILED(rc)) throw rc;
9487
9488 data.pciAttachments.push_back(hpda);
9489 }
9490
9491
9492 // guest properties
9493 data.llGuestProperties.clear();
9494#ifdef VBOX_WITH_GUEST_PROPS
9495 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
9496 it != mHWData->mGuestProperties.end();
9497 ++it)
9498 {
9499 HWData::GuestProperty property = *it;
9500
9501 /* Remove transient guest properties at shutdown unless we
9502 * are saving state */
9503 if ( ( mData->mMachineState == MachineState_PoweredOff
9504 || mData->mMachineState == MachineState_Aborted
9505 || mData->mMachineState == MachineState_Teleported)
9506 && ( property.mFlags & guestProp::TRANSIENT
9507 || property.mFlags & guestProp::TRANSRESET))
9508 continue;
9509 settings::GuestProperty prop;
9510 prop.strName = property.strName;
9511 prop.strValue = property.strValue;
9512 prop.timestamp = property.mTimestamp;
9513 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
9514 guestProp::writeFlags(property.mFlags, szFlags);
9515 prop.strFlags = szFlags;
9516
9517 data.llGuestProperties.push_back(prop);
9518 }
9519
9520 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
9521 /* I presume this doesn't require a backup(). */
9522 mData->mGuestPropertiesModified = FALSE;
9523#endif /* VBOX_WITH_GUEST_PROPS defined */
9524 }
9525 catch(std::bad_alloc &)
9526 {
9527 return E_OUTOFMEMORY;
9528 }
9529
9530 AssertComRC(rc);
9531 return rc;
9532}
9533
9534/**
9535 * Saves the storage controller configuration.
9536 *
9537 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
9538 */
9539HRESULT Machine::saveStorageControllers(settings::Storage &data)
9540{
9541 data.llStorageControllers.clear();
9542
9543 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
9544 it != mStorageControllers->end();
9545 ++it)
9546 {
9547 HRESULT rc;
9548 ComObjPtr<StorageController> pCtl = *it;
9549
9550 settings::StorageController ctl;
9551 ctl.strName = pCtl->getName();
9552 ctl.controllerType = pCtl->getControllerType();
9553 ctl.storageBus = pCtl->getStorageBus();
9554 ctl.ulInstance = pCtl->getInstance();
9555 ctl.fBootable = pCtl->getBootable();
9556
9557 /* Save the port count. */
9558 ULONG portCount;
9559 rc = pCtl->COMGETTER(PortCount)(&portCount);
9560 ComAssertComRCRet(rc, rc);
9561 ctl.ulPortCount = portCount;
9562
9563 /* Save fUseHostIOCache */
9564 BOOL fUseHostIOCache;
9565 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9566 ComAssertComRCRet(rc, rc);
9567 ctl.fUseHostIOCache = !!fUseHostIOCache;
9568
9569 /* Save IDE emulation settings. */
9570 if (ctl.controllerType == StorageControllerType_IntelAhci)
9571 {
9572 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
9573 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
9574 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
9575 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
9576 )
9577 ComAssertComRCRet(rc, rc);
9578 }
9579
9580 /* save the devices now. */
9581 rc = saveStorageDevices(pCtl, ctl);
9582 ComAssertComRCRet(rc, rc);
9583
9584 data.llStorageControllers.push_back(ctl);
9585 }
9586
9587 return S_OK;
9588}
9589
9590/**
9591 * Saves the hard disk configuration.
9592 */
9593HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
9594 settings::StorageController &data)
9595{
9596 MediaData::AttachmentList atts;
9597
9598 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
9599 if (FAILED(rc)) return rc;
9600
9601 data.llAttachedDevices.clear();
9602 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9603 it != atts.end();
9604 ++it)
9605 {
9606 settings::AttachedDevice dev;
9607
9608 MediumAttachment *pAttach = *it;
9609 Medium *pMedium = pAttach->getMedium();
9610
9611 dev.deviceType = pAttach->getType();
9612 dev.lPort = pAttach->getPort();
9613 dev.lDevice = pAttach->getDevice();
9614 if (pMedium)
9615 {
9616 if (pMedium->isHostDrive())
9617 dev.strHostDriveSrc = pMedium->getLocationFull();
9618 else
9619 dev.uuid = pMedium->getId();
9620 dev.fPassThrough = pAttach->getPassthrough();
9621 }
9622
9623 dev.strBwGroup = pAttach->getBandwidthGroup();
9624
9625 data.llAttachedDevices.push_back(dev);
9626 }
9627
9628 return S_OK;
9629}
9630
9631/**
9632 * Saves machine state settings as defined by aFlags
9633 * (SaveSTS_* values).
9634 *
9635 * @param aFlags Combination of SaveSTS_* flags.
9636 *
9637 * @note Locks objects for writing.
9638 */
9639HRESULT Machine::saveStateSettings(int aFlags)
9640{
9641 if (aFlags == 0)
9642 return S_OK;
9643
9644 AutoCaller autoCaller(this);
9645 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9646
9647 /* This object's write lock is also necessary to serialize file access
9648 * (prevent concurrent reads and writes) */
9649 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9650
9651 HRESULT rc = S_OK;
9652
9653 Assert(mData->pMachineConfigFile);
9654
9655 try
9656 {
9657 if (aFlags & SaveSTS_CurStateModified)
9658 mData->pMachineConfigFile->fCurrentStateModified = true;
9659
9660 if (aFlags & SaveSTS_StateFilePath)
9661 {
9662 if (!mSSData->strStateFilePath.isEmpty())
9663 /* try to make the file name relative to the settings file dir */
9664 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
9665 else
9666 mData->pMachineConfigFile->strStateFile.setNull();
9667 }
9668
9669 if (aFlags & SaveSTS_StateTimeStamp)
9670 {
9671 Assert( mData->mMachineState != MachineState_Aborted
9672 || mSSData->strStateFilePath.isEmpty());
9673
9674 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
9675
9676 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
9677//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
9678 }
9679
9680 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
9681 }
9682 catch (...)
9683 {
9684 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
9685 }
9686
9687 return rc;
9688}
9689
9690/**
9691 * Ensures that the given medium is added to a media registry. If this machine
9692 * was created with 4.0 or later, then the machine registry is used. Otherwise
9693 * the global VirtualBox media registry is used. If the medium was actually
9694 * added to a registry (because it wasn't in the registry yet), the UUID of
9695 * that registry is added to the given list so that the caller can save the
9696 * registry.
9697 *
9698 * Caller must hold machine read lock!
9699 *
9700 * @param pMedium
9701 * @param llRegistriesThatNeedSaving
9702 * @param puuid Optional buffer that receives the registry UUID that was used.
9703 */
9704void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
9705 GuidList &llRegistriesThatNeedSaving,
9706 Guid *puuid)
9707{
9708 // decide which medium registry to use now that the medium is attached:
9709 Guid uuid;
9710 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
9711 // machine XML is VirtualBox 4.0 or higher:
9712 uuid = getId(); // machine UUID
9713 else
9714 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
9715
9716 AutoCaller autoCaller(pMedium);
9717 if (FAILED(autoCaller.rc())) return;
9718 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9719
9720 if (pMedium->addRegistry(uuid, false /* fRecurse */))
9721 // registry actually changed:
9722 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
9723
9724 if (puuid)
9725 *puuid = uuid;
9726}
9727
9728/**
9729 * Creates differencing hard disks for all normal hard disks attached to this
9730 * machine and a new set of attachments to refer to created disks.
9731 *
9732 * Used when taking a snapshot or when deleting the current state. Gets called
9733 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
9734 *
9735 * This method assumes that mMediaData contains the original hard disk attachments
9736 * it needs to create diffs for. On success, these attachments will be replaced
9737 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
9738 * called to delete created diffs which will also rollback mMediaData and restore
9739 * whatever was backed up before calling this method.
9740 *
9741 * Attachments with non-normal hard disks are left as is.
9742 *
9743 * If @a aOnline is @c false then the original hard disks that require implicit
9744 * diffs will be locked for reading. Otherwise it is assumed that they are
9745 * already locked for writing (when the VM was started). Note that in the latter
9746 * case it is responsibility of the caller to lock the newly created diffs for
9747 * writing if this method succeeds.
9748 *
9749 * @param aProgress Progress object to run (must contain at least as
9750 * many operations left as the number of hard disks
9751 * attached).
9752 * @param aOnline Whether the VM was online prior to this operation.
9753 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9754 *
9755 * @note The progress object is not marked as completed, neither on success nor
9756 * on failure. This is a responsibility of the caller.
9757 *
9758 * @note Locks this object for writing.
9759 */
9760HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
9761 ULONG aWeight,
9762 bool aOnline,
9763 GuidList *pllRegistriesThatNeedSaving)
9764{
9765 LogFlowThisFunc(("aOnline=%d\n", aOnline));
9766
9767 AutoCaller autoCaller(this);
9768 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9769
9770 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9771
9772 /* must be in a protective state because we leave the lock below */
9773 AssertReturn( mData->mMachineState == MachineState_Saving
9774 || mData->mMachineState == MachineState_LiveSnapshotting
9775 || mData->mMachineState == MachineState_RestoringSnapshot
9776 || mData->mMachineState == MachineState_DeletingSnapshot
9777 , E_FAIL);
9778
9779 HRESULT rc = S_OK;
9780
9781 MediumLockListMap lockedMediaOffline;
9782 MediumLockListMap *lockedMediaMap;
9783 if (aOnline)
9784 lockedMediaMap = &mData->mSession.mLockedMedia;
9785 else
9786 lockedMediaMap = &lockedMediaOffline;
9787
9788 try
9789 {
9790 if (!aOnline)
9791 {
9792 /* lock all attached hard disks early to detect "in use"
9793 * situations before creating actual diffs */
9794 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9795 it != mMediaData->mAttachments.end();
9796 ++it)
9797 {
9798 MediumAttachment* pAtt = *it;
9799 if (pAtt->getType() == DeviceType_HardDisk)
9800 {
9801 Medium* pMedium = pAtt->getMedium();
9802 Assert(pMedium);
9803
9804 MediumLockList *pMediumLockList(new MediumLockList());
9805 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
9806 false /* fMediumLockWrite */,
9807 NULL,
9808 *pMediumLockList);
9809 if (FAILED(rc))
9810 {
9811 delete pMediumLockList;
9812 throw rc;
9813 }
9814 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
9815 if (FAILED(rc))
9816 {
9817 throw setError(rc,
9818 tr("Collecting locking information for all attached media failed"));
9819 }
9820 }
9821 }
9822
9823 /* Now lock all media. If this fails, nothing is locked. */
9824 rc = lockedMediaMap->Lock();
9825 if (FAILED(rc))
9826 {
9827 throw setError(rc,
9828 tr("Locking of attached media failed"));
9829 }
9830 }
9831
9832 /* remember the current list (note that we don't use backup() since
9833 * mMediaData may be already backed up) */
9834 MediaData::AttachmentList atts = mMediaData->mAttachments;
9835
9836 /* start from scratch */
9837 mMediaData->mAttachments.clear();
9838
9839 /* go through remembered attachments and create diffs for normal hard
9840 * disks and attach them */
9841 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9842 it != atts.end();
9843 ++it)
9844 {
9845 MediumAttachment* pAtt = *it;
9846
9847 DeviceType_T devType = pAtt->getType();
9848 Medium* pMedium = pAtt->getMedium();
9849
9850 if ( devType != DeviceType_HardDisk
9851 || pMedium == NULL
9852 || pMedium->getType() != MediumType_Normal)
9853 {
9854 /* copy the attachment as is */
9855
9856 /** @todo the progress object created in Console::TakeSnaphot
9857 * only expects operations for hard disks. Later other
9858 * device types need to show up in the progress as well. */
9859 if (devType == DeviceType_HardDisk)
9860 {
9861 if (pMedium == NULL)
9862 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9863 aWeight); // weight
9864 else
9865 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9866 pMedium->getBase()->getName().c_str()).raw(),
9867 aWeight); // weight
9868 }
9869
9870 mMediaData->mAttachments.push_back(pAtt);
9871 continue;
9872 }
9873
9874 /* need a diff */
9875 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9876 pMedium->getBase()->getName().c_str()).raw(),
9877 aWeight); // weight
9878
9879 Utf8Str strFullSnapshotFolder;
9880 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9881
9882 ComObjPtr<Medium> diff;
9883 diff.createObject();
9884 // store the diff in the same registry as the parent
9885 // (this cannot fail here because we can't create implicit diffs for
9886 // unregistered images)
9887 Guid uuidRegistryParent;
9888 bool fInRegistry = pMedium->getFirstRegistryMachineId(uuidRegistryParent);
9889 Assert(fInRegistry); NOREF(fInRegistry);
9890 rc = diff->init(mParent,
9891 pMedium->getPreferredDiffFormat(),
9892 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9893 uuidRegistryParent,
9894 pllRegistriesThatNeedSaving);
9895 if (FAILED(rc)) throw rc;
9896
9897 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9898 * the push_back? Looks like we're going to leave medium with the
9899 * wrong kind of lock (general issue with if we fail anywhere at all)
9900 * and an orphaned VDI in the snapshots folder. */
9901
9902 /* update the appropriate lock list */
9903 MediumLockList *pMediumLockList;
9904 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9905 AssertComRCThrowRC(rc);
9906 if (aOnline)
9907 {
9908 rc = pMediumLockList->Update(pMedium, false);
9909 AssertComRCThrowRC(rc);
9910 }
9911
9912 /* leave the lock before the potentially lengthy operation */
9913 alock.leave();
9914 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9915 pMediumLockList,
9916 NULL /* aProgress */,
9917 true /* aWait */,
9918 pllRegistriesThatNeedSaving);
9919 alock.enter();
9920 if (FAILED(rc)) throw rc;
9921
9922 rc = lockedMediaMap->Unlock();
9923 AssertComRCThrowRC(rc);
9924 rc = pMediumLockList->Append(diff, true);
9925 AssertComRCThrowRC(rc);
9926 rc = lockedMediaMap->Lock();
9927 AssertComRCThrowRC(rc);
9928
9929 rc = diff->addBackReference(mData->mUuid);
9930 AssertComRCThrowRC(rc);
9931
9932 /* add a new attachment */
9933 ComObjPtr<MediumAttachment> attachment;
9934 attachment.createObject();
9935 rc = attachment->init(this,
9936 diff,
9937 pAtt->getControllerName(),
9938 pAtt->getPort(),
9939 pAtt->getDevice(),
9940 DeviceType_HardDisk,
9941 true /* aImplicit */,
9942 pAtt->getBandwidthGroup());
9943 if (FAILED(rc)) throw rc;
9944
9945 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9946 AssertComRCThrowRC(rc);
9947 mMediaData->mAttachments.push_back(attachment);
9948 }
9949 }
9950 catch (HRESULT aRC) { rc = aRC; }
9951
9952 /* unlock all hard disks we locked */
9953 if (!aOnline)
9954 {
9955 ErrorInfoKeeper eik;
9956
9957 HRESULT rc1 = lockedMediaMap->Clear();
9958 AssertComRC(rc1);
9959 }
9960
9961 if (FAILED(rc))
9962 {
9963 MultiResult mrc = rc;
9964
9965 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9966 }
9967
9968 return rc;
9969}
9970
9971/**
9972 * Deletes implicit differencing hard disks created either by
9973 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
9974 *
9975 * Note that to delete hard disks created by #AttachMedium() this method is
9976 * called from #fixupMedia() when the changes are rolled back.
9977 *
9978 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9979 *
9980 * @note Locks this object for writing.
9981 */
9982HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9983{
9984 AutoCaller autoCaller(this);
9985 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9986
9987 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9988 LogFlowThisFuncEnter();
9989
9990 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9991
9992 HRESULT rc = S_OK;
9993
9994 MediaData::AttachmentList implicitAtts;
9995
9996 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9997
9998 /* enumerate new attachments */
9999 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10000 it != mMediaData->mAttachments.end();
10001 ++it)
10002 {
10003 ComObjPtr<Medium> hd = (*it)->getMedium();
10004 if (hd.isNull())
10005 continue;
10006
10007 if ((*it)->isImplicit())
10008 {
10009 /* deassociate and mark for deletion */
10010 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
10011 rc = hd->removeBackReference(mData->mUuid);
10012 AssertComRC(rc);
10013 implicitAtts.push_back(*it);
10014 continue;
10015 }
10016
10017 /* was this hard disk attached before? */
10018 if (!findAttachment(oldAtts, hd))
10019 {
10020 /* no: de-associate */
10021 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
10022 rc = hd->removeBackReference(mData->mUuid);
10023 AssertComRC(rc);
10024 continue;
10025 }
10026 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
10027 }
10028
10029 /* rollback hard disk changes */
10030 mMediaData.rollback();
10031
10032 MultiResult mrc(S_OK);
10033
10034 /* delete unused implicit diffs */
10035 if (implicitAtts.size() != 0)
10036 {
10037 /* will leave the lock before the potentially lengthy
10038 * operation, so protect with the special state (unless already
10039 * protected) */
10040 MachineState_T oldState = mData->mMachineState;
10041 if ( oldState != MachineState_Saving
10042 && oldState != MachineState_LiveSnapshotting
10043 && oldState != MachineState_RestoringSnapshot
10044 && oldState != MachineState_DeletingSnapshot
10045 && oldState != MachineState_DeletingSnapshotOnline
10046 && oldState != MachineState_DeletingSnapshotPaused
10047 )
10048 setMachineState(MachineState_SettingUp);
10049
10050 alock.leave();
10051
10052 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
10053 it != implicitAtts.end();
10054 ++it)
10055 {
10056 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
10057 ComObjPtr<Medium> hd = (*it)->getMedium();
10058
10059 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
10060 pllRegistriesThatNeedSaving);
10061 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
10062 mrc = rc;
10063 }
10064
10065 alock.enter();
10066
10067 if (mData->mMachineState == MachineState_SettingUp)
10068 setMachineState(oldState);
10069 }
10070
10071 return mrc;
10072}
10073
10074/**
10075 * Looks through the given list of media attachments for one with the given parameters
10076 * and returns it, or NULL if not found. The list is a parameter so that backup lists
10077 * can be searched as well if needed.
10078 *
10079 * @param list
10080 * @param aControllerName
10081 * @param aControllerPort
10082 * @param aDevice
10083 * @return
10084 */
10085MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
10086 IN_BSTR aControllerName,
10087 LONG aControllerPort,
10088 LONG aDevice)
10089{
10090 for (MediaData::AttachmentList::const_iterator it = ll.begin();
10091 it != ll.end();
10092 ++it)
10093 {
10094 MediumAttachment *pAttach = *it;
10095 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
10096 return pAttach;
10097 }
10098
10099 return NULL;
10100}
10101
10102/**
10103 * Looks through the given list of media attachments for one with the given parameters
10104 * and returns it, or NULL if not found. The list is a parameter so that backup lists
10105 * can be searched as well if needed.
10106 *
10107 * @param list
10108 * @param aControllerName
10109 * @param aControllerPort
10110 * @param aDevice
10111 * @return
10112 */
10113MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
10114 ComObjPtr<Medium> pMedium)
10115{
10116 for (MediaData::AttachmentList::const_iterator it = ll.begin();
10117 it != ll.end();
10118 ++it)
10119 {
10120 MediumAttachment *pAttach = *it;
10121 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
10122 if (pMediumThis == pMedium)
10123 return pAttach;
10124 }
10125
10126 return NULL;
10127}
10128
10129/**
10130 * Looks through the given list of media attachments for one with the given parameters
10131 * and returns it, or NULL if not found. The list is a parameter so that backup lists
10132 * can be searched as well if needed.
10133 *
10134 * @param list
10135 * @param aControllerName
10136 * @param aControllerPort
10137 * @param aDevice
10138 * @return
10139 */
10140MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
10141 Guid &id)
10142{
10143 for (MediaData::AttachmentList::const_iterator it = ll.begin();
10144 it != ll.end();
10145 ++it)
10146 {
10147 MediumAttachment *pAttach = *it;
10148 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
10149 if (pMediumThis->getId() == id)
10150 return pAttach;
10151 }
10152
10153 return NULL;
10154}
10155
10156/**
10157 * Main implementation for Machine::DetachDevice. This also gets called
10158 * from Machine::prepareUnregister() so it has been taken out for simplicity.
10159 *
10160 * @param pAttach Medium attachment to detach.
10161 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
10162 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
10163 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
10164 * @return
10165 */
10166HRESULT Machine::detachDevice(MediumAttachment *pAttach,
10167 AutoWriteLock &writeLock,
10168 Snapshot *pSnapshot,
10169 GuidList *pllRegistriesThatNeedSaving)
10170{
10171 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
10172 DeviceType_T mediumType = pAttach->getType();
10173
10174 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
10175
10176 if (pAttach->isImplicit())
10177 {
10178 /* attempt to implicitly delete the implicitly created diff */
10179
10180 /// @todo move the implicit flag from MediumAttachment to Medium
10181 /// and forbid any hard disk operation when it is implicit. Or maybe
10182 /// a special media state for it to make it even more simple.
10183
10184 Assert(mMediaData.isBackedUp());
10185
10186 /* will leave the lock before the potentially lengthy operation, so
10187 * protect with the special state */
10188 MachineState_T oldState = mData->mMachineState;
10189 setMachineState(MachineState_SettingUp);
10190
10191 writeLock.release();
10192
10193 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
10194 true /*aWait*/,
10195 pllRegistriesThatNeedSaving);
10196
10197 writeLock.acquire();
10198
10199 setMachineState(oldState);
10200
10201 if (FAILED(rc)) return rc;
10202 }
10203
10204 setModified(IsModified_Storage);
10205 mMediaData.backup();
10206
10207 // we cannot use erase (it) below because backup() above will create
10208 // a copy of the list and make this copy active, but the iterator
10209 // still refers to the original and is not valid for the copy
10210 mMediaData->mAttachments.remove(pAttach);
10211
10212 if (!oldmedium.isNull())
10213 {
10214 // if this is from a snapshot, do not defer detachment to commitMedia()
10215 if (pSnapshot)
10216 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
10217 // else if non-hard disk media, do not defer detachment to commitMedia() either
10218 else if (mediumType != DeviceType_HardDisk)
10219 oldmedium->removeBackReference(mData->mUuid);
10220 }
10221
10222 return S_OK;
10223}
10224
10225/**
10226 * Goes thru all media of the given list and
10227 *
10228 * 1) calls detachDevice() on each of them for this machine and
10229 * 2) adds all Medium objects found in the process to the given list,
10230 * depending on cleanupMode.
10231 *
10232 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
10233 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
10234 * media to the list.
10235 *
10236 * This gets called from Machine::Unregister, both for the actual Machine and
10237 * the SnapshotMachine objects that might be found in the snapshots.
10238 *
10239 * Requires caller and locking. The machine lock must be passed in because it
10240 * will be passed on to detachDevice which needs it for temporary unlocking.
10241 *
10242 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
10243 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
10244 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
10245 * otherwise no media get added.
10246 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
10247 * @return
10248 */
10249HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
10250 Snapshot *pSnapshot,
10251 CleanupMode_T cleanupMode,
10252 MediaList &llMedia)
10253{
10254 Assert(isWriteLockOnCurrentThread());
10255
10256 HRESULT rc;
10257
10258 // make a temporary list because detachDevice invalidates iterators into
10259 // mMediaData->mAttachments
10260 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
10261
10262 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
10263 it != llAttachments2.end();
10264 ++it)
10265 {
10266 ComObjPtr<MediumAttachment> &pAttach = *it;
10267 ComObjPtr<Medium> pMedium = pAttach->getMedium();
10268
10269 if (!pMedium.isNull())
10270 {
10271 DeviceType_T devType = pMedium->getDeviceType();
10272 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
10273 && devType == DeviceType_HardDisk)
10274 || (cleanupMode == CleanupMode_Full)
10275 )
10276 llMedia.push_back(pMedium);
10277 }
10278
10279 // real machine: then we need to use the proper method
10280 rc = detachDevice(pAttach,
10281 writeLock,
10282 pSnapshot,
10283 NULL /* pfNeedsSaveSettings */);
10284
10285 if (FAILED(rc))
10286 return rc;
10287 }
10288
10289 return S_OK;
10290}
10291
10292/**
10293 * Perform deferred hard disk detachments.
10294 *
10295 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
10296 * backed up).
10297 *
10298 * If @a aOnline is @c true then this method will also unlock the old hard disks
10299 * for which the new implicit diffs were created and will lock these new diffs for
10300 * writing.
10301 *
10302 * @param aOnline Whether the VM was online prior to this operation.
10303 *
10304 * @note Locks this object for writing!
10305 */
10306void Machine::commitMedia(bool aOnline /*= false*/)
10307{
10308 AutoCaller autoCaller(this);
10309 AssertComRCReturnVoid(autoCaller.rc());
10310
10311 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10312
10313 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
10314
10315 HRESULT rc = S_OK;
10316
10317 /* no attach/detach operations -- nothing to do */
10318 if (!mMediaData.isBackedUp())
10319 return;
10320
10321 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
10322 bool fMediaNeedsLocking = false;
10323
10324 /* enumerate new attachments */
10325 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10326 it != mMediaData->mAttachments.end();
10327 ++it)
10328 {
10329 MediumAttachment *pAttach = *it;
10330
10331 pAttach->commit();
10332
10333 Medium* pMedium = pAttach->getMedium();
10334 bool fImplicit = pAttach->isImplicit();
10335
10336 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
10337 (pMedium) ? pMedium->getName().c_str() : "NULL",
10338 fImplicit));
10339
10340 /** @todo convert all this Machine-based voodoo to MediumAttachment
10341 * based commit logic. */
10342 if (fImplicit)
10343 {
10344 /* convert implicit attachment to normal */
10345 pAttach->setImplicit(false);
10346
10347 if ( aOnline
10348 && pMedium
10349 && pAttach->getType() == DeviceType_HardDisk
10350 )
10351 {
10352 ComObjPtr<Medium> parent = pMedium->getParent();
10353 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
10354
10355 /* update the appropriate lock list */
10356 MediumLockList *pMediumLockList;
10357 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
10358 AssertComRC(rc);
10359 if (pMediumLockList)
10360 {
10361 /* unlock if there's a need to change the locking */
10362 if (!fMediaNeedsLocking)
10363 {
10364 rc = mData->mSession.mLockedMedia.Unlock();
10365 AssertComRC(rc);
10366 fMediaNeedsLocking = true;
10367 }
10368 rc = pMediumLockList->Update(parent, false);
10369 AssertComRC(rc);
10370 rc = pMediumLockList->Append(pMedium, true);
10371 AssertComRC(rc);
10372 }
10373 }
10374
10375 continue;
10376 }
10377
10378 if (pMedium)
10379 {
10380 /* was this medium attached before? */
10381 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
10382 oldIt != oldAtts.end();
10383 ++oldIt)
10384 {
10385 MediumAttachment *pOldAttach = *oldIt;
10386 if (pOldAttach->getMedium() == pMedium)
10387 {
10388 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
10389
10390 /* yes: remove from old to avoid de-association */
10391 oldAtts.erase(oldIt);
10392 break;
10393 }
10394 }
10395 }
10396 }
10397
10398 /* enumerate remaining old attachments and de-associate from the
10399 * current machine state */
10400 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
10401 it != oldAtts.end();
10402 ++it)
10403 {
10404 MediumAttachment *pAttach = *it;
10405 Medium* pMedium = pAttach->getMedium();
10406
10407 /* Detach only hard disks, since DVD/floppy media is detached
10408 * instantly in MountMedium. */
10409 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
10410 {
10411 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
10412
10413 /* now de-associate from the current machine state */
10414 rc = pMedium->removeBackReference(mData->mUuid);
10415 AssertComRC(rc);
10416
10417 if (aOnline)
10418 {
10419 /* unlock since medium is not used anymore */
10420 MediumLockList *pMediumLockList;
10421 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
10422 AssertComRC(rc);
10423 if (pMediumLockList)
10424 {
10425 rc = mData->mSession.mLockedMedia.Remove(pAttach);
10426 AssertComRC(rc);
10427 }
10428 }
10429 }
10430 }
10431
10432 /* take media locks again so that the locking state is consistent */
10433 if (fMediaNeedsLocking)
10434 {
10435 Assert(aOnline);
10436 rc = mData->mSession.mLockedMedia.Lock();
10437 AssertComRC(rc);
10438 }
10439
10440 /* commit the hard disk changes */
10441 mMediaData.commit();
10442
10443 if (isSessionMachine())
10444 {
10445 /*
10446 * Update the parent machine to point to the new owner.
10447 * This is necessary because the stored parent will point to the
10448 * session machine otherwise and cause crashes or errors later
10449 * when the session machine gets invalid.
10450 */
10451 /** @todo Change the MediumAttachment class to behave like any other
10452 * class in this regard by creating peer MediumAttachment
10453 * objects for session machines and share the data with the peer
10454 * machine.
10455 */
10456 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10457 it != mMediaData->mAttachments.end();
10458 ++it)
10459 {
10460 (*it)->updateParentMachine(mPeer);
10461 }
10462
10463 /* attach new data to the primary machine and reshare it */
10464 mPeer->mMediaData.attach(mMediaData);
10465 }
10466
10467 return;
10468}
10469
10470/**
10471 * Perform deferred deletion of implicitly created diffs.
10472 *
10473 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
10474 * backed up).
10475 *
10476 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
10477 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
10478 *
10479 * @note Locks this object for writing!
10480 *
10481 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
10482 */
10483void Machine::rollbackMedia()
10484{
10485 AutoCaller autoCaller(this);
10486 AssertComRCReturnVoid (autoCaller.rc());
10487
10488 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10489
10490 LogFlowThisFunc(("Entering\n"));
10491
10492 HRESULT rc = S_OK;
10493
10494 /* no attach/detach operations -- nothing to do */
10495 if (!mMediaData.isBackedUp())
10496 return;
10497
10498 /* enumerate new attachments */
10499 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10500 it != mMediaData->mAttachments.end();
10501 ++it)
10502 {
10503 MediumAttachment *pAttach = *it;
10504 /* Fix up the backrefs for DVD/floppy media. */
10505 if (pAttach->getType() != DeviceType_HardDisk)
10506 {
10507 Medium* pMedium = pAttach->getMedium();
10508 if (pMedium)
10509 {
10510 rc = pMedium->removeBackReference(mData->mUuid);
10511 AssertComRC(rc);
10512 }
10513 }
10514
10515 (*it)->rollback();
10516
10517 pAttach = *it;
10518 /* Fix up the backrefs for DVD/floppy media. */
10519 if (pAttach->getType() != DeviceType_HardDisk)
10520 {
10521 Medium* pMedium = pAttach->getMedium();
10522 if (pMedium)
10523 {
10524 rc = pMedium->addBackReference(mData->mUuid);
10525 AssertComRC(rc);
10526 }
10527 }
10528 }
10529
10530 /** @todo convert all this Machine-based voodoo to MediumAttachment
10531 * based rollback logic. */
10532 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
10533 // which gets called if Machine::registeredInit() fails...
10534 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
10535
10536 return;
10537}
10538
10539/**
10540 * Returns true if the settings file is located in the directory named exactly
10541 * as the machine; this means, among other things, that the machine directory
10542 * should be auto-renamed.
10543 *
10544 * @param aSettingsDir if not NULL, the full machine settings file directory
10545 * name will be assigned there.
10546 *
10547 * @note Doesn't lock anything.
10548 * @note Not thread safe (must be called from this object's lock).
10549 */
10550bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
10551{
10552 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
10553 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
10554 if (aSettingsDir)
10555 *aSettingsDir = strMachineDirName;
10556 strMachineDirName.stripPath(); // vmname
10557 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
10558 strConfigFileOnly.stripPath() // vmname.vbox
10559 .stripExt(); // vmname
10560
10561 AssertReturn(!strMachineDirName.isEmpty(), false);
10562 AssertReturn(!strConfigFileOnly.isEmpty(), false);
10563
10564 return strMachineDirName == strConfigFileOnly;
10565}
10566
10567/**
10568 * Discards all changes to machine settings.
10569 *
10570 * @param aNotify Whether to notify the direct session about changes or not.
10571 *
10572 * @note Locks objects for writing!
10573 */
10574void Machine::rollback(bool aNotify)
10575{
10576 AutoCaller autoCaller(this);
10577 AssertComRCReturn(autoCaller.rc(), (void)0);
10578
10579 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10580
10581 if (!mStorageControllers.isNull())
10582 {
10583 if (mStorageControllers.isBackedUp())
10584 {
10585 /* unitialize all new devices (absent in the backed up list). */
10586 StorageControllerList::const_iterator it = mStorageControllers->begin();
10587 StorageControllerList *backedList = mStorageControllers.backedUpData();
10588 while (it != mStorageControllers->end())
10589 {
10590 if ( std::find(backedList->begin(), backedList->end(), *it)
10591 == backedList->end()
10592 )
10593 {
10594 (*it)->uninit();
10595 }
10596 ++it;
10597 }
10598
10599 /* restore the list */
10600 mStorageControllers.rollback();
10601 }
10602
10603 /* rollback any changes to devices after restoring the list */
10604 if (mData->flModifications & IsModified_Storage)
10605 {
10606 StorageControllerList::const_iterator it = mStorageControllers->begin();
10607 while (it != mStorageControllers->end())
10608 {
10609 (*it)->rollback();
10610 ++it;
10611 }
10612 }
10613 }
10614
10615 mUserData.rollback();
10616
10617 mHWData.rollback();
10618
10619 if (mData->flModifications & IsModified_Storage)
10620 rollbackMedia();
10621
10622 if (mBIOSSettings)
10623 mBIOSSettings->rollback();
10624
10625 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
10626 mVRDEServer->rollback();
10627
10628 if (mAudioAdapter)
10629 mAudioAdapter->rollback();
10630
10631 if (mUSBController && (mData->flModifications & IsModified_USB))
10632 mUSBController->rollback();
10633
10634 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
10635 mBandwidthControl->rollback();
10636
10637 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
10638 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
10639 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
10640
10641 if (mData->flModifications & IsModified_NetworkAdapters)
10642 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10643 if ( mNetworkAdapters[slot]
10644 && mNetworkAdapters[slot]->isModified())
10645 {
10646 mNetworkAdapters[slot]->rollback();
10647 networkAdapters[slot] = mNetworkAdapters[slot];
10648 }
10649
10650 if (mData->flModifications & IsModified_SerialPorts)
10651 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10652 if ( mSerialPorts[slot]
10653 && mSerialPorts[slot]->isModified())
10654 {
10655 mSerialPorts[slot]->rollback();
10656 serialPorts[slot] = mSerialPorts[slot];
10657 }
10658
10659 if (mData->flModifications & IsModified_ParallelPorts)
10660 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10661 if ( mParallelPorts[slot]
10662 && mParallelPorts[slot]->isModified())
10663 {
10664 mParallelPorts[slot]->rollback();
10665 parallelPorts[slot] = mParallelPorts[slot];
10666 }
10667
10668 if (aNotify)
10669 {
10670 /* inform the direct session about changes */
10671
10672 ComObjPtr<Machine> that = this;
10673 uint32_t flModifications = mData->flModifications;
10674 alock.leave();
10675
10676 if (flModifications & IsModified_SharedFolders)
10677 that->onSharedFolderChange();
10678
10679 if (flModifications & IsModified_VRDEServer)
10680 that->onVRDEServerChange(/* aRestart */ TRUE);
10681 if (flModifications & IsModified_USB)
10682 that->onUSBControllerChange();
10683
10684 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
10685 if (networkAdapters[slot])
10686 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
10687 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
10688 if (serialPorts[slot])
10689 that->onSerialPortChange(serialPorts[slot]);
10690 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
10691 if (parallelPorts[slot])
10692 that->onParallelPortChange(parallelPorts[slot]);
10693
10694 if (flModifications & IsModified_Storage)
10695 that->onStorageControllerChange();
10696
10697#if 0
10698 if (flModifications & IsModified_BandwidthControl)
10699 that->onBandwidthControlChange();
10700#endif
10701 }
10702}
10703
10704/**
10705 * Commits all the changes to machine settings.
10706 *
10707 * Note that this operation is supposed to never fail.
10708 *
10709 * @note Locks this object and children for writing.
10710 */
10711void Machine::commit()
10712{
10713 AutoCaller autoCaller(this);
10714 AssertComRCReturnVoid(autoCaller.rc());
10715
10716 AutoCaller peerCaller(mPeer);
10717 AssertComRCReturnVoid(peerCaller.rc());
10718
10719 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
10720
10721 /*
10722 * use safe commit to ensure Snapshot machines (that share mUserData)
10723 * will still refer to a valid memory location
10724 */
10725 mUserData.commitCopy();
10726
10727 mHWData.commit();
10728
10729 if (mMediaData.isBackedUp())
10730 commitMedia();
10731
10732 mBIOSSettings->commit();
10733 mVRDEServer->commit();
10734 mAudioAdapter->commit();
10735 mUSBController->commit();
10736 mBandwidthControl->commit();
10737
10738 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10739 mNetworkAdapters[slot]->commit();
10740 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10741 mSerialPorts[slot]->commit();
10742 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10743 mParallelPorts[slot]->commit();
10744
10745 bool commitStorageControllers = false;
10746
10747 if (mStorageControllers.isBackedUp())
10748 {
10749 mStorageControllers.commit();
10750
10751 if (mPeer)
10752 {
10753 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
10754
10755 /* Commit all changes to new controllers (this will reshare data with
10756 * peers for those who have peers) */
10757 StorageControllerList *newList = new StorageControllerList();
10758 StorageControllerList::const_iterator it = mStorageControllers->begin();
10759 while (it != mStorageControllers->end())
10760 {
10761 (*it)->commit();
10762
10763 /* look if this controller has a peer device */
10764 ComObjPtr<StorageController> peer = (*it)->getPeer();
10765 if (!peer)
10766 {
10767 /* no peer means the device is a newly created one;
10768 * create a peer owning data this device share it with */
10769 peer.createObject();
10770 peer->init(mPeer, *it, true /* aReshare */);
10771 }
10772 else
10773 {
10774 /* remove peer from the old list */
10775 mPeer->mStorageControllers->remove(peer);
10776 }
10777 /* and add it to the new list */
10778 newList->push_back(peer);
10779
10780 ++it;
10781 }
10782
10783 /* uninit old peer's controllers that are left */
10784 it = mPeer->mStorageControllers->begin();
10785 while (it != mPeer->mStorageControllers->end())
10786 {
10787 (*it)->uninit();
10788 ++it;
10789 }
10790
10791 /* attach new list of controllers to our peer */
10792 mPeer->mStorageControllers.attach(newList);
10793 }
10794 else
10795 {
10796 /* we have no peer (our parent is the newly created machine);
10797 * just commit changes to devices */
10798 commitStorageControllers = true;
10799 }
10800 }
10801 else
10802 {
10803 /* the list of controllers itself is not changed,
10804 * just commit changes to controllers themselves */
10805 commitStorageControllers = true;
10806 }
10807
10808 if (commitStorageControllers)
10809 {
10810 StorageControllerList::const_iterator it = mStorageControllers->begin();
10811 while (it != mStorageControllers->end())
10812 {
10813 (*it)->commit();
10814 ++it;
10815 }
10816 }
10817
10818 if (isSessionMachine())
10819 {
10820 /* attach new data to the primary machine and reshare it */
10821 mPeer->mUserData.attach(mUserData);
10822 mPeer->mHWData.attach(mHWData);
10823 /* mMediaData is reshared by fixupMedia */
10824 // mPeer->mMediaData.attach(mMediaData);
10825 Assert(mPeer->mMediaData.data() == mMediaData.data());
10826 }
10827}
10828
10829/**
10830 * Copies all the hardware data from the given machine.
10831 *
10832 * Currently, only called when the VM is being restored from a snapshot. In
10833 * particular, this implies that the VM is not running during this method's
10834 * call.
10835 *
10836 * @note This method must be called from under this object's lock.
10837 *
10838 * @note This method doesn't call #commit(), so all data remains backed up and
10839 * unsaved.
10840 */
10841void Machine::copyFrom(Machine *aThat)
10842{
10843 AssertReturnVoid(!isSnapshotMachine());
10844 AssertReturnVoid(aThat->isSnapshotMachine());
10845
10846 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
10847
10848 mHWData.assignCopy(aThat->mHWData);
10849
10850 // create copies of all shared folders (mHWData after attaching a copy
10851 // contains just references to original objects)
10852 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10853 it != mHWData->mSharedFolders.end();
10854 ++it)
10855 {
10856 ComObjPtr<SharedFolder> folder;
10857 folder.createObject();
10858 HRESULT rc = folder->initCopy(getMachine(), *it);
10859 AssertComRC(rc);
10860 *it = folder;
10861 }
10862
10863 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
10864 mVRDEServer->copyFrom(aThat->mVRDEServer);
10865 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
10866 mUSBController->copyFrom(aThat->mUSBController);
10867 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10868
10869 /* create private copies of all controllers */
10870 mStorageControllers.backup();
10871 mStorageControllers->clear();
10872 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10873 it != aThat->mStorageControllers->end();
10874 ++it)
10875 {
10876 ComObjPtr<StorageController> ctrl;
10877 ctrl.createObject();
10878 ctrl->initCopy(this, *it);
10879 mStorageControllers->push_back(ctrl);
10880 }
10881
10882 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10883 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10884 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10885 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10886 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10887 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10888}
10889
10890/**
10891 * Returns whether the given storage controller is hotplug capable.
10892 *
10893 * @returns true if the controller supports hotplugging
10894 * false otherwise.
10895 * @param enmCtrlType The controller type to check for.
10896 */
10897bool Machine::isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
10898{
10899 switch (enmCtrlType)
10900 {
10901 case StorageControllerType_IntelAhci:
10902 return true;
10903 case StorageControllerType_LsiLogic:
10904 case StorageControllerType_LsiLogicSas:
10905 case StorageControllerType_BusLogic:
10906 case StorageControllerType_PIIX3:
10907 case StorageControllerType_PIIX4:
10908 case StorageControllerType_ICH6:
10909 case StorageControllerType_I82078:
10910 default:
10911 return false;
10912 }
10913}
10914
10915#ifdef VBOX_WITH_RESOURCE_USAGE_API
10916
10917void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10918{
10919 AssertReturnVoid(isWriteLockOnCurrentThread());
10920 AssertPtrReturnVoid(aCollector);
10921
10922 pm::CollectorHAL *hal = aCollector->getHAL();
10923 /* Create sub metrics */
10924 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10925 "Percentage of processor time spent in user mode by the VM process.");
10926 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10927 "Percentage of processor time spent in kernel mode by the VM process.");
10928 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10929 "Size of resident portion of VM process in memory.");
10930 /* Create and register base metrics */
10931 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10932 cpuLoadUser, cpuLoadKernel);
10933 aCollector->registerBaseMetric(cpuLoad);
10934 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10935 ramUsageUsed);
10936 aCollector->registerBaseMetric(ramUsage);
10937
10938 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10939 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10940 new pm::AggregateAvg()));
10941 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10942 new pm::AggregateMin()));
10943 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10944 new pm::AggregateMax()));
10945 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10946 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10947 new pm::AggregateAvg()));
10948 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10949 new pm::AggregateMin()));
10950 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10951 new pm::AggregateMax()));
10952
10953 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10954 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10955 new pm::AggregateAvg()));
10956 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10957 new pm::AggregateMin()));
10958 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10959 new pm::AggregateMax()));
10960
10961
10962 /* Guest metrics collector */
10963 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10964 aCollector->registerGuest(mCollectorGuest);
10965 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10966 this, __PRETTY_FUNCTION__, mCollectorGuest));
10967
10968 /* Create sub metrics */
10969 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10970 "Percentage of processor time spent in user mode as seen by the guest.");
10971 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10972 "Percentage of processor time spent in kernel mode as seen by the guest.");
10973 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10974 "Percentage of processor time spent idling as seen by the guest.");
10975
10976 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10977 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10978 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10979 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10980 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10981 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10982
10983 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10984
10985 /* Create and register base metrics */
10986 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10987 guestLoadUser, guestLoadKernel, guestLoadIdle);
10988 aCollector->registerBaseMetric(guestCpuLoad);
10989
10990 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10991 guestMemTotal, guestMemFree,
10992 guestMemBalloon, guestMemShared,
10993 guestMemCache, guestPagedTotal);
10994 aCollector->registerBaseMetric(guestCpuMem);
10995
10996 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10997 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10998 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10999 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
11000
11001 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
11002 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
11003 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
11004 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
11005
11006 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
11007 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
11008 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
11009 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
11010
11011 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
11012 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
11013 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
11014 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
11015
11016 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
11017 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
11018 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
11019 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
11020
11021 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
11022 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
11023 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
11024 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
11025
11026 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
11027 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
11028 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
11029 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
11030
11031 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
11032 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
11033 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
11034 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
11035
11036 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
11037 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
11038 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
11039 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
11040}
11041
11042void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
11043{
11044 AssertReturnVoid(isWriteLockOnCurrentThread());
11045
11046 if (aCollector)
11047 {
11048 aCollector->unregisterMetricsFor(aMachine);
11049 aCollector->unregisterBaseMetricsFor(aMachine);
11050 }
11051}
11052
11053#endif /* VBOX_WITH_RESOURCE_USAGE_API */
11054
11055
11056////////////////////////////////////////////////////////////////////////////////
11057
11058DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
11059
11060HRESULT SessionMachine::FinalConstruct()
11061{
11062 LogFlowThisFunc(("\n"));
11063
11064#if defined(RT_OS_WINDOWS)
11065 mIPCSem = NULL;
11066#elif defined(RT_OS_OS2)
11067 mIPCSem = NULLHANDLE;
11068#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11069 mIPCSem = -1;
11070#else
11071# error "Port me!"
11072#endif
11073
11074 return BaseFinalConstruct();
11075}
11076
11077void SessionMachine::FinalRelease()
11078{
11079 LogFlowThisFunc(("\n"));
11080
11081 uninit(Uninit::Unexpected);
11082
11083 BaseFinalRelease();
11084}
11085
11086/**
11087 * @note Must be called only by Machine::openSession() from its own write lock.
11088 */
11089HRESULT SessionMachine::init(Machine *aMachine)
11090{
11091 LogFlowThisFuncEnter();
11092 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
11093
11094 AssertReturn(aMachine, E_INVALIDARG);
11095
11096 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
11097
11098 /* Enclose the state transition NotReady->InInit->Ready */
11099 AutoInitSpan autoInitSpan(this);
11100 AssertReturn(autoInitSpan.isOk(), E_FAIL);
11101
11102 /* create the interprocess semaphore */
11103#if defined(RT_OS_WINDOWS)
11104 mIPCSemName = aMachine->mData->m_strConfigFileFull;
11105 for (size_t i = 0; i < mIPCSemName.length(); i++)
11106 if (mIPCSemName.raw()[i] == '\\')
11107 mIPCSemName.raw()[i] = '/';
11108 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
11109 ComAssertMsgRet(mIPCSem,
11110 ("Cannot create IPC mutex '%ls', err=%d",
11111 mIPCSemName.raw(), ::GetLastError()),
11112 E_FAIL);
11113#elif defined(RT_OS_OS2)
11114 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
11115 aMachine->mData->mUuid.raw());
11116 mIPCSemName = ipcSem;
11117 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
11118 ComAssertMsgRet(arc == NO_ERROR,
11119 ("Cannot create IPC mutex '%s', arc=%ld",
11120 ipcSem.c_str(), arc),
11121 E_FAIL);
11122#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11123# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11124# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
11125 /** @todo Check that this still works correctly. */
11126 AssertCompileSize(key_t, 8);
11127# else
11128 AssertCompileSize(key_t, 4);
11129# endif
11130 key_t key;
11131 mIPCSem = -1;
11132 mIPCKey = "0";
11133 for (uint32_t i = 0; i < 1 << 24; i++)
11134 {
11135 key = ((uint32_t)'V' << 24) | i;
11136 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
11137 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
11138 {
11139 mIPCSem = sem;
11140 if (sem >= 0)
11141 mIPCKey = BstrFmt("%u", key);
11142 break;
11143 }
11144 }
11145# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11146 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
11147 char *pszSemName = NULL;
11148 RTStrUtf8ToCurrentCP(&pszSemName, semName);
11149 key_t key = ::ftok(pszSemName, 'V');
11150 RTStrFree(pszSemName);
11151
11152 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
11153# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11154
11155 int errnoSave = errno;
11156 if (mIPCSem < 0 && errnoSave == ENOSYS)
11157 {
11158 setError(E_FAIL,
11159 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
11160 "support for SysV IPC. Check the host kernel configuration for "
11161 "CONFIG_SYSVIPC=y"));
11162 return E_FAIL;
11163 }
11164 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
11165 * the IPC semaphores */
11166 if (mIPCSem < 0 && errnoSave == ENOSPC)
11167 {
11168#ifdef RT_OS_LINUX
11169 setError(E_FAIL,
11170 tr("Cannot create IPC semaphore because the system limit for the "
11171 "maximum number of semaphore sets (SEMMNI), or the system wide "
11172 "maximum number of semaphores (SEMMNS) would be exceeded. The "
11173 "current set of SysV IPC semaphores can be determined from "
11174 "the file /proc/sysvipc/sem"));
11175#else
11176 setError(E_FAIL,
11177 tr("Cannot create IPC semaphore because the system-imposed limit "
11178 "on the maximum number of allowed semaphores or semaphore "
11179 "identifiers system-wide would be exceeded"));
11180#endif
11181 return E_FAIL;
11182 }
11183 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
11184 E_FAIL);
11185 /* set the initial value to 1 */
11186 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
11187 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
11188 E_FAIL);
11189#else
11190# error "Port me!"
11191#endif
11192
11193 /* memorize the peer Machine */
11194 unconst(mPeer) = aMachine;
11195 /* share the parent pointer */
11196 unconst(mParent) = aMachine->mParent;
11197
11198 /* take the pointers to data to share */
11199 mData.share(aMachine->mData);
11200 mSSData.share(aMachine->mSSData);
11201
11202 mUserData.share(aMachine->mUserData);
11203 mHWData.share(aMachine->mHWData);
11204 mMediaData.share(aMachine->mMediaData);
11205
11206 mStorageControllers.allocate();
11207 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
11208 it != aMachine->mStorageControllers->end();
11209 ++it)
11210 {
11211 ComObjPtr<StorageController> ctl;
11212 ctl.createObject();
11213 ctl->init(this, *it);
11214 mStorageControllers->push_back(ctl);
11215 }
11216
11217 unconst(mBIOSSettings).createObject();
11218 mBIOSSettings->init(this, aMachine->mBIOSSettings);
11219 /* create another VRDEServer object that will be mutable */
11220 unconst(mVRDEServer).createObject();
11221 mVRDEServer->init(this, aMachine->mVRDEServer);
11222 /* create another audio adapter object that will be mutable */
11223 unconst(mAudioAdapter).createObject();
11224 mAudioAdapter->init(this, aMachine->mAudioAdapter);
11225 /* create a list of serial ports that will be mutable */
11226 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
11227 {
11228 unconst(mSerialPorts[slot]).createObject();
11229 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
11230 }
11231 /* create a list of parallel ports that will be mutable */
11232 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
11233 {
11234 unconst(mParallelPorts[slot]).createObject();
11235 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
11236 }
11237 /* create another USB controller object that will be mutable */
11238 unconst(mUSBController).createObject();
11239 mUSBController->init(this, aMachine->mUSBController);
11240
11241 /* create a list of network adapters that will be mutable */
11242 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
11243 {
11244 unconst(mNetworkAdapters[slot]).createObject();
11245 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
11246 }
11247
11248 /* create another bandwidth control object that will be mutable */
11249 unconst(mBandwidthControl).createObject();
11250 mBandwidthControl->init(this, aMachine->mBandwidthControl);
11251
11252 /* default is to delete saved state on Saved -> PoweredOff transition */
11253 mRemoveSavedState = true;
11254
11255 /* Confirm a successful initialization when it's the case */
11256 autoInitSpan.setSucceeded();
11257
11258 LogFlowThisFuncLeave();
11259 return S_OK;
11260}
11261
11262/**
11263 * Uninitializes this session object. If the reason is other than
11264 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
11265 *
11266 * @param aReason uninitialization reason
11267 *
11268 * @note Locks mParent + this object for writing.
11269 */
11270void SessionMachine::uninit(Uninit::Reason aReason)
11271{
11272 LogFlowThisFuncEnter();
11273 LogFlowThisFunc(("reason=%d\n", aReason));
11274
11275 /*
11276 * Strongly reference ourselves to prevent this object deletion after
11277 * mData->mSession.mMachine.setNull() below (which can release the last
11278 * reference and call the destructor). Important: this must be done before
11279 * accessing any members (and before AutoUninitSpan that does it as well).
11280 * This self reference will be released as the very last step on return.
11281 */
11282 ComObjPtr<SessionMachine> selfRef = this;
11283
11284 /* Enclose the state transition Ready->InUninit->NotReady */
11285 AutoUninitSpan autoUninitSpan(this);
11286 if (autoUninitSpan.uninitDone())
11287 {
11288 LogFlowThisFunc(("Already uninitialized\n"));
11289 LogFlowThisFuncLeave();
11290 return;
11291 }
11292
11293 if (autoUninitSpan.initFailed())
11294 {
11295 /* We've been called by init() because it's failed. It's not really
11296 * necessary (nor it's safe) to perform the regular uninit sequence
11297 * below, the following is enough.
11298 */
11299 LogFlowThisFunc(("Initialization failed.\n"));
11300#if defined(RT_OS_WINDOWS)
11301 if (mIPCSem)
11302 ::CloseHandle(mIPCSem);
11303 mIPCSem = NULL;
11304#elif defined(RT_OS_OS2)
11305 if (mIPCSem != NULLHANDLE)
11306 ::DosCloseMutexSem(mIPCSem);
11307 mIPCSem = NULLHANDLE;
11308#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11309 if (mIPCSem >= 0)
11310 ::semctl(mIPCSem, 0, IPC_RMID);
11311 mIPCSem = -1;
11312# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11313 mIPCKey = "0";
11314# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
11315#else
11316# error "Port me!"
11317#endif
11318 uninitDataAndChildObjects();
11319 mData.free();
11320 unconst(mParent) = NULL;
11321 unconst(mPeer) = NULL;
11322 LogFlowThisFuncLeave();
11323 return;
11324 }
11325
11326 MachineState_T lastState;
11327 {
11328 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
11329 lastState = mData->mMachineState;
11330 }
11331 NOREF(lastState);
11332
11333#ifdef VBOX_WITH_USB
11334 // release all captured USB devices, but do this before requesting the locks below
11335 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
11336 {
11337 /* Console::captureUSBDevices() is called in the VM process only after
11338 * setting the machine state to Starting or Restoring.
11339 * Console::detachAllUSBDevices() will be called upon successful
11340 * termination. So, we need to release USB devices only if there was
11341 * an abnormal termination of a running VM.
11342 *
11343 * This is identical to SessionMachine::DetachAllUSBDevices except
11344 * for the aAbnormal argument. */
11345 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11346 AssertComRC(rc);
11347 NOREF(rc);
11348
11349 USBProxyService *service = mParent->host()->usbProxyService();
11350 if (service)
11351 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
11352 }
11353#endif /* VBOX_WITH_USB */
11354
11355 // we need to lock this object in uninit() because the lock is shared
11356 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
11357 // and others need mParent lock, and USB needs host lock.
11358 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
11359
11360 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
11361 this, __PRETTY_FUNCTION__, mCollectorGuest));
11362 if (mCollectorGuest)
11363 {
11364 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
11365 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
11366 mCollectorGuest = NULL;
11367 }
11368#if 0
11369 // Trigger async cleanup tasks, avoid doing things here which are not
11370 // vital to be done immediately and maybe need more locks. This calls
11371 // Machine::unregisterMetrics().
11372 mParent->onMachineUninit(mPeer);
11373#else
11374 /*
11375 * It is safe to call Machine::unregisterMetrics() here because
11376 * PerformanceCollector::samplerCallback no longer accesses guest methods
11377 * holding the lock.
11378 */
11379 unregisterMetrics(mParent->performanceCollector(), mPeer);
11380#endif
11381
11382 if (aReason == Uninit::Abnormal)
11383 {
11384 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
11385 Global::IsOnlineOrTransient(lastState)));
11386
11387 /* reset the state to Aborted */
11388 if (mData->mMachineState != MachineState_Aborted)
11389 setMachineState(MachineState_Aborted);
11390 }
11391
11392 // any machine settings modified?
11393 if (mData->flModifications)
11394 {
11395 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
11396 rollback(false /* aNotify */);
11397 }
11398
11399 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
11400 || !mConsoleTaskData.mSnapshot);
11401 if (!mConsoleTaskData.strStateFilePath.isEmpty())
11402 {
11403 LogWarningThisFunc(("canceling failed save state request!\n"));
11404 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
11405 }
11406 else if (!mConsoleTaskData.mSnapshot.isNull())
11407 {
11408 LogWarningThisFunc(("canceling untaken snapshot!\n"));
11409
11410 /* delete all differencing hard disks created (this will also attach
11411 * their parents back by rolling back mMediaData) */
11412 rollbackMedia();
11413
11414 // delete the saved state file (it might have been already created)
11415 // AFTER killing the snapshot so that releaseSavedStateFile() won't
11416 // think it's still in use
11417 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
11418 mConsoleTaskData.mSnapshot->uninit();
11419 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
11420 }
11421
11422 if (!mData->mSession.mType.isEmpty())
11423 {
11424 /* mType is not null when this machine's process has been started by
11425 * Machine::LaunchVMProcess(), therefore it is our child. We
11426 * need to queue the PID to reap the process (and avoid zombies on
11427 * Linux). */
11428 Assert(mData->mSession.mPid != NIL_RTPROCESS);
11429 mParent->addProcessToReap(mData->mSession.mPid);
11430 }
11431
11432 mData->mSession.mPid = NIL_RTPROCESS;
11433
11434 if (aReason == Uninit::Unexpected)
11435 {
11436 /* Uninitialization didn't come from #checkForDeath(), so tell the
11437 * client watcher thread to update the set of machines that have open
11438 * sessions. */
11439 mParent->updateClientWatcher();
11440 }
11441
11442 /* uninitialize all remote controls */
11443 if (mData->mSession.mRemoteControls.size())
11444 {
11445 LogFlowThisFunc(("Closing remote sessions (%d):\n",
11446 mData->mSession.mRemoteControls.size()));
11447
11448 Data::Session::RemoteControlList::iterator it =
11449 mData->mSession.mRemoteControls.begin();
11450 while (it != mData->mSession.mRemoteControls.end())
11451 {
11452 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
11453 HRESULT rc = (*it)->Uninitialize();
11454 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
11455 if (FAILED(rc))
11456 LogWarningThisFunc(("Forgot to close the remote session?\n"));
11457 ++it;
11458 }
11459 mData->mSession.mRemoteControls.clear();
11460 }
11461
11462 /*
11463 * An expected uninitialization can come only from #checkForDeath().
11464 * Otherwise it means that something's gone really wrong (for example,
11465 * the Session implementation has released the VirtualBox reference
11466 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
11467 * etc). However, it's also possible, that the client releases the IPC
11468 * semaphore correctly (i.e. before it releases the VirtualBox reference),
11469 * but the VirtualBox release event comes first to the server process.
11470 * This case is practically possible, so we should not assert on an
11471 * unexpected uninit, just log a warning.
11472 */
11473
11474 if ((aReason == Uninit::Unexpected))
11475 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
11476
11477 if (aReason != Uninit::Normal)
11478 {
11479 mData->mSession.mDirectControl.setNull();
11480 }
11481 else
11482 {
11483 /* this must be null here (see #OnSessionEnd()) */
11484 Assert(mData->mSession.mDirectControl.isNull());
11485 Assert(mData->mSession.mState == SessionState_Unlocking);
11486 Assert(!mData->mSession.mProgress.isNull());
11487 }
11488 if (mData->mSession.mProgress)
11489 {
11490 if (aReason == Uninit::Normal)
11491 mData->mSession.mProgress->notifyComplete(S_OK);
11492 else
11493 mData->mSession.mProgress->notifyComplete(E_FAIL,
11494 COM_IIDOF(ISession),
11495 getComponentName(),
11496 tr("The VM session was aborted"));
11497 mData->mSession.mProgress.setNull();
11498 }
11499
11500 /* remove the association between the peer machine and this session machine */
11501 Assert( (SessionMachine*)mData->mSession.mMachine == this
11502 || aReason == Uninit::Unexpected);
11503
11504 /* reset the rest of session data */
11505 mData->mSession.mMachine.setNull();
11506 mData->mSession.mState = SessionState_Unlocked;
11507 mData->mSession.mType.setNull();
11508
11509 /* close the interprocess semaphore before leaving the exclusive lock */
11510#if defined(RT_OS_WINDOWS)
11511 if (mIPCSem)
11512 ::CloseHandle(mIPCSem);
11513 mIPCSem = NULL;
11514#elif defined(RT_OS_OS2)
11515 if (mIPCSem != NULLHANDLE)
11516 ::DosCloseMutexSem(mIPCSem);
11517 mIPCSem = NULLHANDLE;
11518#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11519 if (mIPCSem >= 0)
11520 ::semctl(mIPCSem, 0, IPC_RMID);
11521 mIPCSem = -1;
11522# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11523 mIPCKey = "0";
11524# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
11525#else
11526# error "Port me!"
11527#endif
11528
11529 /* fire an event */
11530 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
11531
11532 uninitDataAndChildObjects();
11533
11534 /* free the essential data structure last */
11535 mData.free();
11536
11537#if 1 /** @todo Please review this change! (bird) */
11538 /* drop the exclusive lock before setting the below two to NULL */
11539 multilock.release();
11540#else
11541 /* leave the exclusive lock before setting the below two to NULL */
11542 multilock.leave();
11543#endif
11544
11545 unconst(mParent) = NULL;
11546 unconst(mPeer) = NULL;
11547
11548 LogFlowThisFuncLeave();
11549}
11550
11551// util::Lockable interface
11552////////////////////////////////////////////////////////////////////////////////
11553
11554/**
11555 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
11556 * with the primary Machine instance (mPeer).
11557 */
11558RWLockHandle *SessionMachine::lockHandle() const
11559{
11560 AssertReturn(mPeer != NULL, NULL);
11561 return mPeer->lockHandle();
11562}
11563
11564// IInternalMachineControl methods
11565////////////////////////////////////////////////////////////////////////////////
11566
11567/**
11568 * @note Locks this object for writing.
11569 */
11570STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
11571{
11572 AutoCaller autoCaller(this);
11573 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11574
11575 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11576
11577 mRemoveSavedState = aRemove;
11578
11579 return S_OK;
11580}
11581
11582/**
11583 * @note Locks the same as #setMachineState() does.
11584 */
11585STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
11586{
11587 return setMachineState(aMachineState);
11588}
11589
11590/**
11591 * @note Locks this object for reading.
11592 */
11593STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
11594{
11595 AutoCaller autoCaller(this);
11596 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11597
11598 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11599
11600#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
11601 mIPCSemName.cloneTo(aId);
11602 return S_OK;
11603#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11604# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11605 mIPCKey.cloneTo(aId);
11606# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11607 mData->m_strConfigFileFull.cloneTo(aId);
11608# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11609 return S_OK;
11610#else
11611# error "Port me!"
11612#endif
11613}
11614
11615/**
11616 * @note Locks this object for writing.
11617 */
11618STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
11619{
11620 LogFlowThisFunc(("aProgress=%p\n", aProgress));
11621 AutoCaller autoCaller(this);
11622 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11623
11624 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11625
11626 if (mData->mSession.mState != SessionState_Locked)
11627 return VBOX_E_INVALID_OBJECT_STATE;
11628
11629 if (!mData->mSession.mProgress.isNull())
11630 mData->mSession.mProgress->setOtherProgressObject(aProgress);
11631
11632 LogFlowThisFunc(("returns S_OK.\n"));
11633 return S_OK;
11634}
11635
11636/**
11637 * @note Locks this object for writing.
11638 */
11639STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
11640{
11641 AutoCaller autoCaller(this);
11642 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11643
11644 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11645
11646 if (mData->mSession.mState != SessionState_Locked)
11647 return VBOX_E_INVALID_OBJECT_STATE;
11648
11649 /* Finalize the LaunchVMProcess progress object. */
11650 if (mData->mSession.mProgress)
11651 {
11652 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
11653 mData->mSession.mProgress.setNull();
11654 }
11655
11656 if (SUCCEEDED((HRESULT)iResult))
11657 {
11658#ifdef VBOX_WITH_RESOURCE_USAGE_API
11659 /* The VM has been powered up successfully, so it makes sense
11660 * now to offer the performance metrics for a running machine
11661 * object. Doing it earlier wouldn't be safe. */
11662 registerMetrics(mParent->performanceCollector(), mPeer,
11663 mData->mSession.mPid);
11664#endif /* VBOX_WITH_RESOURCE_USAGE_API */
11665 }
11666
11667 return S_OK;
11668}
11669
11670/**
11671 * @note Locks this object for writing.
11672 */
11673STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
11674{
11675 LogFlowThisFuncEnter();
11676
11677 CheckComArgOutPointerValid(aProgress);
11678
11679 AutoCaller autoCaller(this);
11680 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11681
11682 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11683
11684 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
11685 E_FAIL);
11686
11687 /* create a progress object to track operation completion */
11688 ComObjPtr<Progress> pProgress;
11689 pProgress.createObject();
11690 pProgress->init(getVirtualBox(),
11691 static_cast<IMachine *>(this) /* aInitiator */,
11692 Bstr(tr("Stopping the virtual machine")).raw(),
11693 FALSE /* aCancelable */);
11694
11695 /* fill in the console task data */
11696 mConsoleTaskData.mLastState = mData->mMachineState;
11697 mConsoleTaskData.mProgress = pProgress;
11698
11699 /* set the state to Stopping (this is expected by Console::PowerDown()) */
11700 setMachineState(MachineState_Stopping);
11701
11702 pProgress.queryInterfaceTo(aProgress);
11703
11704 return S_OK;
11705}
11706
11707/**
11708 * @note Locks this object for writing.
11709 */
11710STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
11711{
11712 LogFlowThisFuncEnter();
11713
11714 AutoCaller autoCaller(this);
11715 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11716
11717 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11718
11719 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
11720 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
11721 && mConsoleTaskData.mLastState != MachineState_Null,
11722 E_FAIL);
11723
11724 /*
11725 * On failure, set the state to the state we had when BeginPoweringDown()
11726 * was called (this is expected by Console::PowerDown() and the associated
11727 * task). On success the VM process already changed the state to
11728 * MachineState_PoweredOff, so no need to do anything.
11729 */
11730 if (FAILED(iResult))
11731 setMachineState(mConsoleTaskData.mLastState);
11732
11733 /* notify the progress object about operation completion */
11734 Assert(mConsoleTaskData.mProgress);
11735 if (SUCCEEDED(iResult))
11736 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11737 else
11738 {
11739 Utf8Str strErrMsg(aErrMsg);
11740 if (strErrMsg.length())
11741 mConsoleTaskData.mProgress->notifyComplete(iResult,
11742 COM_IIDOF(ISession),
11743 getComponentName(),
11744 strErrMsg.c_str());
11745 else
11746 mConsoleTaskData.mProgress->notifyComplete(iResult);
11747 }
11748
11749 /* clear out the temporary saved state data */
11750 mConsoleTaskData.mLastState = MachineState_Null;
11751 mConsoleTaskData.mProgress.setNull();
11752
11753 LogFlowThisFuncLeave();
11754 return S_OK;
11755}
11756
11757
11758/**
11759 * Goes through the USB filters of the given machine to see if the given
11760 * device matches any filter or not.
11761 *
11762 * @note Locks the same as USBController::hasMatchingFilter() does.
11763 */
11764STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
11765 BOOL *aMatched,
11766 ULONG *aMaskedIfs)
11767{
11768 LogFlowThisFunc(("\n"));
11769
11770 CheckComArgNotNull(aUSBDevice);
11771 CheckComArgOutPointerValid(aMatched);
11772
11773 AutoCaller autoCaller(this);
11774 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11775
11776#ifdef VBOX_WITH_USB
11777 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
11778#else
11779 NOREF(aUSBDevice);
11780 NOREF(aMaskedIfs);
11781 *aMatched = FALSE;
11782#endif
11783
11784 return S_OK;
11785}
11786
11787/**
11788 * @note Locks the same as Host::captureUSBDevice() does.
11789 */
11790STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
11791{
11792 LogFlowThisFunc(("\n"));
11793
11794 AutoCaller autoCaller(this);
11795 AssertComRCReturnRC(autoCaller.rc());
11796
11797#ifdef VBOX_WITH_USB
11798 /* if captureDeviceForVM() fails, it must have set extended error info */
11799 clearError();
11800 MultiResult rc = mParent->host()->checkUSBProxyService();
11801 if (FAILED(rc)) return rc;
11802
11803 USBProxyService *service = mParent->host()->usbProxyService();
11804 AssertReturn(service, E_FAIL);
11805 return service->captureDeviceForVM(this, Guid(aId).ref());
11806#else
11807 NOREF(aId);
11808 return E_NOTIMPL;
11809#endif
11810}
11811
11812/**
11813 * @note Locks the same as Host::detachUSBDevice() does.
11814 */
11815STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
11816{
11817 LogFlowThisFunc(("\n"));
11818
11819 AutoCaller autoCaller(this);
11820 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11821
11822#ifdef VBOX_WITH_USB
11823 USBProxyService *service = mParent->host()->usbProxyService();
11824 AssertReturn(service, E_FAIL);
11825 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
11826#else
11827 NOREF(aId);
11828 NOREF(aDone);
11829 return E_NOTIMPL;
11830#endif
11831}
11832
11833/**
11834 * Inserts all machine filters to the USB proxy service and then calls
11835 * Host::autoCaptureUSBDevices().
11836 *
11837 * Called by Console from the VM process upon VM startup.
11838 *
11839 * @note Locks what called methods lock.
11840 */
11841STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
11842{
11843 LogFlowThisFunc(("\n"));
11844
11845 AutoCaller autoCaller(this);
11846 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11847
11848#ifdef VBOX_WITH_USB
11849 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
11850 AssertComRC(rc);
11851 NOREF(rc);
11852
11853 USBProxyService *service = mParent->host()->usbProxyService();
11854 AssertReturn(service, E_FAIL);
11855 return service->autoCaptureDevicesForVM(this);
11856#else
11857 return S_OK;
11858#endif
11859}
11860
11861/**
11862 * Removes all machine filters from the USB proxy service and then calls
11863 * Host::detachAllUSBDevices().
11864 *
11865 * Called by Console from the VM process upon normal VM termination or by
11866 * SessionMachine::uninit() upon abnormal VM termination (from under the
11867 * Machine/SessionMachine lock).
11868 *
11869 * @note Locks what called methods lock.
11870 */
11871STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
11872{
11873 LogFlowThisFunc(("\n"));
11874
11875 AutoCaller autoCaller(this);
11876 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11877
11878#ifdef VBOX_WITH_USB
11879 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11880 AssertComRC(rc);
11881 NOREF(rc);
11882
11883 USBProxyService *service = mParent->host()->usbProxyService();
11884 AssertReturn(service, E_FAIL);
11885 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
11886#else
11887 NOREF(aDone);
11888 return S_OK;
11889#endif
11890}
11891
11892/**
11893 * @note Locks this object for writing.
11894 */
11895STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
11896 IProgress **aProgress)
11897{
11898 LogFlowThisFuncEnter();
11899
11900 AssertReturn(aSession, E_INVALIDARG);
11901 AssertReturn(aProgress, E_INVALIDARG);
11902
11903 AutoCaller autoCaller(this);
11904
11905 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11906 /*
11907 * We don't assert below because it might happen that a non-direct session
11908 * informs us it is closed right after we've been uninitialized -- it's ok.
11909 */
11910 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11911
11912 /* get IInternalSessionControl interface */
11913 ComPtr<IInternalSessionControl> control(aSession);
11914
11915 ComAssertRet(!control.isNull(), E_INVALIDARG);
11916
11917 /* Creating a Progress object requires the VirtualBox lock, and
11918 * thus locking it here is required by the lock order rules. */
11919 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
11920
11921 if (control == mData->mSession.mDirectControl)
11922 {
11923 ComAssertRet(aProgress, E_POINTER);
11924
11925 /* The direct session is being normally closed by the client process
11926 * ----------------------------------------------------------------- */
11927
11928 /* go to the closing state (essential for all open*Session() calls and
11929 * for #checkForDeath()) */
11930 Assert(mData->mSession.mState == SessionState_Locked);
11931 mData->mSession.mState = SessionState_Unlocking;
11932
11933 /* set direct control to NULL to release the remote instance */
11934 mData->mSession.mDirectControl.setNull();
11935 LogFlowThisFunc(("Direct control is set to NULL\n"));
11936
11937 if (mData->mSession.mProgress)
11938 {
11939 /* finalize the progress, someone might wait if a frontend
11940 * closes the session before powering on the VM. */
11941 mData->mSession.mProgress->notifyComplete(E_FAIL,
11942 COM_IIDOF(ISession),
11943 getComponentName(),
11944 tr("The VM session was closed before any attempt to power it on"));
11945 mData->mSession.mProgress.setNull();
11946 }
11947
11948 /* Create the progress object the client will use to wait until
11949 * #checkForDeath() is called to uninitialize this session object after
11950 * it releases the IPC semaphore.
11951 * Note! Because we're "reusing" mProgress here, this must be a proxy
11952 * object just like for LaunchVMProcess. */
11953 Assert(mData->mSession.mProgress.isNull());
11954 ComObjPtr<ProgressProxy> progress;
11955 progress.createObject();
11956 ComPtr<IUnknown> pPeer(mPeer);
11957 progress->init(mParent, pPeer,
11958 Bstr(tr("Closing session")).raw(),
11959 FALSE /* aCancelable */);
11960 progress.queryInterfaceTo(aProgress);
11961 mData->mSession.mProgress = progress;
11962 }
11963 else
11964 {
11965 /* the remote session is being normally closed */
11966 Data::Session::RemoteControlList::iterator it =
11967 mData->mSession.mRemoteControls.begin();
11968 while (it != mData->mSession.mRemoteControls.end())
11969 {
11970 if (control == *it)
11971 break;
11972 ++it;
11973 }
11974 BOOL found = it != mData->mSession.mRemoteControls.end();
11975 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11976 E_INVALIDARG);
11977 mData->mSession.mRemoteControls.remove(*it);
11978 }
11979
11980 LogFlowThisFuncLeave();
11981 return S_OK;
11982}
11983
11984/**
11985 * @note Locks this object for writing.
11986 */
11987STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11988{
11989 LogFlowThisFuncEnter();
11990
11991 CheckComArgOutPointerValid(aProgress);
11992 CheckComArgOutPointerValid(aStateFilePath);
11993
11994 AutoCaller autoCaller(this);
11995 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11996
11997 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11998
11999 AssertReturn( mData->mMachineState == MachineState_Paused
12000 && mConsoleTaskData.mLastState == MachineState_Null
12001 && mConsoleTaskData.strStateFilePath.isEmpty(),
12002 E_FAIL);
12003
12004 /* create a progress object to track operation completion */
12005 ComObjPtr<Progress> pProgress;
12006 pProgress.createObject();
12007 pProgress->init(getVirtualBox(),
12008 static_cast<IMachine *>(this) /* aInitiator */,
12009 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
12010 FALSE /* aCancelable */);
12011
12012 Utf8Str strStateFilePath;
12013 /* stateFilePath is null when the machine is not running */
12014 if (mData->mMachineState == MachineState_Paused)
12015 composeSavedStateFilename(strStateFilePath);
12016
12017 /* fill in the console task data */
12018 mConsoleTaskData.mLastState = mData->mMachineState;
12019 mConsoleTaskData.strStateFilePath = strStateFilePath;
12020 mConsoleTaskData.mProgress = pProgress;
12021
12022 /* set the state to Saving (this is expected by Console::SaveState()) */
12023 setMachineState(MachineState_Saving);
12024
12025 strStateFilePath.cloneTo(aStateFilePath);
12026 pProgress.queryInterfaceTo(aProgress);
12027
12028 return S_OK;
12029}
12030
12031/**
12032 * @note Locks mParent + this object for writing.
12033 */
12034STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
12035{
12036 LogFlowThisFunc(("\n"));
12037
12038 AutoCaller autoCaller(this);
12039 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12040
12041 /* endSavingState() need mParent lock */
12042 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
12043
12044 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
12045 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
12046 && mConsoleTaskData.mLastState != MachineState_Null
12047 && !mConsoleTaskData.strStateFilePath.isEmpty(),
12048 E_FAIL);
12049
12050 /*
12051 * On failure, set the state to the state we had when BeginSavingState()
12052 * was called (this is expected by Console::SaveState() and the associated
12053 * task). On success the VM process already changed the state to
12054 * MachineState_Saved, so no need to do anything.
12055 */
12056 if (FAILED(iResult))
12057 setMachineState(mConsoleTaskData.mLastState);
12058
12059 return endSavingState(iResult, aErrMsg);
12060}
12061
12062/**
12063 * @note Locks this object for writing.
12064 */
12065STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
12066{
12067 LogFlowThisFunc(("\n"));
12068
12069 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
12070
12071 AutoCaller autoCaller(this);
12072 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12073
12074 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12075
12076 AssertReturn( mData->mMachineState == MachineState_PoweredOff
12077 || mData->mMachineState == MachineState_Teleported
12078 || mData->mMachineState == MachineState_Aborted
12079 , E_FAIL); /** @todo setError. */
12080
12081 Utf8Str stateFilePathFull = aSavedStateFile;
12082 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
12083 if (RT_FAILURE(vrc))
12084 return setError(VBOX_E_FILE_ERROR,
12085 tr("Invalid saved state file path '%ls' (%Rrc)"),
12086 aSavedStateFile,
12087 vrc);
12088
12089 mSSData->strStateFilePath = stateFilePathFull;
12090
12091 /* The below setMachineState() will detect the state transition and will
12092 * update the settings file */
12093
12094 return setMachineState(MachineState_Saved);
12095}
12096
12097STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
12098 ComSafeArrayOut(BSTR, aValues),
12099 ComSafeArrayOut(LONG64, aTimestamps),
12100 ComSafeArrayOut(BSTR, aFlags))
12101{
12102 LogFlowThisFunc(("\n"));
12103
12104#ifdef VBOX_WITH_GUEST_PROPS
12105 using namespace guestProp;
12106
12107 AutoCaller autoCaller(this);
12108 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12109
12110 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12111
12112 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
12113 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
12114 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
12115 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
12116
12117 size_t cEntries = mHWData->mGuestProperties.size();
12118 com::SafeArray<BSTR> names(cEntries);
12119 com::SafeArray<BSTR> values(cEntries);
12120 com::SafeArray<LONG64> timestamps(cEntries);
12121 com::SafeArray<BSTR> flags(cEntries);
12122 unsigned i = 0;
12123 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
12124 it != mHWData->mGuestProperties.end();
12125 ++it)
12126 {
12127 char szFlags[MAX_FLAGS_LEN + 1];
12128 it->strName.cloneTo(&names[i]);
12129 it->strValue.cloneTo(&values[i]);
12130 timestamps[i] = it->mTimestamp;
12131 /* If it is NULL, keep it NULL. */
12132 if (it->mFlags)
12133 {
12134 writeFlags(it->mFlags, szFlags);
12135 Bstr(szFlags).cloneTo(&flags[i]);
12136 }
12137 else
12138 flags[i] = NULL;
12139 ++i;
12140 }
12141 names.detachTo(ComSafeArrayOutArg(aNames));
12142 values.detachTo(ComSafeArrayOutArg(aValues));
12143 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
12144 flags.detachTo(ComSafeArrayOutArg(aFlags));
12145 return S_OK;
12146#else
12147 ReturnComNotImplemented();
12148#endif
12149}
12150
12151STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
12152 IN_BSTR aValue,
12153 LONG64 aTimestamp,
12154 IN_BSTR aFlags)
12155{
12156 LogFlowThisFunc(("\n"));
12157
12158#ifdef VBOX_WITH_GUEST_PROPS
12159 using namespace guestProp;
12160
12161 CheckComArgStrNotEmptyOrNull(aName);
12162 CheckComArgMaybeNull(aValue);
12163 CheckComArgMaybeNull(aFlags);
12164
12165 try
12166 {
12167 /*
12168 * Convert input up front.
12169 */
12170 Utf8Str utf8Name(aName);
12171 uint32_t fFlags = NILFLAG;
12172 if (aFlags)
12173 {
12174 Utf8Str utf8Flags(aFlags);
12175 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
12176 AssertRCReturn(vrc, E_INVALIDARG);
12177 }
12178
12179 /*
12180 * Now grab the object lock, validate the state and do the update.
12181 */
12182 AutoCaller autoCaller(this);
12183 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12184
12185 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12186
12187 switch (mData->mMachineState)
12188 {
12189 case MachineState_Paused:
12190 case MachineState_Running:
12191 case MachineState_Teleporting:
12192 case MachineState_TeleportingPausedVM:
12193 case MachineState_LiveSnapshotting:
12194 case MachineState_DeletingSnapshotOnline:
12195 case MachineState_DeletingSnapshotPaused:
12196 case MachineState_Saving:
12197 break;
12198
12199 default:
12200#ifndef DEBUG_sunlover
12201 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
12202 VBOX_E_INVALID_VM_STATE);
12203#else
12204 return VBOX_E_INVALID_VM_STATE;
12205#endif
12206 }
12207
12208 setModified(IsModified_MachineData);
12209 mHWData.backup();
12210
12211 /** @todo r=bird: The careful memory handling doesn't work out here because
12212 * the catch block won't undo any damage we've done. So, if push_back throws
12213 * bad_alloc then you've lost the value.
12214 *
12215 * Another thing. Doing a linear search here isn't extremely efficient, esp.
12216 * since values that changes actually bubbles to the end of the list. Using
12217 * something that has an efficient lookup and can tolerate a bit of updates
12218 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
12219 * combination of RTStrCache (for sharing names and getting uniqueness into
12220 * the bargain) and hash/tree is another. */
12221 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
12222 iter != mHWData->mGuestProperties.end();
12223 ++iter)
12224 if (utf8Name == iter->strName)
12225 {
12226 mHWData->mGuestProperties.erase(iter);
12227 mData->mGuestPropertiesModified = TRUE;
12228 break;
12229 }
12230 if (aValue != NULL)
12231 {
12232 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
12233 mHWData->mGuestProperties.push_back(property);
12234 mData->mGuestPropertiesModified = TRUE;
12235 }
12236
12237 /*
12238 * Send a callback notification if appropriate
12239 */
12240 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
12241 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
12242 RTSTR_MAX,
12243 utf8Name.c_str(),
12244 RTSTR_MAX, NULL)
12245 )
12246 {
12247 alock.leave();
12248
12249 mParent->onGuestPropertyChange(mData->mUuid,
12250 aName,
12251 aValue,
12252 aFlags);
12253 }
12254 }
12255 catch (...)
12256 {
12257 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
12258 }
12259 return S_OK;
12260#else
12261 ReturnComNotImplemented();
12262#endif
12263}
12264
12265// public methods only for internal purposes
12266/////////////////////////////////////////////////////////////////////////////
12267
12268/**
12269 * Called from the client watcher thread to check for expected or unexpected
12270 * death of the client process that has a direct session to this machine.
12271 *
12272 * On Win32 and on OS/2, this method is called only when we've got the
12273 * mutex (i.e. the client has either died or terminated normally) so it always
12274 * returns @c true (the client is terminated, the session machine is
12275 * uninitialized).
12276 *
12277 * On other platforms, the method returns @c true if the client process has
12278 * terminated normally or abnormally and the session machine was uninitialized,
12279 * and @c false if the client process is still alive.
12280 *
12281 * @note Locks this object for writing.
12282 */
12283bool SessionMachine::checkForDeath()
12284{
12285 Uninit::Reason reason;
12286 bool terminated = false;
12287
12288 /* Enclose autoCaller with a block because calling uninit() from under it
12289 * will deadlock. */
12290 {
12291 AutoCaller autoCaller(this);
12292 if (!autoCaller.isOk())
12293 {
12294 /* return true if not ready, to cause the client watcher to exclude
12295 * the corresponding session from watching */
12296 LogFlowThisFunc(("Already uninitialized!\n"));
12297 return true;
12298 }
12299
12300 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12301
12302 /* Determine the reason of death: if the session state is Closing here,
12303 * everything is fine. Otherwise it means that the client did not call
12304 * OnSessionEnd() before it released the IPC semaphore. This may happen
12305 * either because the client process has abnormally terminated, or
12306 * because it simply forgot to call ISession::Close() before exiting. We
12307 * threat the latter also as an abnormal termination (see
12308 * Session::uninit() for details). */
12309 reason = mData->mSession.mState == SessionState_Unlocking ?
12310 Uninit::Normal :
12311 Uninit::Abnormal;
12312
12313#if defined(RT_OS_WINDOWS)
12314
12315 AssertMsg(mIPCSem, ("semaphore must be created"));
12316
12317 /* release the IPC mutex */
12318 ::ReleaseMutex(mIPCSem);
12319
12320 terminated = true;
12321
12322#elif defined(RT_OS_OS2)
12323
12324 AssertMsg(mIPCSem, ("semaphore must be created"));
12325
12326 /* release the IPC mutex */
12327 ::DosReleaseMutexSem(mIPCSem);
12328
12329 terminated = true;
12330
12331#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
12332
12333 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
12334
12335 int val = ::semctl(mIPCSem, 0, GETVAL);
12336 if (val > 0)
12337 {
12338 /* the semaphore is signaled, meaning the session is terminated */
12339 terminated = true;
12340 }
12341
12342#else
12343# error "Port me!"
12344#endif
12345
12346 } /* AutoCaller block */
12347
12348 if (terminated)
12349 uninit(reason);
12350
12351 return terminated;
12352}
12353
12354/**
12355 * @note Locks this object for reading.
12356 */
12357HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
12358{
12359 LogFlowThisFunc(("\n"));
12360
12361 AutoCaller autoCaller(this);
12362 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12363
12364 ComPtr<IInternalSessionControl> directControl;
12365 {
12366 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12367 directControl = mData->mSession.mDirectControl;
12368 }
12369
12370 /* ignore notifications sent after #OnSessionEnd() is called */
12371 if (!directControl)
12372 return S_OK;
12373
12374 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
12375}
12376
12377/**
12378 * @note Locks this object for reading.
12379 */
12380HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
12381 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
12382{
12383 LogFlowThisFunc(("\n"));
12384
12385 AutoCaller autoCaller(this);
12386 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12387
12388 ComPtr<IInternalSessionControl> directControl;
12389 {
12390 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12391 directControl = mData->mSession.mDirectControl;
12392 }
12393
12394 /* ignore notifications sent after #OnSessionEnd() is called */
12395 if (!directControl)
12396 return S_OK;
12397 /*
12398 * instead acting like callback we ask IVirtualBox deliver corresponding event
12399 */
12400
12401 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
12402 return S_OK;
12403}
12404
12405/**
12406 * @note Locks this object for reading.
12407 */
12408HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
12409{
12410 LogFlowThisFunc(("\n"));
12411
12412 AutoCaller autoCaller(this);
12413 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12414
12415 ComPtr<IInternalSessionControl> directControl;
12416 {
12417 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12418 directControl = mData->mSession.mDirectControl;
12419 }
12420
12421 /* ignore notifications sent after #OnSessionEnd() is called */
12422 if (!directControl)
12423 return S_OK;
12424
12425 return directControl->OnSerialPortChange(serialPort);
12426}
12427
12428/**
12429 * @note Locks this object for reading.
12430 */
12431HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
12432{
12433 LogFlowThisFunc(("\n"));
12434
12435 AutoCaller autoCaller(this);
12436 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12437
12438 ComPtr<IInternalSessionControl> directControl;
12439 {
12440 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12441 directControl = mData->mSession.mDirectControl;
12442 }
12443
12444 /* ignore notifications sent after #OnSessionEnd() is called */
12445 if (!directControl)
12446 return S_OK;
12447
12448 return directControl->OnParallelPortChange(parallelPort);
12449}
12450
12451/**
12452 * @note Locks this object for reading.
12453 */
12454HRESULT SessionMachine::onStorageControllerChange()
12455{
12456 LogFlowThisFunc(("\n"));
12457
12458 AutoCaller autoCaller(this);
12459 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12460
12461 ComPtr<IInternalSessionControl> directControl;
12462 {
12463 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12464 directControl = mData->mSession.mDirectControl;
12465 }
12466
12467 /* ignore notifications sent after #OnSessionEnd() is called */
12468 if (!directControl)
12469 return S_OK;
12470
12471 return directControl->OnStorageControllerChange();
12472}
12473
12474/**
12475 * @note Locks this object for reading.
12476 */
12477HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
12478{
12479 LogFlowThisFunc(("\n"));
12480
12481 AutoCaller autoCaller(this);
12482 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12483
12484 ComPtr<IInternalSessionControl> directControl;
12485 {
12486 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12487 directControl = mData->mSession.mDirectControl;
12488 }
12489
12490 /* ignore notifications sent after #OnSessionEnd() is called */
12491 if (!directControl)
12492 return S_OK;
12493
12494 return directControl->OnMediumChange(aAttachment, aForce);
12495}
12496
12497/**
12498 * @note Locks this object for reading.
12499 */
12500HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
12501{
12502 LogFlowThisFunc(("\n"));
12503
12504 AutoCaller autoCaller(this);
12505 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12506
12507 ComPtr<IInternalSessionControl> directControl;
12508 {
12509 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12510 directControl = mData->mSession.mDirectControl;
12511 }
12512
12513 /* ignore notifications sent after #OnSessionEnd() is called */
12514 if (!directControl)
12515 return S_OK;
12516
12517 return directControl->OnCPUChange(aCPU, aRemove);
12518}
12519
12520HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
12521{
12522 LogFlowThisFunc(("\n"));
12523
12524 AutoCaller autoCaller(this);
12525 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12526
12527 ComPtr<IInternalSessionControl> directControl;
12528 {
12529 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12530 directControl = mData->mSession.mDirectControl;
12531 }
12532
12533 /* ignore notifications sent after #OnSessionEnd() is called */
12534 if (!directControl)
12535 return S_OK;
12536
12537 return directControl->OnCPUExecutionCapChange(aExecutionCap);
12538}
12539
12540/**
12541 * @note Locks this object for reading.
12542 */
12543HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
12544{
12545 LogFlowThisFunc(("\n"));
12546
12547 AutoCaller autoCaller(this);
12548 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12549
12550 ComPtr<IInternalSessionControl> directControl;
12551 {
12552 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12553 directControl = mData->mSession.mDirectControl;
12554 }
12555
12556 /* ignore notifications sent after #OnSessionEnd() is called */
12557 if (!directControl)
12558 return S_OK;
12559
12560 return directControl->OnVRDEServerChange(aRestart);
12561}
12562
12563/**
12564 * @note Locks this object for reading.
12565 */
12566HRESULT SessionMachine::onUSBControllerChange()
12567{
12568 LogFlowThisFunc(("\n"));
12569
12570 AutoCaller autoCaller(this);
12571 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12572
12573 ComPtr<IInternalSessionControl> directControl;
12574 {
12575 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12576 directControl = mData->mSession.mDirectControl;
12577 }
12578
12579 /* ignore notifications sent after #OnSessionEnd() is called */
12580 if (!directControl)
12581 return S_OK;
12582
12583 return directControl->OnUSBControllerChange();
12584}
12585
12586/**
12587 * @note Locks this object for reading.
12588 */
12589HRESULT SessionMachine::onSharedFolderChange()
12590{
12591 LogFlowThisFunc(("\n"));
12592
12593 AutoCaller autoCaller(this);
12594 AssertComRCReturnRC(autoCaller.rc());
12595
12596 ComPtr<IInternalSessionControl> directControl;
12597 {
12598 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12599 directControl = mData->mSession.mDirectControl;
12600 }
12601
12602 /* ignore notifications sent after #OnSessionEnd() is called */
12603 if (!directControl)
12604 return S_OK;
12605
12606 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
12607}
12608
12609/**
12610 * @note Locks this object for reading.
12611 */
12612HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
12613{
12614 LogFlowThisFunc(("\n"));
12615
12616 AutoCaller autoCaller(this);
12617 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12618
12619 ComPtr<IInternalSessionControl> directControl;
12620 {
12621 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12622 directControl = mData->mSession.mDirectControl;
12623 }
12624
12625 /* ignore notifications sent after #OnSessionEnd() is called */
12626 if (!directControl)
12627 return S_OK;
12628
12629 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
12630}
12631
12632/**
12633 * @note Locks this object for reading.
12634 */
12635HRESULT SessionMachine::onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove)
12636{
12637 LogFlowThisFunc(("\n"));
12638
12639 AutoCaller autoCaller(this);
12640 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12641
12642 ComPtr<IInternalSessionControl> directControl;
12643 {
12644 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12645 directControl = mData->mSession.mDirectControl;
12646 }
12647
12648 /* ignore notifications sent after #OnSessionEnd() is called */
12649 if (!directControl)
12650 return S_OK;
12651
12652 return directControl->OnStorageDeviceChange(aAttachment, aRemove);
12653}
12654
12655/**
12656 * Returns @c true if this machine's USB controller reports it has a matching
12657 * filter for the given USB device and @c false otherwise.
12658 *
12659 * @note Caller must have requested machine read lock.
12660 */
12661bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
12662{
12663 AutoCaller autoCaller(this);
12664 /* silently return if not ready -- this method may be called after the
12665 * direct machine session has been called */
12666 if (!autoCaller.isOk())
12667 return false;
12668
12669
12670#ifdef VBOX_WITH_USB
12671 switch (mData->mMachineState)
12672 {
12673 case MachineState_Starting:
12674 case MachineState_Restoring:
12675 case MachineState_TeleportingIn:
12676 case MachineState_Paused:
12677 case MachineState_Running:
12678 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
12679 * elsewhere... */
12680 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
12681 default: break;
12682 }
12683#else
12684 NOREF(aDevice);
12685 NOREF(aMaskedIfs);
12686#endif
12687 return false;
12688}
12689
12690/**
12691 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12692 */
12693HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
12694 IVirtualBoxErrorInfo *aError,
12695 ULONG aMaskedIfs)
12696{
12697 LogFlowThisFunc(("\n"));
12698
12699 AutoCaller autoCaller(this);
12700
12701 /* This notification may happen after the machine object has been
12702 * uninitialized (the session was closed), so don't assert. */
12703 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12704
12705 ComPtr<IInternalSessionControl> directControl;
12706 {
12707 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12708 directControl = mData->mSession.mDirectControl;
12709 }
12710
12711 /* fail on notifications sent after #OnSessionEnd() is called, it is
12712 * expected by the caller */
12713 if (!directControl)
12714 return E_FAIL;
12715
12716 /* No locks should be held at this point. */
12717 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12718 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12719
12720 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
12721}
12722
12723/**
12724 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12725 */
12726HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
12727 IVirtualBoxErrorInfo *aError)
12728{
12729 LogFlowThisFunc(("\n"));
12730
12731 AutoCaller autoCaller(this);
12732
12733 /* This notification may happen after the machine object has been
12734 * uninitialized (the session was closed), so don't assert. */
12735 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12736
12737 ComPtr<IInternalSessionControl> directControl;
12738 {
12739 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12740 directControl = mData->mSession.mDirectControl;
12741 }
12742
12743 /* fail on notifications sent after #OnSessionEnd() is called, it is
12744 * expected by the caller */
12745 if (!directControl)
12746 return E_FAIL;
12747
12748 /* No locks should be held at this point. */
12749 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12750 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12751
12752 return directControl->OnUSBDeviceDetach(aId, aError);
12753}
12754
12755// protected methods
12756/////////////////////////////////////////////////////////////////////////////
12757
12758/**
12759 * Helper method to finalize saving the state.
12760 *
12761 * @note Must be called from under this object's lock.
12762 *
12763 * @param aRc S_OK if the snapshot has been taken successfully
12764 * @param aErrMsg human readable error message for failure
12765 *
12766 * @note Locks mParent + this objects for writing.
12767 */
12768HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
12769{
12770 LogFlowThisFuncEnter();
12771
12772 AutoCaller autoCaller(this);
12773 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12774
12775 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12776
12777 HRESULT rc = S_OK;
12778
12779 if (SUCCEEDED(aRc))
12780 {
12781 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
12782
12783 /* save all VM settings */
12784 rc = saveSettings(NULL);
12785 // no need to check whether VirtualBox.xml needs saving also since
12786 // we can't have a name change pending at this point
12787 }
12788 else
12789 {
12790 // delete the saved state file (it might have been already created);
12791 // we need not check whether this is shared with a snapshot here because
12792 // we certainly created this saved state file here anew
12793 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
12794 }
12795
12796 /* notify the progress object about operation completion */
12797 Assert(mConsoleTaskData.mProgress);
12798 if (SUCCEEDED(aRc))
12799 mConsoleTaskData.mProgress->notifyComplete(S_OK);
12800 else
12801 {
12802 if (aErrMsg.length())
12803 mConsoleTaskData.mProgress->notifyComplete(aRc,
12804 COM_IIDOF(ISession),
12805 getComponentName(),
12806 aErrMsg.c_str());
12807 else
12808 mConsoleTaskData.mProgress->notifyComplete(aRc);
12809 }
12810
12811 /* clear out the temporary saved state data */
12812 mConsoleTaskData.mLastState = MachineState_Null;
12813 mConsoleTaskData.strStateFilePath.setNull();
12814 mConsoleTaskData.mProgress.setNull();
12815
12816 LogFlowThisFuncLeave();
12817 return rc;
12818}
12819
12820/**
12821 * Deletes the given file if it is no longer in use by either the current machine state
12822 * (if the machine is "saved") or any of the machine's snapshots.
12823 *
12824 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
12825 * but is different for each SnapshotMachine. When calling this, the order of calling this
12826 * function on the one hand and changing that variable OR the snapshots tree on the other hand
12827 * is therefore critical. I know, it's all rather messy.
12828 *
12829 * @param strStateFile
12830 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
12831 */
12832void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
12833 Snapshot *pSnapshotToIgnore)
12834{
12835 // it is safe to delete this saved state file if it is not currently in use by the machine ...
12836 if ( (strStateFile.isNotEmpty())
12837 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
12838 )
12839 // ... and it must also not be shared with other snapshots
12840 if ( !mData->mFirstSnapshot
12841 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
12842 // this checks the SnapshotMachine's state file paths
12843 )
12844 RTFileDelete(strStateFile.c_str());
12845}
12846
12847/**
12848 * Locks the attached media.
12849 *
12850 * All attached hard disks are locked for writing and DVD/floppy are locked for
12851 * reading. Parents of attached hard disks (if any) are locked for reading.
12852 *
12853 * This method also performs accessibility check of all media it locks: if some
12854 * media is inaccessible, the method will return a failure and a bunch of
12855 * extended error info objects per each inaccessible medium.
12856 *
12857 * Note that this method is atomic: if it returns a success, all media are
12858 * locked as described above; on failure no media is locked at all (all
12859 * succeeded individual locks will be undone).
12860 *
12861 * This method is intended to be called when the machine is in Starting or
12862 * Restoring state and asserts otherwise.
12863 *
12864 * The locks made by this method must be undone by calling #unlockMedia() when
12865 * no more needed.
12866 */
12867HRESULT SessionMachine::lockMedia()
12868{
12869 AutoCaller autoCaller(this);
12870 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12871
12872 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12873
12874 AssertReturn( mData->mMachineState == MachineState_Starting
12875 || mData->mMachineState == MachineState_Restoring
12876 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
12877 /* bail out if trying to lock things with already set up locking */
12878 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
12879
12880 clearError();
12881 MultiResult mrc(S_OK);
12882
12883 /* Collect locking information for all medium objects attached to the VM. */
12884 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
12885 it != mMediaData->mAttachments.end();
12886 ++it)
12887 {
12888 MediumAttachment* pAtt = *it;
12889 DeviceType_T devType = pAtt->getType();
12890 Medium *pMedium = pAtt->getMedium();
12891
12892 MediumLockList *pMediumLockList(new MediumLockList());
12893 // There can be attachments without a medium (floppy/dvd), and thus
12894 // it's impossible to create a medium lock list. It still makes sense
12895 // to have the empty medium lock list in the map in case a medium is
12896 // attached later.
12897 if (pMedium != NULL)
12898 {
12899 MediumType_T mediumType = pMedium->getType();
12900 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
12901 || mediumType == MediumType_Shareable;
12902 bool fIsVitalImage = (devType == DeviceType_HardDisk);
12903
12904 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
12905 !fIsReadOnlyLock /* fMediumLockWrite */,
12906 NULL,
12907 *pMediumLockList);
12908 if (FAILED(mrc))
12909 {
12910 delete pMediumLockList;
12911 mData->mSession.mLockedMedia.Clear();
12912 break;
12913 }
12914 }
12915
12916 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
12917 if (FAILED(rc))
12918 {
12919 mData->mSession.mLockedMedia.Clear();
12920 mrc = setError(rc,
12921 tr("Collecting locking information for all attached media failed"));
12922 break;
12923 }
12924 }
12925
12926 if (SUCCEEDED(mrc))
12927 {
12928 /* Now lock all media. If this fails, nothing is locked. */
12929 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12930 if (FAILED(rc))
12931 {
12932 mrc = setError(rc,
12933 tr("Locking of attached media failed"));
12934 }
12935 }
12936
12937 return mrc;
12938}
12939
12940/**
12941 * Undoes the locks made by by #lockMedia().
12942 */
12943void SessionMachine::unlockMedia()
12944{
12945 AutoCaller autoCaller(this);
12946 AssertComRCReturnVoid(autoCaller.rc());
12947
12948 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12949
12950 /* we may be holding important error info on the current thread;
12951 * preserve it */
12952 ErrorInfoKeeper eik;
12953
12954 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12955 AssertComRC(rc);
12956}
12957
12958/**
12959 * Helper to change the machine state (reimplementation).
12960 *
12961 * @note Locks this object for writing.
12962 */
12963HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12964{
12965 LogFlowThisFuncEnter();
12966 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12967
12968 AutoCaller autoCaller(this);
12969 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12970
12971 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12972
12973 MachineState_T oldMachineState = mData->mMachineState;
12974
12975 AssertMsgReturn(oldMachineState != aMachineState,
12976 ("oldMachineState=%s, aMachineState=%s\n",
12977 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12978 E_FAIL);
12979
12980 HRESULT rc = S_OK;
12981
12982 int stsFlags = 0;
12983 bool deleteSavedState = false;
12984
12985 /* detect some state transitions */
12986
12987 if ( ( oldMachineState == MachineState_Saved
12988 && aMachineState == MachineState_Restoring)
12989 || ( ( oldMachineState == MachineState_PoweredOff
12990 || oldMachineState == MachineState_Teleported
12991 || oldMachineState == MachineState_Aborted
12992 )
12993 && ( aMachineState == MachineState_TeleportingIn
12994 || aMachineState == MachineState_Starting
12995 )
12996 )
12997 )
12998 {
12999 /* The EMT thread is about to start */
13000
13001 /* Nothing to do here for now... */
13002
13003 /// @todo NEWMEDIA don't let mDVDDrive and other children
13004 /// change anything when in the Starting/Restoring state
13005 }
13006 else if ( ( oldMachineState == MachineState_Running
13007 || oldMachineState == MachineState_Paused
13008 || oldMachineState == MachineState_Teleporting
13009 || oldMachineState == MachineState_LiveSnapshotting
13010 || oldMachineState == MachineState_Stuck
13011 || oldMachineState == MachineState_Starting
13012 || oldMachineState == MachineState_Stopping
13013 || oldMachineState == MachineState_Saving
13014 || oldMachineState == MachineState_Restoring
13015 || oldMachineState == MachineState_TeleportingPausedVM
13016 || oldMachineState == MachineState_TeleportingIn
13017 )
13018 && ( aMachineState == MachineState_PoweredOff
13019 || aMachineState == MachineState_Saved
13020 || aMachineState == MachineState_Teleported
13021 || aMachineState == MachineState_Aborted
13022 )
13023 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
13024 * snapshot */
13025 && ( mConsoleTaskData.mSnapshot.isNull()
13026 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
13027 )
13028 )
13029 {
13030 /* The EMT thread has just stopped, unlock attached media. Note that as
13031 * opposed to locking that is done from Console, we do unlocking here
13032 * because the VM process may have aborted before having a chance to
13033 * properly unlock all media it locked. */
13034
13035 unlockMedia();
13036 }
13037
13038 if (oldMachineState == MachineState_Restoring)
13039 {
13040 if (aMachineState != MachineState_Saved)
13041 {
13042 /*
13043 * delete the saved state file once the machine has finished
13044 * restoring from it (note that Console sets the state from
13045 * Restoring to Saved if the VM couldn't restore successfully,
13046 * to give the user an ability to fix an error and retry --
13047 * we keep the saved state file in this case)
13048 */
13049 deleteSavedState = true;
13050 }
13051 }
13052 else if ( oldMachineState == MachineState_Saved
13053 && ( aMachineState == MachineState_PoweredOff
13054 || aMachineState == MachineState_Aborted
13055 || aMachineState == MachineState_Teleported
13056 )
13057 )
13058 {
13059 /*
13060 * delete the saved state after Console::ForgetSavedState() is called
13061 * or if the VM process (owning a direct VM session) crashed while the
13062 * VM was Saved
13063 */
13064
13065 /// @todo (dmik)
13066 // Not sure that deleting the saved state file just because of the
13067 // client death before it attempted to restore the VM is a good
13068 // thing. But when it crashes we need to go to the Aborted state
13069 // which cannot have the saved state file associated... The only
13070 // way to fix this is to make the Aborted condition not a VM state
13071 // but a bool flag: i.e., when a crash occurs, set it to true and
13072 // change the state to PoweredOff or Saved depending on the
13073 // saved state presence.
13074
13075 deleteSavedState = true;
13076 mData->mCurrentStateModified = TRUE;
13077 stsFlags |= SaveSTS_CurStateModified;
13078 }
13079
13080 if ( aMachineState == MachineState_Starting
13081 || aMachineState == MachineState_Restoring
13082 || aMachineState == MachineState_TeleportingIn
13083 )
13084 {
13085 /* set the current state modified flag to indicate that the current
13086 * state is no more identical to the state in the
13087 * current snapshot */
13088 if (!mData->mCurrentSnapshot.isNull())
13089 {
13090 mData->mCurrentStateModified = TRUE;
13091 stsFlags |= SaveSTS_CurStateModified;
13092 }
13093 }
13094
13095 if (deleteSavedState)
13096 {
13097 if (mRemoveSavedState)
13098 {
13099 Assert(!mSSData->strStateFilePath.isEmpty());
13100
13101 // it is safe to delete the saved state file if ...
13102 if ( !mData->mFirstSnapshot // ... we have no snapshots or
13103 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
13104 // ... none of the snapshots share the saved state file
13105 )
13106 RTFileDelete(mSSData->strStateFilePath.c_str());
13107 }
13108
13109 mSSData->strStateFilePath.setNull();
13110 stsFlags |= SaveSTS_StateFilePath;
13111 }
13112
13113 /* redirect to the underlying peer machine */
13114 mPeer->setMachineState(aMachineState);
13115
13116 if ( aMachineState == MachineState_PoweredOff
13117 || aMachineState == MachineState_Teleported
13118 || aMachineState == MachineState_Aborted
13119 || aMachineState == MachineState_Saved)
13120 {
13121 /* the machine has stopped execution
13122 * (or the saved state file was adopted) */
13123 stsFlags |= SaveSTS_StateTimeStamp;
13124 }
13125
13126 if ( ( oldMachineState == MachineState_PoweredOff
13127 || oldMachineState == MachineState_Aborted
13128 || oldMachineState == MachineState_Teleported
13129 )
13130 && aMachineState == MachineState_Saved)
13131 {
13132 /* the saved state file was adopted */
13133 Assert(!mSSData->strStateFilePath.isEmpty());
13134 stsFlags |= SaveSTS_StateFilePath;
13135 }
13136
13137#ifdef VBOX_WITH_GUEST_PROPS
13138 if ( aMachineState == MachineState_PoweredOff
13139 || aMachineState == MachineState_Aborted
13140 || aMachineState == MachineState_Teleported)
13141 {
13142 /* Make sure any transient guest properties get removed from the
13143 * property store on shutdown. */
13144
13145 HWData::GuestPropertyList::iterator it;
13146 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
13147 if (!fNeedsSaving)
13148 for (it = mHWData->mGuestProperties.begin();
13149 it != mHWData->mGuestProperties.end(); ++it)
13150 if ( (it->mFlags & guestProp::TRANSIENT)
13151 || (it->mFlags & guestProp::TRANSRESET))
13152 {
13153 fNeedsSaving = true;
13154 break;
13155 }
13156 if (fNeedsSaving)
13157 {
13158 mData->mCurrentStateModified = TRUE;
13159 stsFlags |= SaveSTS_CurStateModified;
13160 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
13161 }
13162 }
13163#endif
13164
13165 rc = saveStateSettings(stsFlags);
13166
13167 if ( ( oldMachineState != MachineState_PoweredOff
13168 && oldMachineState != MachineState_Aborted
13169 && oldMachineState != MachineState_Teleported
13170 )
13171 && ( aMachineState == MachineState_PoweredOff
13172 || aMachineState == MachineState_Aborted
13173 || aMachineState == MachineState_Teleported
13174 )
13175 )
13176 {
13177 /* we've been shut down for any reason */
13178 /* no special action so far */
13179 }
13180
13181 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
13182 LogFlowThisFuncLeave();
13183 return rc;
13184}
13185
13186/**
13187 * Sends the current machine state value to the VM process.
13188 *
13189 * @note Locks this object for reading, then calls a client process.
13190 */
13191HRESULT SessionMachine::updateMachineStateOnClient()
13192{
13193 AutoCaller autoCaller(this);
13194 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
13195
13196 ComPtr<IInternalSessionControl> directControl;
13197 {
13198 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
13199 AssertReturn(!!mData, E_FAIL);
13200 directControl = mData->mSession.mDirectControl;
13201
13202 /* directControl may be already set to NULL here in #OnSessionEnd()
13203 * called too early by the direct session process while there is still
13204 * some operation (like deleting the snapshot) in progress. The client
13205 * process in this case is waiting inside Session::close() for the
13206 * "end session" process object to complete, while #uninit() called by
13207 * #checkForDeath() on the Watcher thread is waiting for the pending
13208 * operation to complete. For now, we accept this inconsistent behavior
13209 * and simply do nothing here. */
13210
13211 if (mData->mSession.mState == SessionState_Unlocking)
13212 return S_OK;
13213
13214 AssertReturn(!directControl.isNull(), E_FAIL);
13215 }
13216
13217 return directControl->UpdateMachineState(mData->mMachineState);
13218}
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