VirtualBox

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

Last change on this file since 38533 was 38499, checked in by vboxsync, 13 years ago

Main/Machine+Medium: fix medium registry association when attaching a device or mounting a medium, when there is a chain of parent images which are not associated with any media registry, including the necessary locking adjustments

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette