VirtualBox

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

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

warning

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