VirtualBox

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

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

Main: fix VM initialization if a shared folder does not exists (fix OVF import/vbox addition of other hosts)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 428.2 KB
Line 
1/* $Id: MachineImpl.cpp 38494 2011-08-19 09:01:48Z 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 addMediumToRegistry(medium, llRegistriesThatNeedSaving, &uuidRegistryParent);
3736 }
3737 rc = diff->init(mParent,
3738 medium->getPreferredDiffFormat(),
3739 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
3740 uuidRegistryParent,
3741 &llRegistriesThatNeedSaving);
3742 if (FAILED(rc)) return rc;
3743
3744 /* Apply the normal locking logic to the entire chain. */
3745 MediumLockList *pMediumLockList(new MediumLockList());
3746 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
3747 true /* fMediumLockWrite */,
3748 medium,
3749 *pMediumLockList);
3750 if (SUCCEEDED(rc))
3751 {
3752 rc = pMediumLockList->Lock();
3753 if (FAILED(rc))
3754 setError(rc,
3755 tr("Could not lock medium when creating diff '%s'"),
3756 diff->getLocationFull().c_str());
3757 else
3758 {
3759 /* will leave the lock before the potentially lengthy operation, so
3760 * protect with the special state */
3761 MachineState_T oldState = mData->mMachineState;
3762 setMachineState(MachineState_SettingUp);
3763
3764 mediumLock.leave();
3765 treeLock.leave();
3766 alock.leave();
3767
3768 rc = medium->createDiffStorage(diff,
3769 MediumVariant_Standard,
3770 pMediumLockList,
3771 NULL /* aProgress */,
3772 true /* aWait */,
3773 &llRegistriesThatNeedSaving);
3774
3775 alock.enter();
3776 treeLock.enter();
3777 mediumLock.enter();
3778
3779 setMachineState(oldState);
3780 }
3781 }
3782
3783 /* Unlock the media and free the associated memory. */
3784 delete pMediumLockList;
3785
3786 if (FAILED(rc)) return rc;
3787
3788 /* use the created diff for the actual attachment */
3789 medium = diff;
3790 mediumCaller.attach(medium);
3791 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3792 mediumLock.attach(medium);
3793 }
3794 while (0);
3795
3796 ComObjPtr<MediumAttachment> attachment;
3797 attachment.createObject();
3798 rc = attachment->init(this,
3799 medium,
3800 aControllerName,
3801 aControllerPort,
3802 aDevice,
3803 aType,
3804 fIndirect,
3805 false /* fPassthrough */,
3806 false /* fTempEject */,
3807 false /* fNonRotational */,
3808 Utf8Str::Empty);
3809 if (FAILED(rc)) return rc;
3810
3811 if (associate && !medium.isNull())
3812 {
3813 // as the last step, associate the medium to the VM
3814 rc = medium->addBackReference(mData->mUuid);
3815 // here we can fail because of Deleting, or being in process of creating a Diff
3816 if (FAILED(rc)) return rc;
3817
3818 addMediumToRegistry(medium,
3819 llRegistriesThatNeedSaving,
3820 NULL /* Guid *puuid */);
3821 }
3822
3823 /* success: finally remember the attachment */
3824 setModified(IsModified_Storage);
3825 mMediaData.backup();
3826 mMediaData->mAttachments.push_back(attachment);
3827
3828 mediumLock.release();
3829 treeLock.leave();
3830 alock.release();
3831
3832 if (fHotplug)
3833 rc = onStorageDeviceChange(attachment, FALSE /* aRemove */);
3834
3835 mParent->saveRegistries(llRegistriesThatNeedSaving);
3836
3837 return rc;
3838}
3839
3840STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
3841 LONG aDevice)
3842{
3843 CheckComArgStrNotEmptyOrNull(aControllerName);
3844
3845 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
3846 aControllerName, aControllerPort, aDevice));
3847
3848 AutoCaller autoCaller(this);
3849 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3850
3851 GuidList llRegistriesThatNeedSaving;
3852
3853 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3854
3855 HRESULT rc = checkStateDependency(MutableStateDep);
3856 if (FAILED(rc)) return rc;
3857
3858 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3859
3860 /* Check for an existing controller. */
3861 ComObjPtr<StorageController> ctl;
3862 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
3863 if (FAILED(rc)) return rc;
3864
3865 StorageControllerType_T ctrlType;
3866 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
3867 if (FAILED(rc))
3868 return setError(E_FAIL,
3869 tr("Could not get type of controller '%ls'"),
3870 aControllerName);
3871
3872 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
3873 bool fHotplug = false;
3874 if (Global::IsOnlineOrTransient(mData->mMachineState))
3875 fHotplug = true;
3876
3877 if (fHotplug && !isControllerHotplugCapable(ctrlType))
3878 return setError(VBOX_E_INVALID_VM_STATE,
3879 tr("Controller '%ls' does not support hotplugging"),
3880 aControllerName);
3881
3882 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3883 aControllerName,
3884 aControllerPort,
3885 aDevice);
3886 if (!pAttach)
3887 return setError(VBOX_E_OBJECT_NOT_FOUND,
3888 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3889 aDevice, aControllerPort, aControllerName);
3890
3891 /*
3892 * The VM has to detach the device before we delete any implicit diffs.
3893 * If this fails we can roll back without loosing data.
3894 */
3895 if (fHotplug)
3896 {
3897 alock.leave();
3898 rc = onStorageDeviceChange(pAttach, TRUE /* aRemove */);
3899 alock.enter();
3900 }
3901 if (FAILED(rc)) return rc;
3902
3903 /* If we are here everything went well and we can delete the implicit now. */
3904 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */, &llRegistriesThatNeedSaving);
3905
3906 alock.release();
3907
3908 if (SUCCEEDED(rc))
3909 rc = mParent->saveRegistries(llRegistriesThatNeedSaving);
3910
3911 return rc;
3912}
3913
3914STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
3915 LONG aDevice, BOOL aPassthrough)
3916{
3917 CheckComArgStrNotEmptyOrNull(aControllerName);
3918
3919 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aPassthrough=%d\n",
3920 aControllerName, aControllerPort, aDevice, aPassthrough));
3921
3922 AutoCaller autoCaller(this);
3923 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3924
3925 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3926
3927 HRESULT rc = checkStateDependency(MutableStateDep);
3928 if (FAILED(rc)) return rc;
3929
3930 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3931
3932 if (Global::IsOnlineOrTransient(mData->mMachineState))
3933 return setError(VBOX_E_INVALID_VM_STATE,
3934 tr("Invalid machine state: %s"),
3935 Global::stringifyMachineState(mData->mMachineState));
3936
3937 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3938 aControllerName,
3939 aControllerPort,
3940 aDevice);
3941 if (!pAttach)
3942 return setError(VBOX_E_OBJECT_NOT_FOUND,
3943 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3944 aDevice, aControllerPort, aControllerName);
3945
3946
3947 setModified(IsModified_Storage);
3948 mMediaData.backup();
3949
3950 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3951
3952 if (pAttach->getType() != DeviceType_DVD)
3953 return setError(E_INVALIDARG,
3954 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3955 aDevice, aControllerPort, aControllerName);
3956 pAttach->updatePassthrough(!!aPassthrough);
3957
3958 return S_OK;
3959}
3960
3961STDMETHODIMP Machine::TemporaryEjectDevice(IN_BSTR aControllerName, LONG aControllerPort,
3962 LONG aDevice, BOOL aTemporaryEject)
3963{
3964 CheckComArgStrNotEmptyOrNull(aControllerName);
3965
3966 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aTemporaryEject=%d\n",
3967 aControllerName, aControllerPort, aDevice, aTemporaryEject));
3968
3969 AutoCaller autoCaller(this);
3970 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3971
3972 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3973
3974 HRESULT rc = checkStateDependency(MutableStateDep);
3975 if (FAILED(rc)) return rc;
3976
3977 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3978 aControllerName,
3979 aControllerPort,
3980 aDevice);
3981 if (!pAttach)
3982 return setError(VBOX_E_OBJECT_NOT_FOUND,
3983 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3984 aDevice, aControllerPort, aControllerName);
3985
3986
3987 setModified(IsModified_Storage);
3988 mMediaData.backup();
3989
3990 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3991
3992 if (pAttach->getType() != DeviceType_DVD)
3993 return setError(E_INVALIDARG,
3994 tr("Setting temporary eject flag rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3995 aDevice, aControllerPort, aControllerName);
3996 pAttach->updateTempEject(!!aTemporaryEject);
3997
3998 return S_OK;
3999}
4000
4001STDMETHODIMP Machine::NonRotationalDevice(IN_BSTR aControllerName, LONG aControllerPort,
4002 LONG aDevice, BOOL aNonRotational)
4003{
4004 CheckComArgStrNotEmptyOrNull(aControllerName);
4005
4006 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aNonRotational=%d\n",
4007 aControllerName, aControllerPort, aDevice, aNonRotational));
4008
4009 AutoCaller autoCaller(this);
4010 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4011
4012 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4013
4014 HRESULT rc = checkStateDependency(MutableStateDep);
4015 if (FAILED(rc)) return rc;
4016
4017 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4018
4019 if (Global::IsOnlineOrTransient(mData->mMachineState))
4020 return setError(VBOX_E_INVALID_VM_STATE,
4021 tr("Invalid machine state: %s"),
4022 Global::stringifyMachineState(mData->mMachineState));
4023
4024 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4025 aControllerName,
4026 aControllerPort,
4027 aDevice);
4028 if (!pAttach)
4029 return setError(VBOX_E_OBJECT_NOT_FOUND,
4030 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4031 aDevice, aControllerPort, aControllerName);
4032
4033
4034 setModified(IsModified_Storage);
4035 mMediaData.backup();
4036
4037 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4038
4039 if (pAttach->getType() != DeviceType_HardDisk)
4040 return setError(E_INVALIDARG,
4041 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"),
4042 aDevice, aControllerPort, aControllerName);
4043 pAttach->updateNonRotational(!!aNonRotational);
4044
4045 return S_OK;
4046}
4047
4048STDMETHODIMP Machine::SetBandwidthGroupForDevice(IN_BSTR aControllerName, LONG aControllerPort,
4049 LONG aDevice, IBandwidthGroup *aBandwidthGroup)
4050{
4051 CheckComArgStrNotEmptyOrNull(aControllerName);
4052
4053 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4054 aControllerName, aControllerPort, aDevice));
4055
4056 AutoCaller autoCaller(this);
4057 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4058
4059 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4060
4061 HRESULT rc = checkStateDependency(MutableStateDep);
4062 if (FAILED(rc)) return rc;
4063
4064 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
4065
4066 if (Global::IsOnlineOrTransient(mData->mMachineState))
4067 return setError(VBOX_E_INVALID_VM_STATE,
4068 tr("Invalid machine state: %s"),
4069 Global::stringifyMachineState(mData->mMachineState));
4070
4071 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
4072 aControllerName,
4073 aControllerPort,
4074 aDevice);
4075 if (!pAttach)
4076 return setError(VBOX_E_OBJECT_NOT_FOUND,
4077 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4078 aDevice, aControllerPort, aControllerName);
4079
4080
4081 setModified(IsModified_Storage);
4082 mMediaData.backup();
4083
4084 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(aBandwidthGroup);
4085 if (aBandwidthGroup && group.isNull())
4086 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
4087
4088 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4089
4090 const Utf8Str strBandwidthGroupOld = pAttach->getBandwidthGroup();
4091 if (strBandwidthGroupOld.isNotEmpty())
4092 {
4093 /* Get the bandwidth group object and release it - this must not fail. */
4094 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
4095 rc = getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
4096 Assert(SUCCEEDED(rc));
4097
4098 pBandwidthGroupOld->release();
4099 pAttach->updateBandwidthGroup(Utf8Str::Empty);
4100 }
4101
4102 if (!group.isNull())
4103 {
4104 group->reference();
4105 pAttach->updateBandwidthGroup(group->getName());
4106 }
4107
4108 return S_OK;
4109}
4110
4111
4112STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
4113 LONG aControllerPort,
4114 LONG aDevice,
4115 IMedium *aMedium,
4116 BOOL aForce)
4117{
4118 int rc = S_OK;
4119 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aForce=%d\n",
4120 aControllerName, aControllerPort, aDevice, aForce));
4121
4122 CheckComArgStrNotEmptyOrNull(aControllerName);
4123
4124 AutoCaller autoCaller(this);
4125 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4126
4127 // request the host lock first, since might be calling Host methods for getting host drives;
4128 // next, protect the media tree all the while we're in here, as well as our member variables
4129 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
4130 this->lockHandle(),
4131 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4132
4133 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4134 aControllerName,
4135 aControllerPort,
4136 aDevice);
4137 if (pAttach.isNull())
4138 return setError(VBOX_E_OBJECT_NOT_FOUND,
4139 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
4140 aDevice, aControllerPort, aControllerName);
4141
4142 /* Remember previously mounted medium. The medium before taking the
4143 * backup is not necessarily the same thing. */
4144 ComObjPtr<Medium> oldmedium;
4145 oldmedium = pAttach->getMedium();
4146
4147 ComObjPtr<Medium> pMedium = static_cast<Medium*>(aMedium);
4148 if (aMedium && pMedium.isNull())
4149 return setError(E_INVALIDARG, "The given medium pointer is invalid");
4150
4151 AutoCaller mediumCaller(pMedium);
4152 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4153
4154 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4155 if (pMedium)
4156 {
4157 DeviceType_T mediumType = pAttach->getType();
4158 switch (mediumType)
4159 {
4160 case DeviceType_DVD:
4161 case DeviceType_Floppy:
4162 break;
4163
4164 default:
4165 return setError(VBOX_E_INVALID_OBJECT_STATE,
4166 tr("The device at port %d, device %d of controller '%ls' of this virtual machine is not removeable"),
4167 aControllerPort,
4168 aDevice,
4169 aControllerName);
4170 }
4171 }
4172
4173 setModified(IsModified_Storage);
4174 mMediaData.backup();
4175
4176 GuidList llRegistriesThatNeedSaving;
4177
4178 {
4179 // The backup operation makes the pAttach reference point to the
4180 // old settings. Re-get the correct reference.
4181 pAttach = findAttachment(mMediaData->mAttachments,
4182 aControllerName,
4183 aControllerPort,
4184 aDevice);
4185 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4186 if (!oldmedium.isNull())
4187 oldmedium->removeBackReference(mData->mUuid);
4188 if (!pMedium.isNull())
4189 {
4190 pMedium->addBackReference(mData->mUuid);
4191
4192 addMediumToRegistry(pMedium, llRegistriesThatNeedSaving, NULL /* Guid *puuid */ );
4193 }
4194
4195 pAttach->updateMedium(pMedium);
4196 }
4197
4198 setModified(IsModified_Storage);
4199
4200 mediumLock.release();
4201 multiLock.release();
4202 rc = onMediumChange(pAttach, aForce);
4203 multiLock.acquire();
4204 mediumLock.acquire();
4205
4206 /* On error roll back this change only. */
4207 if (FAILED(rc))
4208 {
4209 if (!pMedium.isNull())
4210 pMedium->removeBackReference(mData->mUuid);
4211 pAttach = findAttachment(mMediaData->mAttachments,
4212 aControllerName,
4213 aControllerPort,
4214 aDevice);
4215 /* If the attachment is gone in the meantime, bail out. */
4216 if (pAttach.isNull())
4217 return rc;
4218 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4219 if (!oldmedium.isNull())
4220 oldmedium->addBackReference(mData->mUuid);
4221 pAttach->updateMedium(oldmedium);
4222 }
4223
4224 mediumLock.release();
4225 multiLock.release();
4226
4227 mParent->saveRegistries(llRegistriesThatNeedSaving);
4228
4229 return rc;
4230}
4231
4232STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
4233 LONG aControllerPort,
4234 LONG aDevice,
4235 IMedium **aMedium)
4236{
4237 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4238 aControllerName, aControllerPort, aDevice));
4239
4240 CheckComArgStrNotEmptyOrNull(aControllerName);
4241 CheckComArgOutPointerValid(aMedium);
4242
4243 AutoCaller autoCaller(this);
4244 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4245
4246 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4247
4248 *aMedium = NULL;
4249
4250 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4251 aControllerName,
4252 aControllerPort,
4253 aDevice);
4254 if (pAttach.isNull())
4255 return setError(VBOX_E_OBJECT_NOT_FOUND,
4256 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4257 aDevice, aControllerPort, aControllerName);
4258
4259 pAttach->getMedium().queryInterfaceTo(aMedium);
4260
4261 return S_OK;
4262}
4263
4264STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
4265{
4266 CheckComArgOutPointerValid(port);
4267 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
4268
4269 AutoCaller autoCaller(this);
4270 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4271
4272 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4273
4274 mSerialPorts[slot].queryInterfaceTo(port);
4275
4276 return S_OK;
4277}
4278
4279STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
4280{
4281 CheckComArgOutPointerValid(port);
4282 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
4283
4284 AutoCaller autoCaller(this);
4285 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4286
4287 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4288
4289 mParallelPorts[slot].queryInterfaceTo(port);
4290
4291 return S_OK;
4292}
4293
4294STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
4295{
4296 CheckComArgOutPointerValid(adapter);
4297 CheckComArgExpr(slot, slot < RT_ELEMENTS(mNetworkAdapters));
4298
4299 AutoCaller autoCaller(this);
4300 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4301
4302 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4303
4304 mNetworkAdapters[slot].queryInterfaceTo(adapter);
4305
4306 return S_OK;
4307}
4308
4309STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
4310{
4311 if (ComSafeArrayOutIsNull(aKeys))
4312 return E_POINTER;
4313
4314 AutoCaller autoCaller(this);
4315 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4316
4317 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4318
4319 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
4320 int i = 0;
4321 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4322 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4323 ++it, ++i)
4324 {
4325 const Utf8Str &strKey = it->first;
4326 strKey.cloneTo(&saKeys[i]);
4327 }
4328 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
4329
4330 return S_OK;
4331 }
4332
4333 /**
4334 * @note Locks this object for reading.
4335 */
4336STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
4337 BSTR *aValue)
4338{
4339 CheckComArgStrNotEmptyOrNull(aKey);
4340 CheckComArgOutPointerValid(aValue);
4341
4342 AutoCaller autoCaller(this);
4343 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4344
4345 /* start with nothing found */
4346 Bstr bstrResult("");
4347
4348 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4349
4350 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
4351 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4352 // found:
4353 bstrResult = it->second; // source is a Utf8Str
4354
4355 /* return the result to caller (may be empty) */
4356 bstrResult.cloneTo(aValue);
4357
4358 return S_OK;
4359}
4360
4361 /**
4362 * @note Locks mParent for writing + this object for writing.
4363 */
4364STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
4365{
4366 CheckComArgStrNotEmptyOrNull(aKey);
4367
4368 AutoCaller autoCaller(this);
4369 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4370
4371 Utf8Str strKey(aKey);
4372 Utf8Str strValue(aValue);
4373 Utf8Str strOldValue; // empty
4374
4375 // locking note: we only hold the read lock briefly to look up the old value,
4376 // then release it and call the onExtraCanChange callbacks. There is a small
4377 // chance of a race insofar as the callback might be called twice if two callers
4378 // change the same key at the same time, but that's a much better solution
4379 // than the deadlock we had here before. The actual changing of the extradata
4380 // is then performed under the write lock and race-free.
4381
4382 // look up the old value first; if nothing has changed then we need not do anything
4383 {
4384 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
4385 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
4386 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4387 strOldValue = it->second;
4388 }
4389
4390 bool fChanged;
4391 if ((fChanged = (strOldValue != strValue)))
4392 {
4393 // ask for permission from all listeners outside the locks;
4394 // onExtraDataCanChange() only briefly requests the VirtualBox
4395 // lock to copy the list of callbacks to invoke
4396 Bstr error;
4397 Bstr bstrValue(aValue);
4398
4399 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue.raw(), error))
4400 {
4401 const char *sep = error.isEmpty() ? "" : ": ";
4402 CBSTR err = error.raw();
4403 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
4404 sep, err));
4405 return setError(E_ACCESSDENIED,
4406 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
4407 aKey,
4408 bstrValue.raw(),
4409 sep,
4410 err);
4411 }
4412
4413 // data is changing and change not vetoed: then write it out under the lock
4414 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4415
4416 if (isSnapshotMachine())
4417 {
4418 HRESULT rc = checkStateDependency(MutableStateDep);
4419 if (FAILED(rc)) return rc;
4420 }
4421
4422 if (strValue.isEmpty())
4423 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
4424 else
4425 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
4426 // creates a new key if needed
4427
4428 bool fNeedsGlobalSaveSettings = false;
4429 saveSettings(&fNeedsGlobalSaveSettings);
4430
4431 if (fNeedsGlobalSaveSettings)
4432 {
4433 // save the global settings; for that we should hold only the VirtualBox lock
4434 alock.release();
4435 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
4436 mParent->saveSettings();
4437 }
4438 }
4439
4440 // fire notification outside the lock
4441 if (fChanged)
4442 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
4443
4444 return S_OK;
4445}
4446
4447STDMETHODIMP Machine::SaveSettings()
4448{
4449 AutoCaller autoCaller(this);
4450 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4451
4452 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
4453
4454 /* when there was auto-conversion, we want to save the file even if
4455 * the VM is saved */
4456 HRESULT rc = checkStateDependency(MutableStateDep);
4457 if (FAILED(rc)) return rc;
4458
4459 /* the settings file path may never be null */
4460 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
4461
4462 /* save all VM data excluding snapshots */
4463 bool fNeedsGlobalSaveSettings = false;
4464 rc = saveSettings(&fNeedsGlobalSaveSettings);
4465 mlock.release();
4466
4467 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
4468 {
4469 // save the global settings; for that we should hold only the VirtualBox lock
4470 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
4471 rc = mParent->saveSettings();
4472 }
4473
4474 return rc;
4475}
4476
4477STDMETHODIMP Machine::DiscardSettings()
4478{
4479 AutoCaller autoCaller(this);
4480 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4481
4482 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4483
4484 HRESULT rc = checkStateDependency(MutableStateDep);
4485 if (FAILED(rc)) return rc;
4486
4487 /*
4488 * during this rollback, the session will be notified if data has
4489 * been actually changed
4490 */
4491 rollback(true /* aNotify */);
4492
4493 return S_OK;
4494}
4495
4496/** @note Locks objects! */
4497STDMETHODIMP Machine::Unregister(CleanupMode_T cleanupMode,
4498 ComSafeArrayOut(IMedium*, aMedia))
4499{
4500 // use AutoLimitedCaller because this call is valid on inaccessible machines as well
4501 AutoLimitedCaller autoCaller(this);
4502 AssertComRCReturnRC(autoCaller.rc());
4503
4504 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4505
4506 Guid id(getId());
4507
4508 if (mData->mSession.mState != SessionState_Unlocked)
4509 return setError(VBOX_E_INVALID_OBJECT_STATE,
4510 tr("Cannot unregister the machine '%s' while it is locked"),
4511 mUserData->s.strName.c_str());
4512
4513 // wait for state dependents to drop to zero
4514 ensureNoStateDependencies();
4515
4516 if (!mData->mAccessible)
4517 {
4518 // inaccessible maschines can only be unregistered; uninitialize ourselves
4519 // here because currently there may be no unregistered that are inaccessible
4520 // (this state combination is not supported). Note releasing the caller and
4521 // leaving the lock before calling uninit()
4522 alock.leave();
4523 autoCaller.release();
4524
4525 uninit();
4526
4527 mParent->unregisterMachine(this, id);
4528 // calls VirtualBox::saveSettings()
4529
4530 return S_OK;
4531 }
4532
4533 HRESULT rc = S_OK;
4534
4535 // discard saved state
4536 if (mData->mMachineState == MachineState_Saved)
4537 {
4538 // add the saved state file to the list of files the caller should delete
4539 Assert(!mSSData->strStateFilePath.isEmpty());
4540 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
4541
4542 mSSData->strStateFilePath.setNull();
4543
4544 // unconditionally set the machine state to powered off, we now
4545 // know no session has locked the machine
4546 mData->mMachineState = MachineState_PoweredOff;
4547 }
4548
4549 size_t cSnapshots = 0;
4550 if (mData->mFirstSnapshot)
4551 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4552 if (cSnapshots && cleanupMode == CleanupMode_UnregisterOnly)
4553 // fail now before we start detaching media
4554 return setError(VBOX_E_INVALID_OBJECT_STATE,
4555 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
4556 mUserData->s.strName.c_str(), cSnapshots);
4557
4558 // This list collects the medium objects from all medium attachments
4559 // which we will detach from the machine and its snapshots, in a specific
4560 // order which allows for closing all media without getting "media in use"
4561 // errors, simply by going through the list from the front to the back:
4562 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
4563 // and must be closed before the parent media from the snapshots, or closing the parents
4564 // will fail because they still have children);
4565 // 2) media from the youngest snapshots followed by those from the parent snapshots until
4566 // the root ("first") snapshot of the machine.
4567 MediaList llMedia;
4568
4569 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4570 && mMediaData->mAttachments.size()
4571 )
4572 {
4573 // we have media attachments: detach them all and add the Medium objects to our list
4574 if (cleanupMode != CleanupMode_UnregisterOnly)
4575 detachAllMedia(alock, NULL /* pSnapshot */, cleanupMode, llMedia);
4576 else
4577 return setError(VBOX_E_INVALID_OBJECT_STATE,
4578 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
4579 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
4580 }
4581
4582 if (cSnapshots)
4583 {
4584 // autoCleanup must be true here, or we would have failed above
4585
4586 // add the media from the medium attachments of the snapshots to llMedia
4587 // as well, after the "main" machine media; Snapshot::uninitRecursively()
4588 // calls Machine::detachAllMedia() for the snapshot machine, recursing
4589 // into the children first
4590
4591 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
4592 MachineState_T oldState = mData->mMachineState;
4593 mData->mMachineState = MachineState_DeletingSnapshot;
4594
4595 // make a copy of the first snapshot so the refcount does not drop to 0
4596 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
4597 // because of the AutoCaller voodoo)
4598 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
4599
4600 // GO!
4601 pFirstSnapshot->uninitRecursively(alock, cleanupMode, llMedia, mData->llFilesToDelete);
4602
4603 mData->mMachineState = oldState;
4604 }
4605
4606 if (FAILED(rc))
4607 {
4608 rollbackMedia();
4609 return rc;
4610 }
4611
4612 // commit all the media changes made above
4613 commitMedia();
4614
4615 mData->mRegistered = false;
4616
4617 // machine lock no longer needed
4618 alock.release();
4619
4620 // return media to caller
4621 SafeIfaceArray<IMedium> sfaMedia(llMedia);
4622 sfaMedia.detachTo(ComSafeArrayOutArg(aMedia));
4623
4624 mParent->unregisterMachine(this, id);
4625 // calls VirtualBox::saveSettings()
4626
4627 return S_OK;
4628}
4629
4630struct Machine::DeleteTask
4631{
4632 ComObjPtr<Machine> pMachine;
4633 RTCList< ComPtr<IMedium> > llMediums;
4634 std::list<Utf8Str> llFilesToDelete;
4635 ComObjPtr<Progress> pProgress;
4636 GuidList llRegistriesThatNeedSaving;
4637};
4638
4639STDMETHODIMP Machine::Delete(ComSafeArrayIn(IMedium*, aMedia), IProgress **aProgress)
4640{
4641 LogFlowFuncEnter();
4642
4643 AutoCaller autoCaller(this);
4644 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4645
4646 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4647
4648 HRESULT rc = checkStateDependency(MutableStateDep);
4649 if (FAILED(rc)) return rc;
4650
4651 if (mData->mRegistered)
4652 return setError(VBOX_E_INVALID_VM_STATE,
4653 tr("Cannot delete settings of a registered machine"));
4654
4655 DeleteTask *pTask = new DeleteTask;
4656 pTask->pMachine = this;
4657 com::SafeIfaceArray<IMedium> sfaMedia(ComSafeArrayInArg(aMedia));
4658
4659 // collect files to delete
4660 pTask->llFilesToDelete = mData->llFilesToDelete; // saved states pushed here by Unregister()
4661
4662 for (size_t i = 0; i < sfaMedia.size(); ++i)
4663 {
4664 IMedium *pIMedium(sfaMedia[i]);
4665 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
4666 if (pMedium.isNull())
4667 return setError(E_INVALIDARG, "The given medium pointer with index %d is invalid", i);
4668 SafeArray<BSTR> ids;
4669 rc = pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(ids));
4670 if (FAILED(rc)) return rc;
4671 /* At this point the medium should not have any back references
4672 * anymore. If it has it is attached to another VM and *must* not
4673 * deleted. */
4674 if (ids.size() < 1)
4675 pTask->llMediums.append(pMedium);
4676 }
4677 if (mData->pMachineConfigFile->fileExists())
4678 pTask->llFilesToDelete.push_back(mData->m_strConfigFileFull);
4679
4680 pTask->pProgress.createObject();
4681 pTask->pProgress->init(getVirtualBox(),
4682 static_cast<IMachine*>(this) /* aInitiator */,
4683 Bstr(tr("Deleting files")).raw(),
4684 true /* fCancellable */,
4685 pTask->llFilesToDelete.size() + pTask->llMediums.size() + 1, // cOperations
4686 BstrFmt(tr("Deleting '%s'"), pTask->llFilesToDelete.front().c_str()).raw());
4687
4688 int vrc = RTThreadCreate(NULL,
4689 Machine::deleteThread,
4690 (void*)pTask,
4691 0,
4692 RTTHREADTYPE_MAIN_WORKER,
4693 0,
4694 "MachineDelete");
4695
4696 pTask->pProgress.queryInterfaceTo(aProgress);
4697
4698 if (RT_FAILURE(vrc))
4699 {
4700 delete pTask;
4701 return setError(E_FAIL, "Could not create MachineDelete thread (%Rrc)", vrc);
4702 }
4703
4704 LogFlowFuncLeave();
4705
4706 return S_OK;
4707}
4708
4709/**
4710 * Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
4711 * calls Machine::deleteTaskWorker() on the actual machine object.
4712 * @param Thread
4713 * @param pvUser
4714 * @return
4715 */
4716/*static*/
4717DECLCALLBACK(int) Machine::deleteThread(RTTHREAD Thread, void *pvUser)
4718{
4719 LogFlowFuncEnter();
4720
4721 DeleteTask *pTask = (DeleteTask*)pvUser;
4722 Assert(pTask);
4723 Assert(pTask->pMachine);
4724 Assert(pTask->pProgress);
4725
4726 HRESULT rc = pTask->pMachine->deleteTaskWorker(*pTask);
4727 pTask->pProgress->notifyComplete(rc);
4728
4729 delete pTask;
4730
4731 LogFlowFuncLeave();
4732
4733 NOREF(Thread);
4734
4735 return VINF_SUCCESS;
4736}
4737
4738/**
4739 * Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
4740 * @param task
4741 * @return
4742 */
4743HRESULT Machine::deleteTaskWorker(DeleteTask &task)
4744{
4745 AutoCaller autoCaller(this);
4746 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4747
4748 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4749
4750 HRESULT rc = S_OK;
4751
4752 try
4753 {
4754 ULONG uLogHistoryCount = 3;
4755 ComPtr<ISystemProperties> systemProperties;
4756 rc = mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4757 if (FAILED(rc)) throw rc;
4758
4759 if (!systemProperties.isNull())
4760 {
4761 rc = systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4762 if (FAILED(rc)) throw rc;
4763 }
4764
4765 MachineState_T oldState = mData->mMachineState;
4766 setMachineState(MachineState_SettingUp);
4767 alock.release();
4768 for (size_t i = 0; i < task.llMediums.size(); ++i)
4769 {
4770 ComObjPtr<Medium> pMedium = (Medium*)(IMedium*)task.llMediums.at(i);
4771 {
4772 AutoCaller mac(pMedium);
4773 if (FAILED(mac.rc())) throw mac.rc();
4774 Utf8Str strLocation = pMedium->getLocationFull();
4775 rc = task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), strLocation.c_str()).raw(), 1);
4776 if (FAILED(rc)) throw rc;
4777 LogFunc(("Deleting file %s\n", strLocation.c_str()));
4778 }
4779 ComPtr<IProgress> pProgress2;
4780 rc = pMedium->DeleteStorage(pProgress2.asOutParam());
4781 if (FAILED(rc)) throw rc;
4782 rc = task.pProgress->WaitForAsyncProgressCompletion(pProgress2);
4783 if (FAILED(rc)) throw rc;
4784 /* Check the result of the asynchrony process. */
4785 LONG iRc;
4786 rc = pProgress2->COMGETTER(ResultCode)(&iRc);
4787 if (FAILED(rc)) throw rc;
4788 if (FAILED(iRc))
4789 {
4790 /* If the thread of the progress object has an error, then
4791 * retrieve the error info from there, or it'll be lost. */
4792 ProgressErrorInfo info(pProgress2);
4793 throw setError(iRc, Utf8Str(info.getText()).c_str());
4794 }
4795 }
4796 setMachineState(oldState);
4797 alock.acquire();
4798
4799 // delete the files pushed on the task list by Machine::Delete()
4800 // (this includes saved states of the machine and snapshots and
4801 // medium storage files from the IMedium list passed in, and the
4802 // machine XML file)
4803 std::list<Utf8Str>::const_iterator it = task.llFilesToDelete.begin();
4804 while (it != task.llFilesToDelete.end())
4805 {
4806 const Utf8Str &strFile = *it;
4807 LogFunc(("Deleting file %s\n", strFile.c_str()));
4808 int vrc = RTFileDelete(strFile.c_str());
4809 if (RT_FAILURE(vrc))
4810 throw setError(VBOX_E_IPRT_ERROR,
4811 tr("Could not delete file '%s' (%Rrc)"), strFile.c_str(), vrc);
4812
4813 ++it;
4814 if (it == task.llFilesToDelete.end())
4815 {
4816 rc = task.pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
4817 if (FAILED(rc)) throw rc;
4818 break;
4819 }
4820
4821 rc = task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
4822 if (FAILED(rc)) throw rc;
4823 }
4824
4825 /* delete the settings only when the file actually exists */
4826 if (mData->pMachineConfigFile->fileExists())
4827 {
4828 /* Delete any backup or uncommitted XML files. Ignore failures.
4829 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4830 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4831 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4832 RTFileDelete(otherXml.c_str());
4833 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4834 RTFileDelete(otherXml.c_str());
4835
4836 /* delete the Logs folder, nothing important should be left
4837 * there (we don't check for errors because the user might have
4838 * some private files there that we don't want to delete) */
4839 Utf8Str logFolder;
4840 getLogFolder(logFolder);
4841 Assert(logFolder.length());
4842 if (RTDirExists(logFolder.c_str()))
4843 {
4844 /* Delete all VBox.log[.N] files from the Logs folder
4845 * (this must be in sync with the rotation logic in
4846 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4847 * files that may have been created by the GUI. */
4848 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4849 logFolder.c_str(), RTPATH_DELIMITER);
4850 RTFileDelete(log.c_str());
4851 log = Utf8StrFmt("%s%cVBox.png",
4852 logFolder.c_str(), RTPATH_DELIMITER);
4853 RTFileDelete(log.c_str());
4854 for (int i = uLogHistoryCount; i > 0; i--)
4855 {
4856 log = Utf8StrFmt("%s%cVBox.log.%d",
4857 logFolder.c_str(), RTPATH_DELIMITER, i);
4858 RTFileDelete(log.c_str());
4859 log = Utf8StrFmt("%s%cVBox.png.%d",
4860 logFolder.c_str(), RTPATH_DELIMITER, i);
4861 RTFileDelete(log.c_str());
4862 }
4863
4864 RTDirRemove(logFolder.c_str());
4865 }
4866
4867 /* delete the Snapshots folder, nothing important should be left
4868 * there (we don't check for errors because the user might have
4869 * some private files there that we don't want to delete) */
4870 Utf8Str strFullSnapshotFolder;
4871 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4872 Assert(!strFullSnapshotFolder.isEmpty());
4873 if (RTDirExists(strFullSnapshotFolder.c_str()))
4874 RTDirRemove(strFullSnapshotFolder.c_str());
4875
4876 // delete the directory that contains the settings file, but only
4877 // if it matches the VM name
4878 Utf8Str settingsDir;
4879 if (isInOwnDir(&settingsDir))
4880 RTDirRemove(settingsDir.c_str());
4881 }
4882
4883 alock.release();
4884
4885 rc = mParent->saveRegistries(task.llRegistriesThatNeedSaving);
4886 if (FAILED(rc)) throw rc;
4887 }
4888 catch (HRESULT aRC) { rc = aRC; }
4889
4890 return rc;
4891}
4892
4893STDMETHODIMP Machine::FindSnapshot(IN_BSTR aNameOrId, ISnapshot **aSnapshot)
4894{
4895 CheckComArgOutPointerValid(aSnapshot);
4896
4897 AutoCaller autoCaller(this);
4898 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4899
4900 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4901
4902 ComObjPtr<Snapshot> pSnapshot;
4903 HRESULT rc;
4904
4905 if (!aNameOrId || !*aNameOrId)
4906 // null case (caller wants root snapshot): findSnapshotById() handles this
4907 rc = findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
4908 else
4909 {
4910 Guid uuid(aNameOrId);
4911 if (!uuid.isEmpty())
4912 rc = findSnapshotById(uuid, pSnapshot, true /* aSetError */);
4913 else
4914 rc = findSnapshotByName(Utf8Str(aNameOrId), pSnapshot, true /* aSetError */);
4915 }
4916 pSnapshot.queryInterfaceTo(aSnapshot);
4917
4918 return rc;
4919}
4920
4921STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4922{
4923 CheckComArgStrNotEmptyOrNull(aName);
4924 CheckComArgStrNotEmptyOrNull(aHostPath);
4925
4926 AutoCaller autoCaller(this);
4927 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4928
4929 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4930
4931 HRESULT rc = checkStateDependency(MutableStateDep);
4932 if (FAILED(rc)) return rc;
4933
4934 Utf8Str strName(aName);
4935
4936 ComObjPtr<SharedFolder> sharedFolder;
4937 rc = findSharedFolder(strName, sharedFolder, false /* aSetError */);
4938 if (SUCCEEDED(rc))
4939 return setError(VBOX_E_OBJECT_IN_USE,
4940 tr("Shared folder named '%s' already exists"),
4941 strName.c_str());
4942
4943 sharedFolder.createObject();
4944 rc = sharedFolder->init(getMachine(),
4945 strName,
4946 aHostPath,
4947 !!aWritable,
4948 !!aAutoMount,
4949 true /* fFailOnError */);
4950 if (FAILED(rc)) return rc;
4951
4952 setModified(IsModified_SharedFolders);
4953 mHWData.backup();
4954 mHWData->mSharedFolders.push_back(sharedFolder);
4955
4956 /* inform the direct session if any */
4957 alock.leave();
4958 onSharedFolderChange();
4959
4960 return S_OK;
4961}
4962
4963STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4964{
4965 CheckComArgStrNotEmptyOrNull(aName);
4966
4967 AutoCaller autoCaller(this);
4968 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4969
4970 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4971
4972 HRESULT rc = checkStateDependency(MutableStateDep);
4973 if (FAILED(rc)) return rc;
4974
4975 ComObjPtr<SharedFolder> sharedFolder;
4976 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4977 if (FAILED(rc)) return rc;
4978
4979 setModified(IsModified_SharedFolders);
4980 mHWData.backup();
4981 mHWData->mSharedFolders.remove(sharedFolder);
4982
4983 /* inform the direct session if any */
4984 alock.leave();
4985 onSharedFolderChange();
4986
4987 return S_OK;
4988}
4989
4990STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4991{
4992 CheckComArgOutPointerValid(aCanShow);
4993
4994 /* start with No */
4995 *aCanShow = FALSE;
4996
4997 AutoCaller autoCaller(this);
4998 AssertComRCReturnRC(autoCaller.rc());
4999
5000 ComPtr<IInternalSessionControl> directControl;
5001 {
5002 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5003
5004 if (mData->mSession.mState != SessionState_Locked)
5005 return setError(VBOX_E_INVALID_VM_STATE,
5006 tr("Machine is not locked for session (session state: %s)"),
5007 Global::stringifySessionState(mData->mSession.mState));
5008
5009 directControl = mData->mSession.mDirectControl;
5010 }
5011
5012 /* ignore calls made after #OnSessionEnd() is called */
5013 if (!directControl)
5014 return S_OK;
5015
5016 LONG64 dummy;
5017 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
5018}
5019
5020STDMETHODIMP Machine::ShowConsoleWindow(LONG64 *aWinId)
5021{
5022 CheckComArgOutPointerValid(aWinId);
5023
5024 AutoCaller autoCaller(this);
5025 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5026
5027 ComPtr<IInternalSessionControl> directControl;
5028 {
5029 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5030
5031 if (mData->mSession.mState != SessionState_Locked)
5032 return setError(E_FAIL,
5033 tr("Machine is not locked for session (session state: %s)"),
5034 Global::stringifySessionState(mData->mSession.mState));
5035
5036 directControl = mData->mSession.mDirectControl;
5037 }
5038
5039 /* ignore calls made after #OnSessionEnd() is called */
5040 if (!directControl)
5041 return S_OK;
5042
5043 BOOL dummy;
5044 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
5045}
5046
5047#ifdef VBOX_WITH_GUEST_PROPS
5048/**
5049 * Look up a guest property in VBoxSVC's internal structures.
5050 */
5051HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
5052 BSTR *aValue,
5053 LONG64 *aTimestamp,
5054 BSTR *aFlags) const
5055{
5056 using namespace guestProp;
5057
5058 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5059 Utf8Str strName(aName);
5060 HWData::GuestPropertyList::const_iterator it;
5061
5062 for (it = mHWData->mGuestProperties.begin();
5063 it != mHWData->mGuestProperties.end(); ++it)
5064 {
5065 if (it->strName == strName)
5066 {
5067 char szFlags[MAX_FLAGS_LEN + 1];
5068 it->strValue.cloneTo(aValue);
5069 *aTimestamp = it->mTimestamp;
5070 writeFlags(it->mFlags, szFlags);
5071 Bstr(szFlags).cloneTo(aFlags);
5072 break;
5073 }
5074 }
5075 return S_OK;
5076}
5077
5078/**
5079 * Query the VM that a guest property belongs to for the property.
5080 * @returns E_ACCESSDENIED if the VM process is not available or not
5081 * currently handling queries and the lookup should then be done in
5082 * VBoxSVC.
5083 */
5084HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
5085 BSTR *aValue,
5086 LONG64 *aTimestamp,
5087 BSTR *aFlags) const
5088{
5089 HRESULT rc;
5090 ComPtr<IInternalSessionControl> directControl;
5091 directControl = mData->mSession.mDirectControl;
5092
5093 /* fail if we were called after #OnSessionEnd() is called. This is a
5094 * silly race condition. */
5095
5096 if (!directControl)
5097 rc = E_ACCESSDENIED;
5098 else
5099 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
5100 false /* isSetter */,
5101 aValue, aTimestamp, aFlags);
5102 return rc;
5103}
5104#endif // VBOX_WITH_GUEST_PROPS
5105
5106STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
5107 BSTR *aValue,
5108 LONG64 *aTimestamp,
5109 BSTR *aFlags)
5110{
5111#ifndef VBOX_WITH_GUEST_PROPS
5112 ReturnComNotImplemented();
5113#else // VBOX_WITH_GUEST_PROPS
5114 CheckComArgStrNotEmptyOrNull(aName);
5115 CheckComArgOutPointerValid(aValue);
5116 CheckComArgOutPointerValid(aTimestamp);
5117 CheckComArgOutPointerValid(aFlags);
5118
5119 AutoCaller autoCaller(this);
5120 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5121
5122 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
5123 if (rc == E_ACCESSDENIED)
5124 /* The VM is not running or the service is not (yet) accessible */
5125 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
5126 return rc;
5127#endif // VBOX_WITH_GUEST_PROPS
5128}
5129
5130STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
5131{
5132 LONG64 dummyTimestamp;
5133 Bstr dummyFlags;
5134 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
5135}
5136
5137STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, LONG64 *aTimestamp)
5138{
5139 Bstr dummyValue;
5140 Bstr dummyFlags;
5141 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
5142}
5143
5144#ifdef VBOX_WITH_GUEST_PROPS
5145/**
5146 * Set a guest property in VBoxSVC's internal structures.
5147 */
5148HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
5149 IN_BSTR aFlags)
5150{
5151 using namespace guestProp;
5152
5153 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5154 HRESULT rc = S_OK;
5155 HWData::GuestProperty property;
5156 property.mFlags = NILFLAG;
5157 bool found = false;
5158
5159 rc = checkStateDependency(MutableStateDep);
5160 if (FAILED(rc)) return rc;
5161
5162 try
5163 {
5164 Utf8Str utf8Name(aName);
5165 Utf8Str utf8Flags(aFlags);
5166 uint32_t fFlags = NILFLAG;
5167 if ( (aFlags != NULL)
5168 && RT_FAILURE(validateFlags(utf8Flags.c_str(), &fFlags))
5169 )
5170 return setError(E_INVALIDARG,
5171 tr("Invalid flag values: '%ls'"),
5172 aFlags);
5173
5174 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
5175 * know, this is simple and do an OK job atm.) */
5176 HWData::GuestPropertyList::iterator it;
5177 for (it = mHWData->mGuestProperties.begin();
5178 it != mHWData->mGuestProperties.end(); ++it)
5179 if (it->strName == utf8Name)
5180 {
5181 property = *it;
5182 if (it->mFlags & (RDONLYHOST))
5183 rc = setError(E_ACCESSDENIED,
5184 tr("The property '%ls' cannot be changed by the host"),
5185 aName);
5186 else
5187 {
5188 setModified(IsModified_MachineData);
5189 mHWData.backup(); // @todo r=dj backup in a loop?!?
5190
5191 /* The backup() operation invalidates our iterator, so
5192 * get a new one. */
5193 for (it = mHWData->mGuestProperties.begin();
5194 it->strName != utf8Name;
5195 ++it)
5196 ;
5197 mHWData->mGuestProperties.erase(it);
5198 }
5199 found = true;
5200 break;
5201 }
5202 if (found && SUCCEEDED(rc))
5203 {
5204 if (*aValue)
5205 {
5206 RTTIMESPEC time;
5207 property.strValue = aValue;
5208 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5209 if (aFlags != NULL)
5210 property.mFlags = fFlags;
5211 mHWData->mGuestProperties.push_back(property);
5212 }
5213 }
5214 else if (SUCCEEDED(rc) && *aValue)
5215 {
5216 RTTIMESPEC time;
5217 setModified(IsModified_MachineData);
5218 mHWData.backup();
5219 property.strName = aName;
5220 property.strValue = aValue;
5221 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5222 property.mFlags = fFlags;
5223 mHWData->mGuestProperties.push_back(property);
5224 }
5225 if ( SUCCEEDED(rc)
5226 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
5227 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
5228 RTSTR_MAX,
5229 utf8Name.c_str(),
5230 RTSTR_MAX,
5231 NULL)
5232 )
5233 )
5234 {
5235 /** @todo r=bird: Why aren't we leaving the lock here? The
5236 * same code in PushGuestProperty does... */
5237 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
5238 }
5239 }
5240 catch (std::bad_alloc &)
5241 {
5242 rc = E_OUTOFMEMORY;
5243 }
5244
5245 return rc;
5246}
5247
5248/**
5249 * Set a property on the VM that that property belongs to.
5250 * @returns E_ACCESSDENIED if the VM process is not available or not
5251 * currently handling queries and the setting should then be done in
5252 * VBoxSVC.
5253 */
5254HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
5255 IN_BSTR aFlags)
5256{
5257 HRESULT rc;
5258
5259 try
5260 {
5261 ComPtr<IInternalSessionControl> directControl = mData->mSession.mDirectControl;
5262
5263 BSTR dummy = NULL; /* will not be changed (setter) */
5264 LONG64 dummy64;
5265 if (!directControl)
5266 rc = E_ACCESSDENIED;
5267 else
5268 /** @todo Fix when adding DeleteGuestProperty(),
5269 see defect. */
5270 rc = directControl->AccessGuestProperty(aName, aValue, aFlags,
5271 true /* isSetter */,
5272 &dummy, &dummy64, &dummy);
5273 }
5274 catch (std::bad_alloc &)
5275 {
5276 rc = E_OUTOFMEMORY;
5277 }
5278
5279 return rc;
5280}
5281#endif // VBOX_WITH_GUEST_PROPS
5282
5283STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
5284 IN_BSTR aFlags)
5285{
5286#ifndef VBOX_WITH_GUEST_PROPS
5287 ReturnComNotImplemented();
5288#else // VBOX_WITH_GUEST_PROPS
5289 CheckComArgStrNotEmptyOrNull(aName);
5290 CheckComArgMaybeNull(aFlags);
5291 CheckComArgMaybeNull(aValue);
5292
5293 AutoCaller autoCaller(this);
5294 if (FAILED(autoCaller.rc()))
5295 return autoCaller.rc();
5296
5297 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
5298 if (rc == E_ACCESSDENIED)
5299 /* The VM is not running or the service is not (yet) accessible */
5300 rc = setGuestPropertyToService(aName, aValue, aFlags);
5301 return rc;
5302#endif // VBOX_WITH_GUEST_PROPS
5303}
5304
5305STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
5306{
5307 return SetGuestProperty(aName, aValue, NULL);
5308}
5309
5310#ifdef VBOX_WITH_GUEST_PROPS
5311/**
5312 * Enumerate the guest properties in VBoxSVC's internal structures.
5313 */
5314HRESULT Machine::enumerateGuestPropertiesInService
5315 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5316 ComSafeArrayOut(BSTR, aValues),
5317 ComSafeArrayOut(LONG64, aTimestamps),
5318 ComSafeArrayOut(BSTR, aFlags))
5319{
5320 using namespace guestProp;
5321
5322 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5323 Utf8Str strPatterns(aPatterns);
5324
5325 /*
5326 * Look for matching patterns and build up a list.
5327 */
5328 HWData::GuestPropertyList propList;
5329 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
5330 it != mHWData->mGuestProperties.end();
5331 ++it)
5332 if ( strPatterns.isEmpty()
5333 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5334 RTSTR_MAX,
5335 it->strName.c_str(),
5336 RTSTR_MAX,
5337 NULL)
5338 )
5339 propList.push_back(*it);
5340
5341 /*
5342 * And build up the arrays for returning the property information.
5343 */
5344 size_t cEntries = propList.size();
5345 SafeArray<BSTR> names(cEntries);
5346 SafeArray<BSTR> values(cEntries);
5347 SafeArray<LONG64> timestamps(cEntries);
5348 SafeArray<BSTR> flags(cEntries);
5349 size_t iProp = 0;
5350 for (HWData::GuestPropertyList::iterator it = propList.begin();
5351 it != propList.end();
5352 ++it)
5353 {
5354 char szFlags[MAX_FLAGS_LEN + 1];
5355 it->strName.cloneTo(&names[iProp]);
5356 it->strValue.cloneTo(&values[iProp]);
5357 timestamps[iProp] = it->mTimestamp;
5358 writeFlags(it->mFlags, szFlags);
5359 Bstr(szFlags).cloneTo(&flags[iProp]);
5360 ++iProp;
5361 }
5362 names.detachTo(ComSafeArrayOutArg(aNames));
5363 values.detachTo(ComSafeArrayOutArg(aValues));
5364 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
5365 flags.detachTo(ComSafeArrayOutArg(aFlags));
5366 return S_OK;
5367}
5368
5369/**
5370 * Enumerate the properties managed by a VM.
5371 * @returns E_ACCESSDENIED if the VM process is not available or not
5372 * currently handling queries and the setting should then be done in
5373 * VBoxSVC.
5374 */
5375HRESULT Machine::enumerateGuestPropertiesOnVM
5376 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5377 ComSafeArrayOut(BSTR, aValues),
5378 ComSafeArrayOut(LONG64, aTimestamps),
5379 ComSafeArrayOut(BSTR, aFlags))
5380{
5381 HRESULT rc;
5382 ComPtr<IInternalSessionControl> directControl;
5383 directControl = mData->mSession.mDirectControl;
5384
5385 if (!directControl)
5386 rc = E_ACCESSDENIED;
5387 else
5388 rc = directControl->EnumerateGuestProperties
5389 (aPatterns, ComSafeArrayOutArg(aNames),
5390 ComSafeArrayOutArg(aValues),
5391 ComSafeArrayOutArg(aTimestamps),
5392 ComSafeArrayOutArg(aFlags));
5393 return rc;
5394}
5395#endif // VBOX_WITH_GUEST_PROPS
5396
5397STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
5398 ComSafeArrayOut(BSTR, aNames),
5399 ComSafeArrayOut(BSTR, aValues),
5400 ComSafeArrayOut(LONG64, aTimestamps),
5401 ComSafeArrayOut(BSTR, aFlags))
5402{
5403#ifndef VBOX_WITH_GUEST_PROPS
5404 ReturnComNotImplemented();
5405#else // VBOX_WITH_GUEST_PROPS
5406 CheckComArgMaybeNull(aPatterns);
5407 CheckComArgOutSafeArrayPointerValid(aNames);
5408 CheckComArgOutSafeArrayPointerValid(aValues);
5409 CheckComArgOutSafeArrayPointerValid(aTimestamps);
5410 CheckComArgOutSafeArrayPointerValid(aFlags);
5411
5412 AutoCaller autoCaller(this);
5413 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5414
5415 HRESULT rc = enumerateGuestPropertiesOnVM
5416 (aPatterns, ComSafeArrayOutArg(aNames),
5417 ComSafeArrayOutArg(aValues),
5418 ComSafeArrayOutArg(aTimestamps),
5419 ComSafeArrayOutArg(aFlags));
5420 if (rc == E_ACCESSDENIED)
5421 /* The VM is not running or the service is not (yet) accessible */
5422 rc = enumerateGuestPropertiesInService
5423 (aPatterns, ComSafeArrayOutArg(aNames),
5424 ComSafeArrayOutArg(aValues),
5425 ComSafeArrayOutArg(aTimestamps),
5426 ComSafeArrayOutArg(aFlags));
5427 return rc;
5428#endif // VBOX_WITH_GUEST_PROPS
5429}
5430
5431STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
5432 ComSafeArrayOut(IMediumAttachment*, aAttachments))
5433{
5434 MediaData::AttachmentList atts;
5435
5436 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
5437 if (FAILED(rc)) return rc;
5438
5439 SafeIfaceArray<IMediumAttachment> attachments(atts);
5440 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
5441
5442 return S_OK;
5443}
5444
5445STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
5446 LONG aControllerPort,
5447 LONG aDevice,
5448 IMediumAttachment **aAttachment)
5449{
5450 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
5451 aControllerName, aControllerPort, aDevice));
5452
5453 CheckComArgStrNotEmptyOrNull(aControllerName);
5454 CheckComArgOutPointerValid(aAttachment);
5455
5456 AutoCaller autoCaller(this);
5457 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5458
5459 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5460
5461 *aAttachment = NULL;
5462
5463 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
5464 aControllerName,
5465 aControllerPort,
5466 aDevice);
5467 if (pAttach.isNull())
5468 return setError(VBOX_E_OBJECT_NOT_FOUND,
5469 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
5470 aDevice, aControllerPort, aControllerName);
5471
5472 pAttach.queryInterfaceTo(aAttachment);
5473
5474 return S_OK;
5475}
5476
5477STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
5478 StorageBus_T aConnectionType,
5479 IStorageController **controller)
5480{
5481 CheckComArgStrNotEmptyOrNull(aName);
5482
5483 if ( (aConnectionType <= StorageBus_Null)
5484 || (aConnectionType > StorageBus_SAS))
5485 return setError(E_INVALIDARG,
5486 tr("Invalid connection type: %d"),
5487 aConnectionType);
5488
5489 AutoCaller autoCaller(this);
5490 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5491
5492 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5493
5494 HRESULT rc = checkStateDependency(MutableStateDep);
5495 if (FAILED(rc)) return rc;
5496
5497 /* try to find one with the name first. */
5498 ComObjPtr<StorageController> ctrl;
5499
5500 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
5501 if (SUCCEEDED(rc))
5502 return setError(VBOX_E_OBJECT_IN_USE,
5503 tr("Storage controller named '%ls' already exists"),
5504 aName);
5505
5506 ctrl.createObject();
5507
5508 /* get a new instance number for the storage controller */
5509 ULONG ulInstance = 0;
5510 bool fBootable = true;
5511 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5512 it != mStorageControllers->end();
5513 ++it)
5514 {
5515 if ((*it)->getStorageBus() == aConnectionType)
5516 {
5517 ULONG ulCurInst = (*it)->getInstance();
5518
5519 if (ulCurInst >= ulInstance)
5520 ulInstance = ulCurInst + 1;
5521
5522 /* Only one controller of each type can be marked as bootable. */
5523 if ((*it)->getBootable())
5524 fBootable = false;
5525 }
5526 }
5527
5528 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
5529 if (FAILED(rc)) return rc;
5530
5531 setModified(IsModified_Storage);
5532 mStorageControllers.backup();
5533 mStorageControllers->push_back(ctrl);
5534
5535 ctrl.queryInterfaceTo(controller);
5536
5537 /* inform the direct session if any */
5538 alock.leave();
5539 onStorageControllerChange();
5540
5541 return S_OK;
5542}
5543
5544STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
5545 IStorageController **aStorageController)
5546{
5547 CheckComArgStrNotEmptyOrNull(aName);
5548
5549 AutoCaller autoCaller(this);
5550 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5551
5552 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5553
5554 ComObjPtr<StorageController> ctrl;
5555
5556 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5557 if (SUCCEEDED(rc))
5558 ctrl.queryInterfaceTo(aStorageController);
5559
5560 return rc;
5561}
5562
5563STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
5564 IStorageController **aStorageController)
5565{
5566 AutoCaller autoCaller(this);
5567 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5568
5569 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5570
5571 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5572 it != mStorageControllers->end();
5573 ++it)
5574 {
5575 if ((*it)->getInstance() == aInstance)
5576 {
5577 (*it).queryInterfaceTo(aStorageController);
5578 return S_OK;
5579 }
5580 }
5581
5582 return setError(VBOX_E_OBJECT_NOT_FOUND,
5583 tr("Could not find a storage controller with instance number '%lu'"),
5584 aInstance);
5585}
5586
5587STDMETHODIMP Machine::SetStorageControllerBootable(IN_BSTR aName, BOOL fBootable)
5588{
5589 AutoCaller autoCaller(this);
5590 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5591
5592 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5593
5594 HRESULT rc = checkStateDependency(MutableStateDep);
5595 if (FAILED(rc)) return rc;
5596
5597 ComObjPtr<StorageController> ctrl;
5598
5599 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5600 if (SUCCEEDED(rc))
5601 {
5602 /* Ensure that only one controller of each type is marked as bootable. */
5603 if (fBootable == TRUE)
5604 {
5605 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5606 it != mStorageControllers->end();
5607 ++it)
5608 {
5609 ComObjPtr<StorageController> aCtrl = (*it);
5610
5611 if ( (aCtrl->getName() != Utf8Str(aName))
5612 && aCtrl->getBootable() == TRUE
5613 && aCtrl->getStorageBus() == ctrl->getStorageBus()
5614 && aCtrl->getControllerType() == ctrl->getControllerType())
5615 {
5616 aCtrl->setBootable(FALSE);
5617 break;
5618 }
5619 }
5620 }
5621
5622 if (SUCCEEDED(rc))
5623 {
5624 ctrl->setBootable(fBootable);
5625 setModified(IsModified_Storage);
5626 }
5627 }
5628
5629 if (SUCCEEDED(rc))
5630 {
5631 /* inform the direct session if any */
5632 alock.leave();
5633 onStorageControllerChange();
5634 }
5635
5636 return rc;
5637}
5638
5639STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5640{
5641 CheckComArgStrNotEmptyOrNull(aName);
5642
5643 AutoCaller autoCaller(this);
5644 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5645
5646 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5647
5648 HRESULT rc = checkStateDependency(MutableStateDep);
5649 if (FAILED(rc)) return rc;
5650
5651 ComObjPtr<StorageController> ctrl;
5652 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5653 if (FAILED(rc)) return rc;
5654
5655 /* We can remove the controller only if there is no device attached. */
5656 /* check if the device slot is already busy */
5657 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5658 it != mMediaData->mAttachments.end();
5659 ++it)
5660 {
5661 if ((*it)->getControllerName() == aName)
5662 return setError(VBOX_E_OBJECT_IN_USE,
5663 tr("Storage controller named '%ls' has still devices attached"),
5664 aName);
5665 }
5666
5667 /* We can remove it now. */
5668 setModified(IsModified_Storage);
5669 mStorageControllers.backup();
5670
5671 ctrl->unshare();
5672
5673 mStorageControllers->remove(ctrl);
5674
5675 /* inform the direct session if any */
5676 alock.leave();
5677 onStorageControllerChange();
5678
5679 return S_OK;
5680}
5681
5682STDMETHODIMP Machine::QuerySavedGuestSize(ULONG uScreenId, ULONG *puWidth, ULONG *puHeight)
5683{
5684 LogFlowThisFunc(("\n"));
5685
5686 CheckComArgNotNull(puWidth);
5687 CheckComArgNotNull(puHeight);
5688
5689 uint32_t u32Width = 0;
5690 uint32_t u32Height = 0;
5691
5692 int vrc = readSavedGuestSize(mSSData->strStateFilePath, uScreenId, &u32Width, &u32Height);
5693 if (RT_FAILURE(vrc))
5694 return setError(VBOX_E_IPRT_ERROR,
5695 tr("Saved guest size is not available (%Rrc)"),
5696 vrc);
5697
5698 *puWidth = u32Width;
5699 *puHeight = u32Height;
5700
5701 return S_OK;
5702}
5703
5704STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5705{
5706 LogFlowThisFunc(("\n"));
5707
5708 CheckComArgNotNull(aSize);
5709 CheckComArgNotNull(aWidth);
5710 CheckComArgNotNull(aHeight);
5711
5712 if (aScreenId != 0)
5713 return E_NOTIMPL;
5714
5715 AutoCaller autoCaller(this);
5716 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5717
5718 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5719
5720 uint8_t *pu8Data = NULL;
5721 uint32_t cbData = 0;
5722 uint32_t u32Width = 0;
5723 uint32_t u32Height = 0;
5724
5725 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5726
5727 if (RT_FAILURE(vrc))
5728 return setError(VBOX_E_IPRT_ERROR,
5729 tr("Saved screenshot data is not available (%Rrc)"),
5730 vrc);
5731
5732 *aSize = cbData;
5733 *aWidth = u32Width;
5734 *aHeight = u32Height;
5735
5736 freeSavedDisplayScreenshot(pu8Data);
5737
5738 return S_OK;
5739}
5740
5741STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5742{
5743 LogFlowThisFunc(("\n"));
5744
5745 CheckComArgNotNull(aWidth);
5746 CheckComArgNotNull(aHeight);
5747 CheckComArgOutSafeArrayPointerValid(aData);
5748
5749 if (aScreenId != 0)
5750 return E_NOTIMPL;
5751
5752 AutoCaller autoCaller(this);
5753 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5754
5755 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5756
5757 uint8_t *pu8Data = NULL;
5758 uint32_t cbData = 0;
5759 uint32_t u32Width = 0;
5760 uint32_t u32Height = 0;
5761
5762 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5763
5764 if (RT_FAILURE(vrc))
5765 return setError(VBOX_E_IPRT_ERROR,
5766 tr("Saved screenshot data is not available (%Rrc)"),
5767 vrc);
5768
5769 *aWidth = u32Width;
5770 *aHeight = u32Height;
5771
5772 com::SafeArray<BYTE> bitmap(cbData);
5773 /* Convert pixels to format expected by the API caller. */
5774 if (aBGR)
5775 {
5776 /* [0] B, [1] G, [2] R, [3] A. */
5777 for (unsigned i = 0; i < cbData; i += 4)
5778 {
5779 bitmap[i] = pu8Data[i];
5780 bitmap[i + 1] = pu8Data[i + 1];
5781 bitmap[i + 2] = pu8Data[i + 2];
5782 bitmap[i + 3] = 0xff;
5783 }
5784 }
5785 else
5786 {
5787 /* [0] R, [1] G, [2] B, [3] A. */
5788 for (unsigned i = 0; i < cbData; i += 4)
5789 {
5790 bitmap[i] = pu8Data[i + 2];
5791 bitmap[i + 1] = pu8Data[i + 1];
5792 bitmap[i + 2] = pu8Data[i];
5793 bitmap[i + 3] = 0xff;
5794 }
5795 }
5796 bitmap.detachTo(ComSafeArrayOutArg(aData));
5797
5798 freeSavedDisplayScreenshot(pu8Data);
5799
5800 return S_OK;
5801}
5802
5803
5804STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5805{
5806 LogFlowThisFunc(("\n"));
5807
5808 CheckComArgNotNull(aWidth);
5809 CheckComArgNotNull(aHeight);
5810 CheckComArgOutSafeArrayPointerValid(aData);
5811
5812 if (aScreenId != 0)
5813 return E_NOTIMPL;
5814
5815 AutoCaller autoCaller(this);
5816 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5817
5818 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5819
5820 uint8_t *pu8Data = NULL;
5821 uint32_t cbData = 0;
5822 uint32_t u32Width = 0;
5823 uint32_t u32Height = 0;
5824
5825 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5826
5827 if (RT_FAILURE(vrc))
5828 return setError(VBOX_E_IPRT_ERROR,
5829 tr("Saved screenshot data is not available (%Rrc)"),
5830 vrc);
5831
5832 *aWidth = u32Width;
5833 *aHeight = u32Height;
5834
5835 uint8_t *pu8PNG = NULL;
5836 uint32_t cbPNG = 0;
5837 uint32_t cxPNG = 0;
5838 uint32_t cyPNG = 0;
5839
5840 DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
5841
5842 com::SafeArray<BYTE> screenData(cbPNG);
5843 screenData.initFrom(pu8PNG, cbPNG);
5844 RTMemFree(pu8PNG);
5845
5846 screenData.detachTo(ComSafeArrayOutArg(aData));
5847
5848 freeSavedDisplayScreenshot(pu8Data);
5849
5850 return S_OK;
5851}
5852
5853STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5854{
5855 LogFlowThisFunc(("\n"));
5856
5857 CheckComArgNotNull(aSize);
5858 CheckComArgNotNull(aWidth);
5859 CheckComArgNotNull(aHeight);
5860
5861 if (aScreenId != 0)
5862 return E_NOTIMPL;
5863
5864 AutoCaller autoCaller(this);
5865 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5866
5867 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5868
5869 uint8_t *pu8Data = NULL;
5870 uint32_t cbData = 0;
5871 uint32_t u32Width = 0;
5872 uint32_t u32Height = 0;
5873
5874 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5875
5876 if (RT_FAILURE(vrc))
5877 return setError(VBOX_E_IPRT_ERROR,
5878 tr("Saved screenshot data is not available (%Rrc)"),
5879 vrc);
5880
5881 *aSize = cbData;
5882 *aWidth = u32Width;
5883 *aHeight = u32Height;
5884
5885 freeSavedDisplayScreenshot(pu8Data);
5886
5887 return S_OK;
5888}
5889
5890STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5891{
5892 LogFlowThisFunc(("\n"));
5893
5894 CheckComArgNotNull(aWidth);
5895 CheckComArgNotNull(aHeight);
5896 CheckComArgOutSafeArrayPointerValid(aData);
5897
5898 if (aScreenId != 0)
5899 return E_NOTIMPL;
5900
5901 AutoCaller autoCaller(this);
5902 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5903
5904 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5905
5906 uint8_t *pu8Data = NULL;
5907 uint32_t cbData = 0;
5908 uint32_t u32Width = 0;
5909 uint32_t u32Height = 0;
5910
5911 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5912
5913 if (RT_FAILURE(vrc))
5914 return setError(VBOX_E_IPRT_ERROR,
5915 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
5916 vrc);
5917
5918 *aWidth = u32Width;
5919 *aHeight = u32Height;
5920
5921 com::SafeArray<BYTE> png(cbData);
5922 png.initFrom(pu8Data, cbData);
5923 png.detachTo(ComSafeArrayOutArg(aData));
5924
5925 freeSavedDisplayScreenshot(pu8Data);
5926
5927 return S_OK;
5928}
5929
5930STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5931{
5932 HRESULT rc = S_OK;
5933 LogFlowThisFunc(("\n"));
5934
5935 AutoCaller autoCaller(this);
5936 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5937
5938 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5939
5940 if (!mHWData->mCPUHotPlugEnabled)
5941 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5942
5943 if (aCpu >= mHWData->mCPUCount)
5944 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5945
5946 if (mHWData->mCPUAttached[aCpu])
5947 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5948
5949 alock.release();
5950 rc = onCPUChange(aCpu, false);
5951 alock.acquire();
5952 if (FAILED(rc)) return rc;
5953
5954 setModified(IsModified_MachineData);
5955 mHWData.backup();
5956 mHWData->mCPUAttached[aCpu] = true;
5957
5958 /* Save settings if online */
5959 if (Global::IsOnline(mData->mMachineState))
5960 saveSettings(NULL);
5961
5962 return S_OK;
5963}
5964
5965STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5966{
5967 HRESULT rc = S_OK;
5968 LogFlowThisFunc(("\n"));
5969
5970 AutoCaller autoCaller(this);
5971 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5972
5973 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5974
5975 if (!mHWData->mCPUHotPlugEnabled)
5976 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5977
5978 if (aCpu >= SchemaDefs::MaxCPUCount)
5979 return setError(E_INVALIDARG,
5980 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5981 SchemaDefs::MaxCPUCount);
5982
5983 if (!mHWData->mCPUAttached[aCpu])
5984 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5985
5986 /* CPU 0 can't be detached */
5987 if (aCpu == 0)
5988 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5989
5990 alock.release();
5991 rc = onCPUChange(aCpu, true);
5992 alock.acquire();
5993 if (FAILED(rc)) return rc;
5994
5995 setModified(IsModified_MachineData);
5996 mHWData.backup();
5997 mHWData->mCPUAttached[aCpu] = false;
5998
5999 /* Save settings if online */
6000 if (Global::IsOnline(mData->mMachineState))
6001 saveSettings(NULL);
6002
6003 return S_OK;
6004}
6005
6006STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
6007{
6008 LogFlowThisFunc(("\n"));
6009
6010 CheckComArgNotNull(aCpuAttached);
6011
6012 *aCpuAttached = false;
6013
6014 AutoCaller autoCaller(this);
6015 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6016
6017 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6018
6019 /* If hotplug is enabled the CPU is always enabled. */
6020 if (!mHWData->mCPUHotPlugEnabled)
6021 {
6022 if (aCpu < mHWData->mCPUCount)
6023 *aCpuAttached = true;
6024 }
6025 else
6026 {
6027 if (aCpu < SchemaDefs::MaxCPUCount)
6028 *aCpuAttached = mHWData->mCPUAttached[aCpu];
6029 }
6030
6031 return S_OK;
6032}
6033
6034STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
6035{
6036 CheckComArgOutPointerValid(aName);
6037
6038 AutoCaller autoCaller(this);
6039 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6040
6041 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6042
6043 Utf8Str log = queryLogFilename(aIdx);
6044 if (!RTFileExists(log.c_str()))
6045 log.setNull();
6046 log.cloneTo(aName);
6047
6048 return S_OK;
6049}
6050
6051STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
6052{
6053 LogFlowThisFunc(("\n"));
6054 CheckComArgOutSafeArrayPointerValid(aData);
6055 if (aSize < 0)
6056 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
6057
6058 AutoCaller autoCaller(this);
6059 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6060
6061 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6062
6063 HRESULT rc = S_OK;
6064 Utf8Str log = queryLogFilename(aIdx);
6065
6066 /* do not unnecessarily hold the lock while doing something which does
6067 * not need the lock and potentially takes a long time. */
6068 alock.release();
6069
6070 /* Limit the chunk size to 32K for now, as that gives better performance
6071 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
6072 * One byte expands to approx. 25 bytes of breathtaking XML. */
6073 size_t cbData = (size_t)RT_MIN(aSize, 32768);
6074 com::SafeArray<BYTE> logData(cbData);
6075
6076 RTFILE LogFile;
6077 int vrc = RTFileOpen(&LogFile, log.c_str(),
6078 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
6079 if (RT_SUCCESS(vrc))
6080 {
6081 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
6082 if (RT_SUCCESS(vrc))
6083 logData.resize(cbData);
6084 else
6085 rc = setError(VBOX_E_IPRT_ERROR,
6086 tr("Could not read log file '%s' (%Rrc)"),
6087 log.c_str(), vrc);
6088 RTFileClose(LogFile);
6089 }
6090 else
6091 rc = setError(VBOX_E_IPRT_ERROR,
6092 tr("Could not open log file '%s' (%Rrc)"),
6093 log.c_str(), vrc);
6094
6095 if (FAILED(rc))
6096 logData.resize(0);
6097 logData.detachTo(ComSafeArrayOutArg(aData));
6098
6099 return rc;
6100}
6101
6102
6103/**
6104 * Currently this method doesn't attach device to the running VM,
6105 * just makes sure it's plugged on next VM start.
6106 */
6107STDMETHODIMP Machine::AttachHostPciDevice(LONG hostAddress, LONG desiredGuestAddress, BOOL /*tryToUnbind*/)
6108{
6109 AutoCaller autoCaller(this);
6110 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6111
6112 // lock scope
6113 {
6114 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6115
6116 HRESULT rc = checkStateDependency(MutableStateDep);
6117 if (FAILED(rc)) return rc;
6118
6119 ChipsetType_T aChipset = ChipsetType_PIIX3;
6120 COMGETTER(ChipsetType)(&aChipset);
6121
6122 if (aChipset != ChipsetType_ICH9)
6123 {
6124 return setError(E_INVALIDARG,
6125 tr("Host PCI attachment only supported with ICH9 chipset"));
6126 }
6127
6128 // check if device with this host PCI address already attached
6129 for (HWData::PciDeviceAssignmentList::iterator it = mHWData->mPciDeviceAssignments.begin();
6130 it != mHWData->mPciDeviceAssignments.end();
6131 ++it)
6132 {
6133 LONG iHostAddress = -1;
6134 ComPtr<PciDeviceAttachment> pAttach;
6135 pAttach = *it;
6136 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6137 if (iHostAddress == hostAddress)
6138 return setError(E_INVALIDARG,
6139 tr("Device with host PCI address already attached to this VM"));
6140 }
6141
6142 ComObjPtr<PciDeviceAttachment> pda;
6143 char name[32];
6144
6145 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (hostAddress>>8) & 0xff, (hostAddress & 0xf8) >> 3, hostAddress & 7);
6146 Bstr bname(name);
6147 pda.createObject();
6148 pda->init(this, bname, hostAddress, desiredGuestAddress, TRUE);
6149 setModified(IsModified_MachineData);
6150 mHWData.backup();
6151 mHWData->mPciDeviceAssignments.push_back(pda);
6152 }
6153
6154 return S_OK;
6155}
6156
6157/**
6158 * Currently this method doesn't detach device from the running VM,
6159 * just makes sure it's not plugged on next VM start.
6160 */
6161STDMETHODIMP Machine::DetachHostPciDevice(LONG hostAddress)
6162{
6163 AutoCaller autoCaller(this);
6164 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6165
6166 ComObjPtr<PciDeviceAttachment> pAttach;
6167 bool fRemoved = false;
6168 HRESULT rc;
6169
6170 // lock scope
6171 {
6172 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6173
6174 rc = checkStateDependency(MutableStateDep);
6175 if (FAILED(rc)) return rc;
6176
6177 for (HWData::PciDeviceAssignmentList::iterator it = mHWData->mPciDeviceAssignments.begin();
6178 it != mHWData->mPciDeviceAssignments.end();
6179 ++it)
6180 {
6181 LONG iHostAddress = -1;
6182 pAttach = *it;
6183 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6184 if (iHostAddress != -1 && iHostAddress == hostAddress)
6185 {
6186 setModified(IsModified_MachineData);
6187 mHWData.backup();
6188 mHWData->mPciDeviceAssignments.remove(pAttach);
6189 fRemoved = true;
6190 break;
6191 }
6192 }
6193 }
6194
6195
6196 /* Fire event outside of the lock */
6197 if (fRemoved)
6198 {
6199 Assert(!pAttach.isNull());
6200 ComPtr<IEventSource> es;
6201 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
6202 Assert(SUCCEEDED(rc));
6203 Bstr mid;
6204 rc = this->COMGETTER(Id)(mid.asOutParam());
6205 Assert(SUCCEEDED(rc));
6206 fireHostPciDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
6207 }
6208
6209 return fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
6210 tr("No host PCI device %08x attached"),
6211 hostAddress
6212 );
6213}
6214
6215STDMETHODIMP Machine::COMGETTER(PciDeviceAssignments)(ComSafeArrayOut(IPciDeviceAttachment *, aAssignments))
6216{
6217 CheckComArgOutSafeArrayPointerValid(aAssignments);
6218
6219 AutoCaller autoCaller(this);
6220 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6221
6222 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6223
6224 SafeIfaceArray<IPciDeviceAttachment> assignments(mHWData->mPciDeviceAssignments);
6225 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
6226
6227 return S_OK;
6228}
6229
6230STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
6231{
6232 CheckComArgOutPointerValid(aBandwidthControl);
6233
6234 AutoCaller autoCaller(this);
6235 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6236
6237 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
6238
6239 return S_OK;
6240}
6241
6242STDMETHODIMP Machine::CloneTo(IMachine *pTarget, CloneMode_T mode, ComSafeArrayIn(CloneOptions_T, options), IProgress **pProgress)
6243{
6244 LogFlowFuncEnter();
6245
6246 CheckComArgNotNull(pTarget);
6247 CheckComArgOutPointerValid(pProgress);
6248
6249 /* Convert the options. */
6250 RTCList<CloneOptions_T> optList;
6251 if (options != NULL)
6252 optList = com::SafeArray<CloneOptions_T>(ComSafeArrayInArg(options)).toList();
6253
6254 if (optList.contains(CloneOptions_Link))
6255 {
6256 if (!isSnapshotMachine())
6257 return setError(E_INVALIDARG,
6258 tr("Linked clone can only be created from a snapshot"));
6259 if (mode != CloneMode_MachineState)
6260 return setError(E_INVALIDARG,
6261 tr("Linked clone can only be created for a single machine state"));
6262 }
6263 AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_INVALIDARG);
6264
6265 AutoCaller autoCaller(this);
6266 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6267
6268
6269 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), mode, optList);
6270
6271 HRESULT rc = pWorker->start(pProgress);
6272
6273 LogFlowFuncLeave();
6274
6275 return rc;
6276}
6277
6278// public methods for internal purposes
6279/////////////////////////////////////////////////////////////////////////////
6280
6281/**
6282 * Adds the given IsModified_* flag to the dirty flags of the machine.
6283 * This must be called either during loadSettings or under the machine write lock.
6284 * @param fl
6285 */
6286void Machine::setModified(uint32_t fl)
6287{
6288 mData->flModifications |= fl;
6289}
6290
6291/**
6292 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
6293 * care of the write locking.
6294 *
6295 * @param fModifications The flag to add.
6296 */
6297void Machine::setModifiedLock(uint32_t fModification)
6298{
6299 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6300 mData->flModifications |= fModification;
6301}
6302
6303/**
6304 * Saves the registry entry of this machine to the given configuration node.
6305 *
6306 * @param aEntryNode Node to save the registry entry to.
6307 *
6308 * @note locks this object for reading.
6309 */
6310HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
6311{
6312 AutoLimitedCaller autoCaller(this);
6313 AssertComRCReturnRC(autoCaller.rc());
6314
6315 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6316
6317 data.uuid = mData->mUuid;
6318 data.strSettingsFile = mData->m_strConfigFile;
6319
6320 return S_OK;
6321}
6322
6323/**
6324 * Calculates the absolute path of the given path taking the directory of the
6325 * machine settings file as the current directory.
6326 *
6327 * @param aPath Path to calculate the absolute path for.
6328 * @param aResult Where to put the result (used only on success, can be the
6329 * same Utf8Str instance as passed in @a aPath).
6330 * @return IPRT result.
6331 *
6332 * @note Locks this object for reading.
6333 */
6334int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
6335{
6336 AutoCaller autoCaller(this);
6337 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6338
6339 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6340
6341 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
6342
6343 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
6344
6345 strSettingsDir.stripFilename();
6346 char folder[RTPATH_MAX];
6347 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
6348 if (RT_SUCCESS(vrc))
6349 aResult = folder;
6350
6351 return vrc;
6352}
6353
6354/**
6355 * Copies strSource to strTarget, making it relative to the machine folder
6356 * if it is a subdirectory thereof, or simply copying it otherwise.
6357 *
6358 * @param strSource Path to evaluate and copy.
6359 * @param strTarget Buffer to receive target path.
6360 *
6361 * @note Locks this object for reading.
6362 */
6363void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6364 Utf8Str &strTarget)
6365{
6366 AutoCaller autoCaller(this);
6367 AssertComRCReturn(autoCaller.rc(), (void)0);
6368
6369 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6370
6371 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6372 // use strTarget as a temporary buffer to hold the machine settings dir
6373 strTarget = mData->m_strConfigFileFull;
6374 strTarget.stripFilename();
6375 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6376 {
6377 // is relative: then append what's left
6378 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6379 // for empty paths (only possible for subdirs) use "." to avoid
6380 // triggering default settings for not present config attributes.
6381 if (strTarget.isEmpty())
6382 strTarget = ".";
6383 }
6384 else
6385 // is not relative: then overwrite
6386 strTarget = strSource;
6387}
6388
6389/**
6390 * Returns the full path to the machine's log folder in the
6391 * \a aLogFolder argument.
6392 */
6393void Machine::getLogFolder(Utf8Str &aLogFolder)
6394{
6395 AutoCaller autoCaller(this);
6396 AssertComRCReturnVoid(autoCaller.rc());
6397
6398 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6399
6400 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6401 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6402 aLogFolder.append(RTPATH_DELIMITER);
6403 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6404}
6405
6406/**
6407 * Returns the full path to the machine's log file for an given index.
6408 */
6409Utf8Str Machine::queryLogFilename(ULONG idx)
6410{
6411 Utf8Str logFolder;
6412 getLogFolder(logFolder);
6413 Assert(logFolder.length());
6414 Utf8Str log;
6415 if (idx == 0)
6416 log = Utf8StrFmt("%s%cVBox.log",
6417 logFolder.c_str(), RTPATH_DELIMITER);
6418 else
6419 log = Utf8StrFmt("%s%cVBox.log.%d",
6420 logFolder.c_str(), RTPATH_DELIMITER, idx);
6421 return log;
6422}
6423
6424/**
6425 * Composes a unique saved state filename based on the current system time. The filename is
6426 * granular to the second so this will work so long as no more than one snapshot is taken on
6427 * a machine per second.
6428 *
6429 * Before version 4.1, we used this formula for saved state files:
6430 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6431 * which no longer works because saved state files can now be shared between the saved state of the
6432 * "saved" machine and an online snapshot, and the following would cause problems:
6433 * 1) save machine
6434 * 2) create online snapshot from that machine state --> reusing saved state file
6435 * 3) save machine again --> filename would be reused, breaking the online snapshot
6436 *
6437 * So instead we now use a timestamp.
6438 *
6439 * @param str
6440 */
6441void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6442{
6443 AutoCaller autoCaller(this);
6444 AssertComRCReturnVoid(autoCaller.rc());
6445
6446 {
6447 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6448 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6449 }
6450
6451 RTTIMESPEC ts;
6452 RTTimeNow(&ts);
6453 RTTIME time;
6454 RTTimeExplode(&time, &ts);
6455
6456 strStateFilePath += RTPATH_DELIMITER;
6457 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
6458 time.i32Year, time.u8Month, time.u8MonthDay,
6459 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
6460}
6461
6462/**
6463 * @note Locks this object for writing, calls the client process
6464 * (inside the lock).
6465 */
6466HRESULT Machine::launchVMProcess(IInternalSessionControl *aControl,
6467 const Utf8Str &strType,
6468 const Utf8Str &strEnvironment,
6469 ProgressProxy *aProgress)
6470{
6471 LogFlowThisFuncEnter();
6472
6473 AssertReturn(aControl, E_FAIL);
6474 AssertReturn(aProgress, E_FAIL);
6475
6476 AutoCaller autoCaller(this);
6477 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6478
6479 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6480
6481 if (!mData->mRegistered)
6482 return setError(E_UNEXPECTED,
6483 tr("The machine '%s' is not registered"),
6484 mUserData->s.strName.c_str());
6485
6486 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6487
6488 if ( mData->mSession.mState == SessionState_Locked
6489 || mData->mSession.mState == SessionState_Spawning
6490 || mData->mSession.mState == SessionState_Unlocking)
6491 return setError(VBOX_E_INVALID_OBJECT_STATE,
6492 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6493 mUserData->s.strName.c_str());
6494
6495 /* may not be busy */
6496 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6497
6498 /* get the path to the executable */
6499 char szPath[RTPATH_MAX];
6500 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6501 size_t sz = strlen(szPath);
6502 szPath[sz++] = RTPATH_DELIMITER;
6503 szPath[sz] = 0;
6504 char *cmd = szPath + sz;
6505 sz = RTPATH_MAX - sz;
6506
6507 int vrc = VINF_SUCCESS;
6508 RTPROCESS pid = NIL_RTPROCESS;
6509
6510 RTENV env = RTENV_DEFAULT;
6511
6512 if (!strEnvironment.isEmpty())
6513 {
6514 char *newEnvStr = NULL;
6515
6516 do
6517 {
6518 /* clone the current environment */
6519 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6520 AssertRCBreakStmt(vrc2, vrc = vrc2);
6521
6522 newEnvStr = RTStrDup(strEnvironment.c_str());
6523 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6524
6525 /* put new variables to the environment
6526 * (ignore empty variable names here since RTEnv API
6527 * intentionally doesn't do that) */
6528 char *var = newEnvStr;
6529 for (char *p = newEnvStr; *p; ++p)
6530 {
6531 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6532 {
6533 *p = '\0';
6534 if (*var)
6535 {
6536 char *val = strchr(var, '=');
6537 if (val)
6538 {
6539 *val++ = '\0';
6540 vrc2 = RTEnvSetEx(env, var, val);
6541 }
6542 else
6543 vrc2 = RTEnvUnsetEx(env, var);
6544 if (RT_FAILURE(vrc2))
6545 break;
6546 }
6547 var = p + 1;
6548 }
6549 }
6550 if (RT_SUCCESS(vrc2) && *var)
6551 vrc2 = RTEnvPutEx(env, var);
6552
6553 AssertRCBreakStmt(vrc2, vrc = vrc2);
6554 }
6555 while (0);
6556
6557 if (newEnvStr != NULL)
6558 RTStrFree(newEnvStr);
6559 }
6560
6561 /* Qt is default */
6562#ifdef VBOX_WITH_QTGUI
6563 if (strType == "gui" || strType == "GUI/Qt")
6564 {
6565# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6566 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6567# else
6568 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6569# endif
6570 Assert(sz >= sizeof(VirtualBox_exe));
6571 strcpy(cmd, VirtualBox_exe);
6572
6573 Utf8Str idStr = mData->mUuid.toString();
6574 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6575 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6576 }
6577#else /* !VBOX_WITH_QTGUI */
6578 if (0)
6579 ;
6580#endif /* VBOX_WITH_QTGUI */
6581
6582 else
6583
6584#ifdef VBOX_WITH_VBOXSDL
6585 if (strType == "sdl" || strType == "GUI/SDL")
6586 {
6587 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6588 Assert(sz >= sizeof(VBoxSDL_exe));
6589 strcpy(cmd, VBoxSDL_exe);
6590
6591 Utf8Str idStr = mData->mUuid.toString();
6592 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6593 fprintf(stderr, "SDL=%s\n", szPath);
6594 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6595 }
6596#else /* !VBOX_WITH_VBOXSDL */
6597 if (0)
6598 ;
6599#endif /* !VBOX_WITH_VBOXSDL */
6600
6601 else
6602
6603#ifdef VBOX_WITH_HEADLESS
6604 if ( strType == "headless"
6605 || strType == "capture"
6606 || strType == "vrdp" /* Deprecated. Same as headless. */
6607 )
6608 {
6609 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6610 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6611 * and a VM works even if the server has not been installed.
6612 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6613 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6614 * differently in 4.0 and 3.x.
6615 */
6616 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6617 Assert(sz >= sizeof(VBoxHeadless_exe));
6618 strcpy(cmd, VBoxHeadless_exe);
6619
6620 Utf8Str idStr = mData->mUuid.toString();
6621 /* Leave space for "--capture" arg. */
6622 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
6623 "--startvm", idStr.c_str(),
6624 "--vrde", "config",
6625 0, /* For "--capture". */
6626 0 };
6627 if (strType == "capture")
6628 {
6629 unsigned pos = RT_ELEMENTS(args) - 2;
6630 args[pos] = "--capture";
6631 }
6632 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6633 }
6634#else /* !VBOX_WITH_HEADLESS */
6635 if (0)
6636 ;
6637#endif /* !VBOX_WITH_HEADLESS */
6638 else
6639 {
6640 RTEnvDestroy(env);
6641 return setError(E_INVALIDARG,
6642 tr("Invalid session type: '%s'"),
6643 strType.c_str());
6644 }
6645
6646 RTEnvDestroy(env);
6647
6648 if (RT_FAILURE(vrc))
6649 return setError(VBOX_E_IPRT_ERROR,
6650 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6651 mUserData->s.strName.c_str(), vrc);
6652
6653 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6654
6655 /*
6656 * Note that we don't leave the lock here before calling the client,
6657 * because it doesn't need to call us back if called with a NULL argument.
6658 * Leaving the lock here is dangerous because we didn't prepare the
6659 * launch data yet, but the client we've just started may happen to be
6660 * too fast and call openSession() that will fail (because of PID, etc.),
6661 * so that the Machine will never get out of the Spawning session state.
6662 */
6663
6664 /* inform the session that it will be a remote one */
6665 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6666 HRESULT rc = aControl->AssignMachine(NULL);
6667 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6668
6669 if (FAILED(rc))
6670 {
6671 /* restore the session state */
6672 mData->mSession.mState = SessionState_Unlocked;
6673 /* The failure may occur w/o any error info (from RPC), so provide one */
6674 return setError(VBOX_E_VM_ERROR,
6675 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6676 }
6677
6678 /* attach launch data to the machine */
6679 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6680 mData->mSession.mRemoteControls.push_back (aControl);
6681 mData->mSession.mProgress = aProgress;
6682 mData->mSession.mPid = pid;
6683 mData->mSession.mState = SessionState_Spawning;
6684 mData->mSession.mType = strType;
6685
6686 LogFlowThisFuncLeave();
6687 return S_OK;
6688}
6689
6690/**
6691 * Returns @c true if the given machine has an open direct session and returns
6692 * the session machine instance and additional session data (on some platforms)
6693 * if so.
6694 *
6695 * Note that when the method returns @c false, the arguments remain unchanged.
6696 *
6697 * @param aMachine Session machine object.
6698 * @param aControl Direct session control object (optional).
6699 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6700 *
6701 * @note locks this object for reading.
6702 */
6703#if defined(RT_OS_WINDOWS)
6704bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6705 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6706 HANDLE *aIPCSem /*= NULL*/,
6707 bool aAllowClosing /*= false*/)
6708#elif defined(RT_OS_OS2)
6709bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6710 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6711 HMTX *aIPCSem /*= NULL*/,
6712 bool aAllowClosing /*= false*/)
6713#else
6714bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6715 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6716 bool aAllowClosing /*= false*/)
6717#endif
6718{
6719 AutoLimitedCaller autoCaller(this);
6720 AssertComRCReturn(autoCaller.rc(), false);
6721
6722 /* just return false for inaccessible machines */
6723 if (autoCaller.state() != Ready)
6724 return false;
6725
6726 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6727
6728 if ( mData->mSession.mState == SessionState_Locked
6729 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6730 )
6731 {
6732 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6733
6734 aMachine = mData->mSession.mMachine;
6735
6736 if (aControl != NULL)
6737 *aControl = mData->mSession.mDirectControl;
6738
6739#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6740 /* Additional session data */
6741 if (aIPCSem != NULL)
6742 *aIPCSem = aMachine->mIPCSem;
6743#endif
6744 return true;
6745 }
6746
6747 return false;
6748}
6749
6750/**
6751 * Returns @c true if the given machine has an spawning direct session and
6752 * returns and additional session data (on some platforms) if so.
6753 *
6754 * Note that when the method returns @c false, the arguments remain unchanged.
6755 *
6756 * @param aPID PID of the spawned direct session process.
6757 *
6758 * @note locks this object for reading.
6759 */
6760#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6761bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6762#else
6763bool Machine::isSessionSpawning()
6764#endif
6765{
6766 AutoLimitedCaller autoCaller(this);
6767 AssertComRCReturn(autoCaller.rc(), false);
6768
6769 /* just return false for inaccessible machines */
6770 if (autoCaller.state() != Ready)
6771 return false;
6772
6773 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6774
6775 if (mData->mSession.mState == SessionState_Spawning)
6776 {
6777#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6778 /* Additional session data */
6779 if (aPID != NULL)
6780 {
6781 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6782 *aPID = mData->mSession.mPid;
6783 }
6784#endif
6785 return true;
6786 }
6787
6788 return false;
6789}
6790
6791/**
6792 * Called from the client watcher thread to check for unexpected client process
6793 * death during Session_Spawning state (e.g. before it successfully opened a
6794 * direct session).
6795 *
6796 * On Win32 and on OS/2, this method is called only when we've got the
6797 * direct client's process termination notification, so it always returns @c
6798 * true.
6799 *
6800 * On other platforms, this method returns @c true if the client process is
6801 * terminated and @c false if it's still alive.
6802 *
6803 * @note Locks this object for writing.
6804 */
6805bool Machine::checkForSpawnFailure()
6806{
6807 AutoCaller autoCaller(this);
6808 if (!autoCaller.isOk())
6809 {
6810 /* nothing to do */
6811 LogFlowThisFunc(("Already uninitialized!\n"));
6812 return true;
6813 }
6814
6815 /* VirtualBox::addProcessToReap() needs a write lock */
6816 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6817
6818 if (mData->mSession.mState != SessionState_Spawning)
6819 {
6820 /* nothing to do */
6821 LogFlowThisFunc(("Not spawning any more!\n"));
6822 return true;
6823 }
6824
6825 HRESULT rc = S_OK;
6826
6827#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6828
6829 /* the process was already unexpectedly terminated, we just need to set an
6830 * error and finalize session spawning */
6831 rc = setError(E_FAIL,
6832 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6833 getName().c_str());
6834#else
6835
6836 /* PID not yet initialized, skip check. */
6837 if (mData->mSession.mPid == NIL_RTPROCESS)
6838 return false;
6839
6840 RTPROCSTATUS status;
6841 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6842 &status);
6843
6844 if (vrc != VERR_PROCESS_RUNNING)
6845 {
6846 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6847 rc = setError(E_FAIL,
6848 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6849 getName().c_str(), status.iStatus);
6850 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6851 rc = setError(E_FAIL,
6852 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6853 getName().c_str(), status.iStatus);
6854 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6855 rc = setError(E_FAIL,
6856 tr("The virtual machine '%s' has terminated abnormally"),
6857 getName().c_str(), status.iStatus);
6858 else
6859 rc = setError(E_FAIL,
6860 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6861 getName().c_str(), rc);
6862 }
6863
6864#endif
6865
6866 if (FAILED(rc))
6867 {
6868 /* Close the remote session, remove the remote control from the list
6869 * and reset session state to Closed (@note keep the code in sync with
6870 * the relevant part in checkForSpawnFailure()). */
6871
6872 Assert(mData->mSession.mRemoteControls.size() == 1);
6873 if (mData->mSession.mRemoteControls.size() == 1)
6874 {
6875 ErrorInfoKeeper eik;
6876 mData->mSession.mRemoteControls.front()->Uninitialize();
6877 }
6878
6879 mData->mSession.mRemoteControls.clear();
6880 mData->mSession.mState = SessionState_Unlocked;
6881
6882 /* finalize the progress after setting the state */
6883 if (!mData->mSession.mProgress.isNull())
6884 {
6885 mData->mSession.mProgress->notifyComplete(rc);
6886 mData->mSession.mProgress.setNull();
6887 }
6888
6889 mParent->addProcessToReap(mData->mSession.mPid);
6890 mData->mSession.mPid = NIL_RTPROCESS;
6891
6892 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6893 return true;
6894 }
6895
6896 return false;
6897}
6898
6899/**
6900 * Checks whether the machine can be registered. If so, commits and saves
6901 * all settings.
6902 *
6903 * @note Must be called from mParent's write lock. Locks this object and
6904 * children for writing.
6905 */
6906HRESULT Machine::prepareRegister()
6907{
6908 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6909
6910 AutoLimitedCaller autoCaller(this);
6911 AssertComRCReturnRC(autoCaller.rc());
6912
6913 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6914
6915 /* wait for state dependents to drop to zero */
6916 ensureNoStateDependencies();
6917
6918 if (!mData->mAccessible)
6919 return setError(VBOX_E_INVALID_OBJECT_STATE,
6920 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6921 mUserData->s.strName.c_str(),
6922 mData->mUuid.toString().c_str());
6923
6924 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6925
6926 if (mData->mRegistered)
6927 return setError(VBOX_E_INVALID_OBJECT_STATE,
6928 tr("The machine '%s' with UUID {%s} is already registered"),
6929 mUserData->s.strName.c_str(),
6930 mData->mUuid.toString().c_str());
6931
6932 HRESULT rc = S_OK;
6933
6934 // Ensure the settings are saved. If we are going to be registered and
6935 // no config file exists yet, create it by calling saveSettings() too.
6936 if ( (mData->flModifications)
6937 || (!mData->pMachineConfigFile->fileExists())
6938 )
6939 {
6940 rc = saveSettings(NULL);
6941 // no need to check whether VirtualBox.xml needs saving too since
6942 // we can't have a machine XML file rename pending
6943 if (FAILED(rc)) return rc;
6944 }
6945
6946 /* more config checking goes here */
6947
6948 if (SUCCEEDED(rc))
6949 {
6950 /* we may have had implicit modifications we want to fix on success */
6951 commit();
6952
6953 mData->mRegistered = true;
6954 }
6955 else
6956 {
6957 /* we may have had implicit modifications we want to cancel on failure*/
6958 rollback(false /* aNotify */);
6959 }
6960
6961 return rc;
6962}
6963
6964/**
6965 * Increases the number of objects dependent on the machine state or on the
6966 * registered state. Guarantees that these two states will not change at least
6967 * until #releaseStateDependency() is called.
6968 *
6969 * Depending on the @a aDepType value, additional state checks may be made.
6970 * These checks will set extended error info on failure. See
6971 * #checkStateDependency() for more info.
6972 *
6973 * If this method returns a failure, the dependency is not added and the caller
6974 * is not allowed to rely on any particular machine state or registration state
6975 * value and may return the failed result code to the upper level.
6976 *
6977 * @param aDepType Dependency type to add.
6978 * @param aState Current machine state (NULL if not interested).
6979 * @param aRegistered Current registered state (NULL if not interested).
6980 *
6981 * @note Locks this object for writing.
6982 */
6983HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6984 MachineState_T *aState /* = NULL */,
6985 BOOL *aRegistered /* = NULL */)
6986{
6987 AutoCaller autoCaller(this);
6988 AssertComRCReturnRC(autoCaller.rc());
6989
6990 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6991
6992 HRESULT rc = checkStateDependency(aDepType);
6993 if (FAILED(rc)) return rc;
6994
6995 {
6996 if (mData->mMachineStateChangePending != 0)
6997 {
6998 /* ensureNoStateDependencies() is waiting for state dependencies to
6999 * drop to zero so don't add more. It may make sense to wait a bit
7000 * and retry before reporting an error (since the pending state
7001 * transition should be really quick) but let's just assert for
7002 * now to see if it ever happens on practice. */
7003
7004 AssertFailed();
7005
7006 return setError(E_ACCESSDENIED,
7007 tr("Machine state change is in progress. Please retry the operation later."));
7008 }
7009
7010 ++mData->mMachineStateDeps;
7011 Assert(mData->mMachineStateDeps != 0 /* overflow */);
7012 }
7013
7014 if (aState)
7015 *aState = mData->mMachineState;
7016 if (aRegistered)
7017 *aRegistered = mData->mRegistered;
7018
7019 return S_OK;
7020}
7021
7022/**
7023 * Decreases the number of objects dependent on the machine state.
7024 * Must always complete the #addStateDependency() call after the state
7025 * dependency is no more necessary.
7026 */
7027void Machine::releaseStateDependency()
7028{
7029 AutoCaller autoCaller(this);
7030 AssertComRCReturnVoid(autoCaller.rc());
7031
7032 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7033
7034 /* releaseStateDependency() w/o addStateDependency()? */
7035 AssertReturnVoid(mData->mMachineStateDeps != 0);
7036 -- mData->mMachineStateDeps;
7037
7038 if (mData->mMachineStateDeps == 0)
7039 {
7040 /* inform ensureNoStateDependencies() that there are no more deps */
7041 if (mData->mMachineStateChangePending != 0)
7042 {
7043 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
7044 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
7045 }
7046 }
7047}
7048
7049// protected methods
7050/////////////////////////////////////////////////////////////////////////////
7051
7052/**
7053 * Performs machine state checks based on the @a aDepType value. If a check
7054 * fails, this method will set extended error info, otherwise it will return
7055 * S_OK. It is supposed, that on failure, the caller will immediately return
7056 * the return value of this method to the upper level.
7057 *
7058 * When @a aDepType is AnyStateDep, this method always returns S_OK.
7059 *
7060 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
7061 * current state of this machine object allows to change settings of the
7062 * machine (i.e. the machine is not registered, or registered but not running
7063 * and not saved). It is useful to call this method from Machine setters
7064 * before performing any change.
7065 *
7066 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
7067 * as for MutableStateDep except that if the machine is saved, S_OK is also
7068 * returned. This is useful in setters which allow changing machine
7069 * properties when it is in the saved state.
7070 *
7071 * @param aDepType Dependency type to check.
7072 *
7073 * @note Non Machine based classes should use #addStateDependency() and
7074 * #releaseStateDependency() methods or the smart AutoStateDependency
7075 * template.
7076 *
7077 * @note This method must be called from under this object's read or write
7078 * lock.
7079 */
7080HRESULT Machine::checkStateDependency(StateDependency aDepType)
7081{
7082 switch (aDepType)
7083 {
7084 case AnyStateDep:
7085 {
7086 break;
7087 }
7088 case MutableStateDep:
7089 {
7090 if ( mData->mRegistered
7091 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
7092 || ( mData->mMachineState != MachineState_Paused
7093 && mData->mMachineState != MachineState_Running
7094 && mData->mMachineState != MachineState_Aborted
7095 && mData->mMachineState != MachineState_Teleported
7096 && mData->mMachineState != MachineState_PoweredOff
7097 )
7098 )
7099 )
7100 return setError(VBOX_E_INVALID_VM_STATE,
7101 tr("The machine is not mutable (state is %s)"),
7102 Global::stringifyMachineState(mData->mMachineState));
7103 break;
7104 }
7105 case MutableOrSavedStateDep:
7106 {
7107 if ( mData->mRegistered
7108 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
7109 || ( mData->mMachineState != MachineState_Paused
7110 && mData->mMachineState != MachineState_Running
7111 && mData->mMachineState != MachineState_Aborted
7112 && mData->mMachineState != MachineState_Teleported
7113 && mData->mMachineState != MachineState_Saved
7114 && mData->mMachineState != MachineState_PoweredOff
7115 )
7116 )
7117 )
7118 return setError(VBOX_E_INVALID_VM_STATE,
7119 tr("The machine is not mutable (state is %s)"),
7120 Global::stringifyMachineState(mData->mMachineState));
7121 break;
7122 }
7123 }
7124
7125 return S_OK;
7126}
7127
7128/**
7129 * Helper to initialize all associated child objects and allocate data
7130 * structures.
7131 *
7132 * This method must be called as a part of the object's initialization procedure
7133 * (usually done in the #init() method).
7134 *
7135 * @note Must be called only from #init() or from #registeredInit().
7136 */
7137HRESULT Machine::initDataAndChildObjects()
7138{
7139 AutoCaller autoCaller(this);
7140 AssertComRCReturnRC(autoCaller.rc());
7141 AssertComRCReturn(autoCaller.state() == InInit ||
7142 autoCaller.state() == Limited, E_FAIL);
7143
7144 AssertReturn(!mData->mAccessible, E_FAIL);
7145
7146 /* allocate data structures */
7147 mSSData.allocate();
7148 mUserData.allocate();
7149 mHWData.allocate();
7150 mMediaData.allocate();
7151 mStorageControllers.allocate();
7152
7153 /* initialize mOSTypeId */
7154 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
7155
7156 /* create associated BIOS settings object */
7157 unconst(mBIOSSettings).createObject();
7158 mBIOSSettings->init(this);
7159
7160 /* create an associated VRDE object (default is disabled) */
7161 unconst(mVRDEServer).createObject();
7162 mVRDEServer->init(this);
7163
7164 /* create associated serial port objects */
7165 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7166 {
7167 unconst(mSerialPorts[slot]).createObject();
7168 mSerialPorts[slot]->init(this, slot);
7169 }
7170
7171 /* create associated parallel port objects */
7172 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7173 {
7174 unconst(mParallelPorts[slot]).createObject();
7175 mParallelPorts[slot]->init(this, slot);
7176 }
7177
7178 /* create the audio adapter object (always present, default is disabled) */
7179 unconst(mAudioAdapter).createObject();
7180 mAudioAdapter->init(this);
7181
7182 /* create the USB controller object (always present, default is disabled) */
7183 unconst(mUSBController).createObject();
7184 mUSBController->init(this);
7185
7186 /* create associated network adapter objects */
7187 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
7188 {
7189 unconst(mNetworkAdapters[slot]).createObject();
7190 mNetworkAdapters[slot]->init(this, slot);
7191 }
7192
7193 /* create the bandwidth control */
7194 unconst(mBandwidthControl).createObject();
7195 mBandwidthControl->init(this);
7196
7197 return S_OK;
7198}
7199
7200/**
7201 * Helper to uninitialize all associated child objects and to free all data
7202 * structures.
7203 *
7204 * This method must be called as a part of the object's uninitialization
7205 * procedure (usually done in the #uninit() method).
7206 *
7207 * @note Must be called only from #uninit() or from #registeredInit().
7208 */
7209void Machine::uninitDataAndChildObjects()
7210{
7211 AutoCaller autoCaller(this);
7212 AssertComRCReturnVoid(autoCaller.rc());
7213 AssertComRCReturnVoid( autoCaller.state() == InUninit
7214 || autoCaller.state() == Limited);
7215
7216 /* tell all our other child objects we've been uninitialized */
7217 if (mBandwidthControl)
7218 {
7219 mBandwidthControl->uninit();
7220 unconst(mBandwidthControl).setNull();
7221 }
7222
7223 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
7224 {
7225 if (mNetworkAdapters[slot])
7226 {
7227 mNetworkAdapters[slot]->uninit();
7228 unconst(mNetworkAdapters[slot]).setNull();
7229 }
7230 }
7231
7232 if (mUSBController)
7233 {
7234 mUSBController->uninit();
7235 unconst(mUSBController).setNull();
7236 }
7237
7238 if (mAudioAdapter)
7239 {
7240 mAudioAdapter->uninit();
7241 unconst(mAudioAdapter).setNull();
7242 }
7243
7244 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7245 {
7246 if (mParallelPorts[slot])
7247 {
7248 mParallelPorts[slot]->uninit();
7249 unconst(mParallelPorts[slot]).setNull();
7250 }
7251 }
7252
7253 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7254 {
7255 if (mSerialPorts[slot])
7256 {
7257 mSerialPorts[slot]->uninit();
7258 unconst(mSerialPorts[slot]).setNull();
7259 }
7260 }
7261
7262 if (mVRDEServer)
7263 {
7264 mVRDEServer->uninit();
7265 unconst(mVRDEServer).setNull();
7266 }
7267
7268 if (mBIOSSettings)
7269 {
7270 mBIOSSettings->uninit();
7271 unconst(mBIOSSettings).setNull();
7272 }
7273
7274 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
7275 * instance is uninitialized; SessionMachine instances refer to real
7276 * Machine hard disks). This is necessary for a clean re-initialization of
7277 * the VM after successfully re-checking the accessibility state. Note
7278 * that in case of normal Machine or SnapshotMachine uninitialization (as
7279 * a result of unregistering or deleting the snapshot), outdated hard
7280 * disk attachments will already be uninitialized and deleted, so this
7281 * code will not affect them. */
7282 if ( !!mMediaData
7283 && (!isSessionMachine())
7284 )
7285 {
7286 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7287 it != mMediaData->mAttachments.end();
7288 ++it)
7289 {
7290 ComObjPtr<Medium> hd = (*it)->getMedium();
7291 if (hd.isNull())
7292 continue;
7293 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
7294 AssertComRC(rc);
7295 }
7296 }
7297
7298 if (!isSessionMachine() && !isSnapshotMachine())
7299 {
7300 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
7301 if (mData->mFirstSnapshot)
7302 {
7303 // snapshots tree is protected by media write lock; strictly
7304 // this isn't necessary here since we're deleting the entire
7305 // machine, but otherwise we assert in Snapshot::uninit()
7306 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7307 mData->mFirstSnapshot->uninit();
7308 mData->mFirstSnapshot.setNull();
7309 }
7310
7311 mData->mCurrentSnapshot.setNull();
7312 }
7313
7314 /* free data structures (the essential mData structure is not freed here
7315 * since it may be still in use) */
7316 mMediaData.free();
7317 mStorageControllers.free();
7318 mHWData.free();
7319 mUserData.free();
7320 mSSData.free();
7321}
7322
7323/**
7324 * Returns a pointer to the Machine object for this machine that acts like a
7325 * parent for complex machine data objects such as shared folders, etc.
7326 *
7327 * For primary Machine objects and for SnapshotMachine objects, returns this
7328 * object's pointer itself. For SessionMachine objects, returns the peer
7329 * (primary) machine pointer.
7330 */
7331Machine* Machine::getMachine()
7332{
7333 if (isSessionMachine())
7334 return (Machine*)mPeer;
7335 return this;
7336}
7337
7338/**
7339 * Makes sure that there are no machine state dependents. If necessary, waits
7340 * for the number of dependents to drop to zero.
7341 *
7342 * Make sure this method is called from under this object's write lock to
7343 * guarantee that no new dependents may be added when this method returns
7344 * control to the caller.
7345 *
7346 * @note Locks this object for writing. The lock will be released while waiting
7347 * (if necessary).
7348 *
7349 * @warning To be used only in methods that change the machine state!
7350 */
7351void Machine::ensureNoStateDependencies()
7352{
7353 AssertReturnVoid(isWriteLockOnCurrentThread());
7354
7355 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7356
7357 /* Wait for all state dependents if necessary */
7358 if (mData->mMachineStateDeps != 0)
7359 {
7360 /* lazy semaphore creation */
7361 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
7362 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
7363
7364 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
7365 mData->mMachineStateDeps));
7366
7367 ++mData->mMachineStateChangePending;
7368
7369 /* reset the semaphore before waiting, the last dependent will signal
7370 * it */
7371 RTSemEventMultiReset(mData->mMachineStateDepsSem);
7372
7373 alock.leave();
7374
7375 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
7376
7377 alock.enter();
7378
7379 -- mData->mMachineStateChangePending;
7380 }
7381}
7382
7383/**
7384 * Changes the machine state and informs callbacks.
7385 *
7386 * This method is not intended to fail so it either returns S_OK or asserts (and
7387 * returns a failure).
7388 *
7389 * @note Locks this object for writing.
7390 */
7391HRESULT Machine::setMachineState(MachineState_T aMachineState)
7392{
7393 LogFlowThisFuncEnter();
7394 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
7395
7396 AutoCaller autoCaller(this);
7397 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7398
7399 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7400
7401 /* wait for state dependents to drop to zero */
7402 ensureNoStateDependencies();
7403
7404 if (mData->mMachineState != aMachineState)
7405 {
7406 mData->mMachineState = aMachineState;
7407
7408 RTTimeNow(&mData->mLastStateChange);
7409
7410 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7411 }
7412
7413 LogFlowThisFuncLeave();
7414 return S_OK;
7415}
7416
7417/**
7418 * Searches for a shared folder with the given logical name
7419 * in the collection of shared folders.
7420 *
7421 * @param aName logical name of the shared folder
7422 * @param aSharedFolder where to return the found object
7423 * @param aSetError whether to set the error info if the folder is
7424 * not found
7425 * @return
7426 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7427 *
7428 * @note
7429 * must be called from under the object's lock!
7430 */
7431HRESULT Machine::findSharedFolder(const Utf8Str &aName,
7432 ComObjPtr<SharedFolder> &aSharedFolder,
7433 bool aSetError /* = false */)
7434{
7435 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
7436 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7437 it != mHWData->mSharedFolders.end();
7438 ++it)
7439 {
7440 SharedFolder *pSF = *it;
7441 AutoCaller autoCaller(pSF);
7442 if (pSF->getName() == aName)
7443 {
7444 aSharedFolder = pSF;
7445 rc = S_OK;
7446 break;
7447 }
7448 }
7449
7450 if (aSetError && FAILED(rc))
7451 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
7452
7453 return rc;
7454}
7455
7456/**
7457 * Initializes all machine instance data from the given settings structures
7458 * from XML. The exception is the machine UUID which needs special handling
7459 * depending on the caller's use case, so the caller needs to set that herself.
7460 *
7461 * This gets called in several contexts during machine initialization:
7462 *
7463 * -- When machine XML exists on disk already and needs to be loaded into memory,
7464 * for example, from registeredInit() to load all registered machines on
7465 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7466 * attached to the machine should be part of some media registry already.
7467 *
7468 * -- During OVF import, when a machine config has been constructed from an
7469 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7470 * ensure that the media listed as attachments in the config (which have
7471 * been imported from the OVF) receive the correct registry ID.
7472 *
7473 * -- During VM cloning.
7474 *
7475 * @param config Machine settings from XML.
7476 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7477 * @return
7478 */
7479HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7480 const Guid *puuidRegistry)
7481{
7482 // copy name, description, OS type, teleporter, UTC etc.
7483 mUserData->s = config.machineUserData;
7484
7485 // look up the object by Id to check it is valid
7486 ComPtr<IGuestOSType> guestOSType;
7487 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7488 guestOSType.asOutParam());
7489 if (FAILED(rc)) return rc;
7490
7491 // stateFile (optional)
7492 if (config.strStateFile.isEmpty())
7493 mSSData->strStateFilePath.setNull();
7494 else
7495 {
7496 Utf8Str stateFilePathFull(config.strStateFile);
7497 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7498 if (RT_FAILURE(vrc))
7499 return setError(E_FAIL,
7500 tr("Invalid saved state file path '%s' (%Rrc)"),
7501 config.strStateFile.c_str(),
7502 vrc);
7503 mSSData->strStateFilePath = stateFilePathFull;
7504 }
7505
7506 // snapshot folder needs special processing so set it again
7507 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7508 if (FAILED(rc)) return rc;
7509
7510 /* Copy the extra data items (Not in any case config is already the same as
7511 * mData->pMachineConfigFile, like when the xml files are read from disk. So
7512 * make sure the extra data map is copied). */
7513 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
7514
7515 /* currentStateModified (optional, default is true) */
7516 mData->mCurrentStateModified = config.fCurrentStateModified;
7517
7518 mData->mLastStateChange = config.timeLastStateChange;
7519
7520 /*
7521 * note: all mUserData members must be assigned prior this point because
7522 * we need to commit changes in order to let mUserData be shared by all
7523 * snapshot machine instances.
7524 */
7525 mUserData.commitCopy();
7526
7527 // machine registry, if present (must be loaded before snapshots)
7528 if (config.canHaveOwnMediaRegistry())
7529 {
7530 // determine machine folder
7531 Utf8Str strMachineFolder = getSettingsFileFull();
7532 strMachineFolder.stripFilename();
7533 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7534 config.mediaRegistry,
7535 strMachineFolder);
7536 if (FAILED(rc)) return rc;
7537 }
7538
7539 /* Snapshot node (optional) */
7540 size_t cRootSnapshots;
7541 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7542 {
7543 // there must be only one root snapshot
7544 Assert(cRootSnapshots == 1);
7545
7546 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7547
7548 rc = loadSnapshot(snap,
7549 config.uuidCurrentSnapshot,
7550 NULL); // no parent == first snapshot
7551 if (FAILED(rc)) return rc;
7552 }
7553
7554 // hardware data
7555 rc = loadHardware(config.hardwareMachine);
7556 if (FAILED(rc)) return rc;
7557
7558 // load storage controllers
7559 rc = loadStorageControllers(config.storageMachine,
7560 puuidRegistry,
7561 NULL /* puuidSnapshot */);
7562 if (FAILED(rc)) return rc;
7563
7564 /*
7565 * NOTE: the assignment below must be the last thing to do,
7566 * otherwise it will be not possible to change the settings
7567 * somewhere in the code above because all setters will be
7568 * blocked by checkStateDependency(MutableStateDep).
7569 */
7570
7571 /* set the machine state to Aborted or Saved when appropriate */
7572 if (config.fAborted)
7573 {
7574 mSSData->strStateFilePath.setNull();
7575
7576 /* no need to use setMachineState() during init() */
7577 mData->mMachineState = MachineState_Aborted;
7578 }
7579 else if (!mSSData->strStateFilePath.isEmpty())
7580 {
7581 /* no need to use setMachineState() during init() */
7582 mData->mMachineState = MachineState_Saved;
7583 }
7584
7585 // after loading settings, we are no longer different from the XML on disk
7586 mData->flModifications = 0;
7587
7588 return S_OK;
7589}
7590
7591/**
7592 * Recursively loads all snapshots starting from the given.
7593 *
7594 * @param aNode <Snapshot> node.
7595 * @param aCurSnapshotId Current snapshot ID from the settings file.
7596 * @param aParentSnapshot Parent snapshot.
7597 */
7598HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7599 const Guid &aCurSnapshotId,
7600 Snapshot *aParentSnapshot)
7601{
7602 AssertReturn(!isSnapshotMachine(), E_FAIL);
7603 AssertReturn(!isSessionMachine(), E_FAIL);
7604
7605 HRESULT rc = S_OK;
7606
7607 Utf8Str strStateFile;
7608 if (!data.strStateFile.isEmpty())
7609 {
7610 /* optional */
7611 strStateFile = data.strStateFile;
7612 int vrc = calculateFullPath(strStateFile, strStateFile);
7613 if (RT_FAILURE(vrc))
7614 return setError(E_FAIL,
7615 tr("Invalid saved state file path '%s' (%Rrc)"),
7616 strStateFile.c_str(),
7617 vrc);
7618 }
7619
7620 /* create a snapshot machine object */
7621 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7622 pSnapshotMachine.createObject();
7623 rc = pSnapshotMachine->init(this,
7624 data.hardware,
7625 data.storage,
7626 data.uuid.ref(),
7627 strStateFile);
7628 if (FAILED(rc)) return rc;
7629
7630 /* create a snapshot object */
7631 ComObjPtr<Snapshot> pSnapshot;
7632 pSnapshot.createObject();
7633 /* initialize the snapshot */
7634 rc = pSnapshot->init(mParent, // VirtualBox object
7635 data.uuid,
7636 data.strName,
7637 data.strDescription,
7638 data.timestamp,
7639 pSnapshotMachine,
7640 aParentSnapshot);
7641 if (FAILED(rc)) return rc;
7642
7643 /* memorize the first snapshot if necessary */
7644 if (!mData->mFirstSnapshot)
7645 mData->mFirstSnapshot = pSnapshot;
7646
7647 /* memorize the current snapshot when appropriate */
7648 if ( !mData->mCurrentSnapshot
7649 && pSnapshot->getId() == aCurSnapshotId
7650 )
7651 mData->mCurrentSnapshot = pSnapshot;
7652
7653 // now create the children
7654 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7655 it != data.llChildSnapshots.end();
7656 ++it)
7657 {
7658 const settings::Snapshot &childData = *it;
7659 // recurse
7660 rc = loadSnapshot(childData,
7661 aCurSnapshotId,
7662 pSnapshot); // parent = the one we created above
7663 if (FAILED(rc)) return rc;
7664 }
7665
7666 return rc;
7667}
7668
7669/**
7670 * @param aNode <Hardware> node.
7671 */
7672HRESULT Machine::loadHardware(const settings::Hardware &data)
7673{
7674 AssertReturn(!isSessionMachine(), E_FAIL);
7675
7676 HRESULT rc = S_OK;
7677
7678 try
7679 {
7680 /* The hardware version attribute (optional). */
7681 mHWData->mHWVersion = data.strVersion;
7682 mHWData->mHardwareUUID = data.uuid;
7683
7684 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7685 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7686 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7687 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7688 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7689 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7690 mHWData->mPAEEnabled = data.fPAE;
7691 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7692
7693 mHWData->mCPUCount = data.cCPUs;
7694 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7695 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7696
7697 // cpu
7698 if (mHWData->mCPUHotPlugEnabled)
7699 {
7700 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7701 it != data.llCpus.end();
7702 ++it)
7703 {
7704 const settings::Cpu &cpu = *it;
7705
7706 mHWData->mCPUAttached[cpu.ulId] = true;
7707 }
7708 }
7709
7710 // cpuid leafs
7711 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7712 it != data.llCpuIdLeafs.end();
7713 ++it)
7714 {
7715 const settings::CpuIdLeaf &leaf = *it;
7716
7717 switch (leaf.ulId)
7718 {
7719 case 0x0:
7720 case 0x1:
7721 case 0x2:
7722 case 0x3:
7723 case 0x4:
7724 case 0x5:
7725 case 0x6:
7726 case 0x7:
7727 case 0x8:
7728 case 0x9:
7729 case 0xA:
7730 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7731 break;
7732
7733 case 0x80000000:
7734 case 0x80000001:
7735 case 0x80000002:
7736 case 0x80000003:
7737 case 0x80000004:
7738 case 0x80000005:
7739 case 0x80000006:
7740 case 0x80000007:
7741 case 0x80000008:
7742 case 0x80000009:
7743 case 0x8000000A:
7744 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7745 break;
7746
7747 default:
7748 /* just ignore */
7749 break;
7750 }
7751 }
7752
7753 mHWData->mMemorySize = data.ulMemorySizeMB;
7754 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7755
7756 // boot order
7757 for (size_t i = 0;
7758 i < RT_ELEMENTS(mHWData->mBootOrder);
7759 i++)
7760 {
7761 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7762 if (it == data.mapBootOrder.end())
7763 mHWData->mBootOrder[i] = DeviceType_Null;
7764 else
7765 mHWData->mBootOrder[i] = it->second;
7766 }
7767
7768 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7769 mHWData->mMonitorCount = data.cMonitors;
7770 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7771 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7772 mHWData->mFirmwareType = data.firmwareType;
7773 mHWData->mPointingHidType = data.pointingHidType;
7774 mHWData->mKeyboardHidType = data.keyboardHidType;
7775 mHWData->mChipsetType = data.chipsetType;
7776 mHWData->mHpetEnabled = data.fHpetEnabled;
7777
7778 /* VRDEServer */
7779 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7780 if (FAILED(rc)) return rc;
7781
7782 /* BIOS */
7783 rc = mBIOSSettings->loadSettings(data.biosSettings);
7784 if (FAILED(rc)) return rc;
7785
7786 // Bandwidth control (must come before network adapters)
7787 rc = mBandwidthControl->loadSettings(data.ioSettings);
7788 if (FAILED(rc)) return rc;
7789
7790 /* USB Controller */
7791 rc = mUSBController->loadSettings(data.usbController);
7792 if (FAILED(rc)) return rc;
7793
7794 // network adapters
7795 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7796 it != data.llNetworkAdapters.end();
7797 ++it)
7798 {
7799 const settings::NetworkAdapter &nic = *it;
7800
7801 /* slot unicity is guaranteed by XML Schema */
7802 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7803 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
7804 if (FAILED(rc)) return rc;
7805 }
7806
7807 // serial ports
7808 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7809 it != data.llSerialPorts.end();
7810 ++it)
7811 {
7812 const settings::SerialPort &s = *it;
7813
7814 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7815 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7816 if (FAILED(rc)) return rc;
7817 }
7818
7819 // parallel ports (optional)
7820 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7821 it != data.llParallelPorts.end();
7822 ++it)
7823 {
7824 const settings::ParallelPort &p = *it;
7825
7826 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7827 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7828 if (FAILED(rc)) return rc;
7829 }
7830
7831 /* AudioAdapter */
7832 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7833 if (FAILED(rc)) return rc;
7834
7835 /* Shared folders */
7836 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7837 it != data.llSharedFolders.end();
7838 ++it)
7839 {
7840 const settings::SharedFolder &sf = *it;
7841
7842 ComObjPtr<SharedFolder> sharedFolder;
7843 /* Check for double entries. Not allowed! */
7844 rc = findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
7845 if (SUCCEEDED(rc))
7846 return setError(VBOX_E_OBJECT_IN_USE,
7847 tr("Shared folder named '%s' already exists"),
7848 sf.strName.c_str());
7849
7850 /* Create the new shared folder. Don't break on error. This will be
7851 * reported when the machine starts. */
7852 sharedFolder.createObject();
7853 rc = sharedFolder->init(getMachine(),
7854 sf.strName,
7855 sf.strHostPath,
7856 RT_BOOL(sf.fWritable),
7857 RT_BOOL(sf.fAutoMount),
7858 false /* fFailOnError */);
7859 if (FAILED(rc)) return rc;
7860 mHWData->mSharedFolders.push_back(sharedFolder);
7861 }
7862
7863 // Clipboard
7864 mHWData->mClipboardMode = data.clipboardMode;
7865
7866 // guest settings
7867 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7868
7869 // IO settings
7870 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7871 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7872
7873 // Host PCI devices
7874 for (settings::HostPciDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
7875 it != data.pciAttachments.end();
7876 ++it)
7877 {
7878 const settings::HostPciDeviceAttachment &hpda = *it;
7879 ComObjPtr<PciDeviceAttachment> pda;
7880
7881 pda.createObject();
7882 pda->loadSettings(this, hpda);
7883 mHWData->mPciDeviceAssignments.push_back(pda);
7884 }
7885
7886#ifdef VBOX_WITH_GUEST_PROPS
7887 /* Guest properties (optional) */
7888 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7889 it != data.llGuestProperties.end();
7890 ++it)
7891 {
7892 const settings::GuestProperty &prop = *it;
7893 uint32_t fFlags = guestProp::NILFLAG;
7894 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7895 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7896 mHWData->mGuestProperties.push_back(property);
7897 }
7898
7899 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7900#endif /* VBOX_WITH_GUEST_PROPS defined */
7901 }
7902 catch(std::bad_alloc &)
7903 {
7904 return E_OUTOFMEMORY;
7905 }
7906
7907 AssertComRC(rc);
7908 return rc;
7909}
7910
7911/**
7912 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7913 *
7914 * @param data
7915 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7916 * @param puuidSnapshot
7917 * @return
7918 */
7919HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7920 const Guid *puuidRegistry,
7921 const Guid *puuidSnapshot)
7922{
7923 AssertReturn(!isSessionMachine(), E_FAIL);
7924
7925 HRESULT rc = S_OK;
7926
7927 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7928 it != data.llStorageControllers.end();
7929 ++it)
7930 {
7931 const settings::StorageController &ctlData = *it;
7932
7933 ComObjPtr<StorageController> pCtl;
7934 /* Try to find one with the name first. */
7935 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7936 if (SUCCEEDED(rc))
7937 return setError(VBOX_E_OBJECT_IN_USE,
7938 tr("Storage controller named '%s' already exists"),
7939 ctlData.strName.c_str());
7940
7941 pCtl.createObject();
7942 rc = pCtl->init(this,
7943 ctlData.strName,
7944 ctlData.storageBus,
7945 ctlData.ulInstance,
7946 ctlData.fBootable);
7947 if (FAILED(rc)) return rc;
7948
7949 mStorageControllers->push_back(pCtl);
7950
7951 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7952 if (FAILED(rc)) return rc;
7953
7954 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7955 if (FAILED(rc)) return rc;
7956
7957 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7958 if (FAILED(rc)) return rc;
7959
7960 /* Set IDE emulation settings (only for AHCI controller). */
7961 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7962 {
7963 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7964 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7965 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7966 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7967 )
7968 return rc;
7969 }
7970
7971 /* Load the attached devices now. */
7972 rc = loadStorageDevices(pCtl,
7973 ctlData,
7974 puuidRegistry,
7975 puuidSnapshot);
7976 if (FAILED(rc)) return rc;
7977 }
7978
7979 return S_OK;
7980}
7981
7982/**
7983 * Called from loadStorageControllers for a controller's devices.
7984 *
7985 * @param aStorageController
7986 * @param data
7987 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7988 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7989 * @return
7990 */
7991HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7992 const settings::StorageController &data,
7993 const Guid *puuidRegistry,
7994 const Guid *puuidSnapshot)
7995{
7996 HRESULT rc = S_OK;
7997
7998 /* paranoia: detect duplicate attachments */
7999 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
8000 it != data.llAttachedDevices.end();
8001 ++it)
8002 {
8003 const settings::AttachedDevice &ad = *it;
8004
8005 for (settings::AttachedDevicesList::const_iterator it2 = it;
8006 it2 != data.llAttachedDevices.end();
8007 ++it2)
8008 {
8009 if (it == it2)
8010 continue;
8011
8012 const settings::AttachedDevice &ad2 = *it2;
8013
8014 if ( ad.lPort == ad2.lPort
8015 && ad.lDevice == ad2.lDevice)
8016 {
8017 return setError(E_FAIL,
8018 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
8019 aStorageController->getName().c_str(),
8020 ad.lPort,
8021 ad.lDevice,
8022 mUserData->s.strName.c_str());
8023 }
8024 }
8025 }
8026
8027 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
8028 it != data.llAttachedDevices.end();
8029 ++it)
8030 {
8031 const settings::AttachedDevice &dev = *it;
8032 ComObjPtr<Medium> medium;
8033
8034 switch (dev.deviceType)
8035 {
8036 case DeviceType_Floppy:
8037 case DeviceType_DVD:
8038 if (dev.strHostDriveSrc.isNotEmpty())
8039 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
8040 else
8041 rc = mParent->findRemoveableMedium(dev.deviceType,
8042 dev.uuid,
8043 false /* fRefresh */,
8044 false /* aSetError */,
8045 medium);
8046 if (rc == VBOX_E_OBJECT_NOT_FOUND)
8047 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
8048 rc = S_OK;
8049 break;
8050
8051 case DeviceType_HardDisk:
8052 {
8053 /* find a hard disk by UUID */
8054 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
8055 if (FAILED(rc))
8056 {
8057 if (isSnapshotMachine())
8058 {
8059 // wrap another error message around the "cannot find hard disk" set by findHardDisk
8060 // so the user knows that the bad disk is in a snapshot somewhere
8061 com::ErrorInfo info;
8062 return setError(E_FAIL,
8063 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
8064 puuidSnapshot->raw(),
8065 info.getText().raw());
8066 }
8067 else
8068 return rc;
8069 }
8070
8071 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
8072
8073 if (medium->getType() == MediumType_Immutable)
8074 {
8075 if (isSnapshotMachine())
8076 return setError(E_FAIL,
8077 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
8078 "of the virtual machine '%s' ('%s')"),
8079 medium->getLocationFull().c_str(),
8080 dev.uuid.raw(),
8081 puuidSnapshot->raw(),
8082 mUserData->s.strName.c_str(),
8083 mData->m_strConfigFileFull.c_str());
8084
8085 return setError(E_FAIL,
8086 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
8087 medium->getLocationFull().c_str(),
8088 dev.uuid.raw(),
8089 mUserData->s.strName.c_str(),
8090 mData->m_strConfigFileFull.c_str());
8091 }
8092
8093 if (medium->getType() == MediumType_MultiAttach)
8094 {
8095 if (isSnapshotMachine())
8096 return setError(E_FAIL,
8097 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
8098 "of the virtual machine '%s' ('%s')"),
8099 medium->getLocationFull().c_str(),
8100 dev.uuid.raw(),
8101 puuidSnapshot->raw(),
8102 mUserData->s.strName.c_str(),
8103 mData->m_strConfigFileFull.c_str());
8104
8105 return setError(E_FAIL,
8106 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
8107 medium->getLocationFull().c_str(),
8108 dev.uuid.raw(),
8109 mUserData->s.strName.c_str(),
8110 mData->m_strConfigFileFull.c_str());
8111 }
8112
8113 if ( !isSnapshotMachine()
8114 && medium->getChildren().size() != 0
8115 )
8116 return setError(E_FAIL,
8117 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
8118 "because it has %d differencing child hard disks"),
8119 medium->getLocationFull().c_str(),
8120 dev.uuid.raw(),
8121 mUserData->s.strName.c_str(),
8122 mData->m_strConfigFileFull.c_str(),
8123 medium->getChildren().size());
8124
8125 if (findAttachment(mMediaData->mAttachments,
8126 medium))
8127 return setError(E_FAIL,
8128 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
8129 medium->getLocationFull().c_str(),
8130 dev.uuid.raw(),
8131 mUserData->s.strName.c_str(),
8132 mData->m_strConfigFileFull.c_str());
8133
8134 break;
8135 }
8136
8137 default:
8138 return setError(E_FAIL,
8139 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
8140 medium->getLocationFull().c_str(),
8141 mUserData->s.strName.c_str(),
8142 mData->m_strConfigFileFull.c_str());
8143 }
8144
8145 if (FAILED(rc))
8146 break;
8147
8148 /* Bandwidth groups are loaded at this point. */
8149 ComObjPtr<BandwidthGroup> pBwGroup;
8150
8151 if (!dev.strBwGroup.isEmpty())
8152 {
8153 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
8154 if (FAILED(rc))
8155 return setError(E_FAIL,
8156 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
8157 medium->getLocationFull().c_str(),
8158 dev.strBwGroup.c_str(),
8159 mUserData->s.strName.c_str(),
8160 mData->m_strConfigFileFull.c_str());
8161 pBwGroup->reference();
8162 }
8163
8164 const Bstr controllerName = aStorageController->getName();
8165 ComObjPtr<MediumAttachment> pAttachment;
8166 pAttachment.createObject();
8167 rc = pAttachment->init(this,
8168 medium,
8169 controllerName,
8170 dev.lPort,
8171 dev.lDevice,
8172 dev.deviceType,
8173 false,
8174 dev.fPassThrough,
8175 dev.fTempEject,
8176 dev.fNonRotational,
8177 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
8178 if (FAILED(rc)) break;
8179
8180 /* associate the medium with this machine and snapshot */
8181 if (!medium.isNull())
8182 {
8183 AutoCaller medCaller(medium);
8184 if (FAILED(medCaller.rc())) return medCaller.rc();
8185 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
8186
8187 if (isSnapshotMachine())
8188 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
8189 else
8190 rc = medium->addBackReference(mData->mUuid);
8191 /* If the medium->addBackReference fails it sets an appropriate
8192 * error message, so no need to do any guesswork here. */
8193
8194 if (puuidRegistry)
8195 // caller wants registry ID to be set on all attached media (OVF import case)
8196 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
8197 }
8198
8199 if (FAILED(rc))
8200 break;
8201
8202 /* back up mMediaData to let registeredInit() properly rollback on failure
8203 * (= limited accessibility) */
8204 setModified(IsModified_Storage);
8205 mMediaData.backup();
8206 mMediaData->mAttachments.push_back(pAttachment);
8207 }
8208
8209 return rc;
8210}
8211
8212/**
8213 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
8214 *
8215 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
8216 * @param aSnapshot where to return the found snapshot
8217 * @param aSetError true to set extended error info on failure
8218 */
8219HRESULT Machine::findSnapshotById(const Guid &aId,
8220 ComObjPtr<Snapshot> &aSnapshot,
8221 bool aSetError /* = false */)
8222{
8223 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8224
8225 if (!mData->mFirstSnapshot)
8226 {
8227 if (aSetError)
8228 return setError(E_FAIL, tr("This machine does not have any snapshots"));
8229 return E_FAIL;
8230 }
8231
8232 if (aId.isEmpty())
8233 aSnapshot = mData->mFirstSnapshot;
8234 else
8235 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
8236
8237 if (!aSnapshot)
8238 {
8239 if (aSetError)
8240 return setError(E_FAIL,
8241 tr("Could not find a snapshot with UUID {%s}"),
8242 aId.toString().c_str());
8243 return E_FAIL;
8244 }
8245
8246 return S_OK;
8247}
8248
8249/**
8250 * Returns the snapshot with the given name or fails of no such snapshot.
8251 *
8252 * @param aName snapshot name to find
8253 * @param aSnapshot where to return the found snapshot
8254 * @param aSetError true to set extended error info on failure
8255 */
8256HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
8257 ComObjPtr<Snapshot> &aSnapshot,
8258 bool aSetError /* = false */)
8259{
8260 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
8261
8262 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8263
8264 if (!mData->mFirstSnapshot)
8265 {
8266 if (aSetError)
8267 return setError(VBOX_E_OBJECT_NOT_FOUND,
8268 tr("This machine does not have any snapshots"));
8269 return VBOX_E_OBJECT_NOT_FOUND;
8270 }
8271
8272 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
8273
8274 if (!aSnapshot)
8275 {
8276 if (aSetError)
8277 return setError(VBOX_E_OBJECT_NOT_FOUND,
8278 tr("Could not find a snapshot named '%s'"), strName.c_str());
8279 return VBOX_E_OBJECT_NOT_FOUND;
8280 }
8281
8282 return S_OK;
8283}
8284
8285/**
8286 * Returns a storage controller object with the given name.
8287 *
8288 * @param aName storage controller name to find
8289 * @param aStorageController where to return the found storage controller
8290 * @param aSetError true to set extended error info on failure
8291 */
8292HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
8293 ComObjPtr<StorageController> &aStorageController,
8294 bool aSetError /* = false */)
8295{
8296 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
8297
8298 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8299 it != mStorageControllers->end();
8300 ++it)
8301 {
8302 if ((*it)->getName() == aName)
8303 {
8304 aStorageController = (*it);
8305 return S_OK;
8306 }
8307 }
8308
8309 if (aSetError)
8310 return setError(VBOX_E_OBJECT_NOT_FOUND,
8311 tr("Could not find a storage controller named '%s'"),
8312 aName.c_str());
8313 return VBOX_E_OBJECT_NOT_FOUND;
8314}
8315
8316HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
8317 MediaData::AttachmentList &atts)
8318{
8319 AutoCaller autoCaller(this);
8320 if (FAILED(autoCaller.rc())) return autoCaller.rc();
8321
8322 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8323
8324 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
8325 it != mMediaData->mAttachments.end();
8326 ++it)
8327 {
8328 const ComObjPtr<MediumAttachment> &pAtt = *it;
8329
8330 // should never happen, but deal with NULL pointers in the list.
8331 AssertStmt(!pAtt.isNull(), continue);
8332
8333 // getControllerName() needs caller+read lock
8334 AutoCaller autoAttCaller(pAtt);
8335 if (FAILED(autoAttCaller.rc()))
8336 {
8337 atts.clear();
8338 return autoAttCaller.rc();
8339 }
8340 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
8341
8342 if (pAtt->getControllerName() == aName)
8343 atts.push_back(pAtt);
8344 }
8345
8346 return S_OK;
8347}
8348
8349/**
8350 * Helper for #saveSettings. Cares about renaming the settings directory and
8351 * file if the machine name was changed and about creating a new settings file
8352 * if this is a new machine.
8353 *
8354 * @note Must be never called directly but only from #saveSettings().
8355 */
8356HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
8357{
8358 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8359
8360 HRESULT rc = S_OK;
8361
8362 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
8363
8364 /* attempt to rename the settings file if machine name is changed */
8365 if ( mUserData->s.fNameSync
8366 && mUserData.isBackedUp()
8367 && mUserData.backedUpData()->s.strName != mUserData->s.strName
8368 )
8369 {
8370 bool dirRenamed = false;
8371 bool fileRenamed = false;
8372
8373 Utf8Str configFile, newConfigFile;
8374 Utf8Str configFilePrev, newConfigFilePrev;
8375 Utf8Str configDir, newConfigDir;
8376
8377 do
8378 {
8379 int vrc = VINF_SUCCESS;
8380
8381 Utf8Str name = mUserData.backedUpData()->s.strName;
8382 Utf8Str newName = mUserData->s.strName;
8383
8384 configFile = mData->m_strConfigFileFull;
8385
8386 /* first, rename the directory if it matches the machine name */
8387 configDir = configFile;
8388 configDir.stripFilename();
8389 newConfigDir = configDir;
8390 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8391 {
8392 newConfigDir.stripFilename();
8393 newConfigDir.append(RTPATH_DELIMITER);
8394 newConfigDir.append(newName);
8395 /* new dir and old dir cannot be equal here because of 'if'
8396 * above and because name != newName */
8397 Assert(configDir != newConfigDir);
8398 if (!fSettingsFileIsNew)
8399 {
8400 /* perform real rename only if the machine is not new */
8401 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8402 if (RT_FAILURE(vrc))
8403 {
8404 rc = setError(E_FAIL,
8405 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8406 configDir.c_str(),
8407 newConfigDir.c_str(),
8408 vrc);
8409 break;
8410 }
8411 dirRenamed = true;
8412 }
8413 }
8414
8415 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8416 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8417
8418 /* then try to rename the settings file itself */
8419 if (newConfigFile != configFile)
8420 {
8421 /* get the path to old settings file in renamed directory */
8422 configFile = Utf8StrFmt("%s%c%s",
8423 newConfigDir.c_str(),
8424 RTPATH_DELIMITER,
8425 RTPathFilename(configFile.c_str()));
8426 if (!fSettingsFileIsNew)
8427 {
8428 /* perform real rename only if the machine is not new */
8429 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8430 if (RT_FAILURE(vrc))
8431 {
8432 rc = setError(E_FAIL,
8433 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8434 configFile.c_str(),
8435 newConfigFile.c_str(),
8436 vrc);
8437 break;
8438 }
8439 fileRenamed = true;
8440 configFilePrev = configFile;
8441 configFilePrev += "-prev";
8442 newConfigFilePrev = newConfigFile;
8443 newConfigFilePrev += "-prev";
8444 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
8445 }
8446 }
8447
8448 // update m_strConfigFileFull amd mConfigFile
8449 mData->m_strConfigFileFull = newConfigFile;
8450 // compute the relative path too
8451 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8452
8453 // store the old and new so that VirtualBox::saveSettings() can update
8454 // the media registry
8455 if ( mData->mRegistered
8456 && configDir != newConfigDir)
8457 {
8458 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8459
8460 if (pfNeedsGlobalSaveSettings)
8461 *pfNeedsGlobalSaveSettings = true;
8462 }
8463
8464 // in the saved state file path, replace the old directory with the new directory
8465 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8466 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8467
8468 // and do the same thing for the saved state file paths of all the online snapshots
8469 if (mData->mFirstSnapshot)
8470 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8471 newConfigDir.c_str());
8472 }
8473 while (0);
8474
8475 if (FAILED(rc))
8476 {
8477 /* silently try to rename everything back */
8478 if (fileRenamed)
8479 {
8480 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
8481 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8482 }
8483 if (dirRenamed)
8484 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8485 }
8486
8487 if (FAILED(rc)) return rc;
8488 }
8489
8490 if (fSettingsFileIsNew)
8491 {
8492 /* create a virgin config file */
8493 int vrc = VINF_SUCCESS;
8494
8495 /* ensure the settings directory exists */
8496 Utf8Str path(mData->m_strConfigFileFull);
8497 path.stripFilename();
8498 if (!RTDirExists(path.c_str()))
8499 {
8500 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8501 if (RT_FAILURE(vrc))
8502 {
8503 return setError(E_FAIL,
8504 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8505 path.c_str(),
8506 vrc);
8507 }
8508 }
8509
8510 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8511 path = Utf8Str(mData->m_strConfigFileFull);
8512 RTFILE f = NIL_RTFILE;
8513 vrc = RTFileOpen(&f, path.c_str(),
8514 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8515 if (RT_FAILURE(vrc))
8516 return setError(E_FAIL,
8517 tr("Could not create the settings file '%s' (%Rrc)"),
8518 path.c_str(),
8519 vrc);
8520 RTFileClose(f);
8521 }
8522
8523 return rc;
8524}
8525
8526/**
8527 * Saves and commits machine data, user data and hardware data.
8528 *
8529 * Note that on failure, the data remains uncommitted.
8530 *
8531 * @a aFlags may combine the following flags:
8532 *
8533 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8534 * Used when saving settings after an operation that makes them 100%
8535 * correspond to the settings from the current snapshot.
8536 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8537 * #isReallyModified() returns false. This is necessary for cases when we
8538 * change machine data directly, not through the backup()/commit() mechanism.
8539 * - SaveS_Force: settings will be saved without doing a deep compare of the
8540 * settings structures. This is used when this is called because snapshots
8541 * have changed to avoid the overhead of the deep compare.
8542 *
8543 * @note Must be called from under this object's write lock. Locks children for
8544 * writing.
8545 *
8546 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8547 * initialized to false and that will be set to true by this function if
8548 * the caller must invoke VirtualBox::saveSettings() because the global
8549 * settings have changed. This will happen if a machine rename has been
8550 * saved and the global machine and media registries will therefore need
8551 * updating.
8552 */
8553HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8554 int aFlags /*= 0*/)
8555{
8556 LogFlowThisFuncEnter();
8557
8558 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8559
8560 /* make sure child objects are unable to modify the settings while we are
8561 * saving them */
8562 ensureNoStateDependencies();
8563
8564 AssertReturn(!isSnapshotMachine(),
8565 E_FAIL);
8566
8567 HRESULT rc = S_OK;
8568 bool fNeedsWrite = false;
8569
8570 /* First, prepare to save settings. It will care about renaming the
8571 * settings directory and file if the machine name was changed and about
8572 * creating a new settings file if this is a new machine. */
8573 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8574 if (FAILED(rc)) return rc;
8575
8576 // keep a pointer to the current settings structures
8577 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8578 settings::MachineConfigFile *pNewConfig = NULL;
8579
8580 try
8581 {
8582 // make a fresh one to have everyone write stuff into
8583 pNewConfig = new settings::MachineConfigFile(NULL);
8584 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8585
8586 // now go and copy all the settings data from COM to the settings structures
8587 // (this calles saveSettings() on all the COM objects in the machine)
8588 copyMachineDataToSettings(*pNewConfig);
8589
8590 if (aFlags & SaveS_ResetCurStateModified)
8591 {
8592 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8593 mData->mCurrentStateModified = FALSE;
8594 fNeedsWrite = true; // always, no need to compare
8595 }
8596 else if (aFlags & SaveS_Force)
8597 {
8598 fNeedsWrite = true; // always, no need to compare
8599 }
8600 else
8601 {
8602 if (!mData->mCurrentStateModified)
8603 {
8604 // do a deep compare of the settings that we just saved with the settings
8605 // previously stored in the config file; this invokes MachineConfigFile::operator==
8606 // which does a deep compare of all the settings, which is expensive but less expensive
8607 // than writing out XML in vain
8608 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8609
8610 // could still be modified if any settings changed
8611 mData->mCurrentStateModified = fAnySettingsChanged;
8612
8613 fNeedsWrite = fAnySettingsChanged;
8614 }
8615 else
8616 fNeedsWrite = true;
8617 }
8618
8619 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8620
8621 if (fNeedsWrite)
8622 // now spit it all out!
8623 pNewConfig->write(mData->m_strConfigFileFull);
8624
8625 mData->pMachineConfigFile = pNewConfig;
8626 delete pOldConfig;
8627 commit();
8628
8629 // after saving settings, we are no longer different from the XML on disk
8630 mData->flModifications = 0;
8631 }
8632 catch (HRESULT err)
8633 {
8634 // we assume that error info is set by the thrower
8635 rc = err;
8636
8637 // restore old config
8638 delete pNewConfig;
8639 mData->pMachineConfigFile = pOldConfig;
8640 }
8641 catch (...)
8642 {
8643 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8644 }
8645
8646 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8647 {
8648 /* Fire the data change event, even on failure (since we've already
8649 * committed all data). This is done only for SessionMachines because
8650 * mutable Machine instances are always not registered (i.e. private
8651 * to the client process that creates them) and thus don't need to
8652 * inform callbacks. */
8653 if (isSessionMachine())
8654 mParent->onMachineDataChange(mData->mUuid);
8655 }
8656
8657 LogFlowThisFunc(("rc=%08X\n", rc));
8658 LogFlowThisFuncLeave();
8659 return rc;
8660}
8661
8662/**
8663 * Implementation for saving the machine settings into the given
8664 * settings::MachineConfigFile instance. This copies machine extradata
8665 * from the previous machine config file in the instance data, if any.
8666 *
8667 * This gets called from two locations:
8668 *
8669 * -- Machine::saveSettings(), during the regular XML writing;
8670 *
8671 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8672 * exported to OVF and we write the VirtualBox proprietary XML
8673 * into a <vbox:Machine> tag.
8674 *
8675 * This routine fills all the fields in there, including snapshots, *except*
8676 * for the following:
8677 *
8678 * -- fCurrentStateModified. There is some special logic associated with that.
8679 *
8680 * The caller can then call MachineConfigFile::write() or do something else
8681 * with it.
8682 *
8683 * Caller must hold the machine lock!
8684 *
8685 * This throws XML errors and HRESULT, so the caller must have a catch block!
8686 */
8687void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8688{
8689 // deep copy extradata
8690 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8691
8692 config.uuid = mData->mUuid;
8693
8694 // copy name, description, OS type, teleport, UTC etc.
8695 config.machineUserData = mUserData->s;
8696
8697 if ( mData->mMachineState == MachineState_Saved
8698 || mData->mMachineState == MachineState_Restoring
8699 // when deleting a snapshot we may or may not have a saved state in the current state,
8700 // so let's not assert here please
8701 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8702 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8703 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8704 && (!mSSData->strStateFilePath.isEmpty())
8705 )
8706 )
8707 {
8708 Assert(!mSSData->strStateFilePath.isEmpty());
8709 /* try to make the file name relative to the settings file dir */
8710 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
8711 }
8712 else
8713 {
8714 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
8715 config.strStateFile.setNull();
8716 }
8717
8718 if (mData->mCurrentSnapshot)
8719 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8720 else
8721 config.uuidCurrentSnapshot.clear();
8722
8723 config.timeLastStateChange = mData->mLastStateChange;
8724 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8725 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8726
8727 HRESULT rc = saveHardware(config.hardwareMachine);
8728 if (FAILED(rc)) throw rc;
8729
8730 rc = saveStorageControllers(config.storageMachine);
8731 if (FAILED(rc)) throw rc;
8732
8733 // save machine's media registry if this is VirtualBox 4.0 or later
8734 if (config.canHaveOwnMediaRegistry())
8735 {
8736 // determine machine folder
8737 Utf8Str strMachineFolder = getSettingsFileFull();
8738 strMachineFolder.stripFilename();
8739 mParent->saveMediaRegistry(config.mediaRegistry,
8740 getId(), // only media with registry ID == machine UUID
8741 strMachineFolder);
8742 // this throws HRESULT
8743 }
8744
8745 // save snapshots
8746 rc = saveAllSnapshots(config);
8747 if (FAILED(rc)) throw rc;
8748}
8749
8750/**
8751 * Saves all snapshots of the machine into the given machine config file. Called
8752 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8753 * @param config
8754 * @return
8755 */
8756HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8757{
8758 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8759
8760 HRESULT rc = S_OK;
8761
8762 try
8763 {
8764 config.llFirstSnapshot.clear();
8765
8766 if (mData->mFirstSnapshot)
8767 {
8768 settings::Snapshot snapNew;
8769 config.llFirstSnapshot.push_back(snapNew);
8770
8771 // get reference to the fresh copy of the snapshot on the list and
8772 // work on that copy directly to avoid excessive copying later
8773 settings::Snapshot &snap = config.llFirstSnapshot.front();
8774
8775 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8776 if (FAILED(rc)) throw rc;
8777 }
8778
8779// if (mType == IsSessionMachine)
8780// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8781
8782 }
8783 catch (HRESULT err)
8784 {
8785 /* we assume that error info is set by the thrower */
8786 rc = err;
8787 }
8788 catch (...)
8789 {
8790 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8791 }
8792
8793 return rc;
8794}
8795
8796/**
8797 * Saves the VM hardware configuration. It is assumed that the
8798 * given node is empty.
8799 *
8800 * @param aNode <Hardware> node to save the VM hardware configuration to.
8801 */
8802HRESULT Machine::saveHardware(settings::Hardware &data)
8803{
8804 HRESULT rc = S_OK;
8805
8806 try
8807 {
8808 /* The hardware version attribute (optional).
8809 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8810 if ( mHWData->mHWVersion == "1"
8811 && mSSData->strStateFilePath.isEmpty()
8812 )
8813 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. */
8814
8815 data.strVersion = mHWData->mHWVersion;
8816 data.uuid = mHWData->mHardwareUUID;
8817
8818 // CPU
8819 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8820 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8821 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8822 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8823 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8824 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8825 data.fPAE = !!mHWData->mPAEEnabled;
8826 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8827
8828 /* Standard and Extended CPUID leafs. */
8829 data.llCpuIdLeafs.clear();
8830 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8831 {
8832 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8833 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8834 }
8835 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8836 {
8837 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8838 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8839 }
8840
8841 data.cCPUs = mHWData->mCPUCount;
8842 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8843 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8844
8845 data.llCpus.clear();
8846 if (data.fCpuHotPlug)
8847 {
8848 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8849 {
8850 if (mHWData->mCPUAttached[idx])
8851 {
8852 settings::Cpu cpu;
8853 cpu.ulId = idx;
8854 data.llCpus.push_back(cpu);
8855 }
8856 }
8857 }
8858
8859 // memory
8860 data.ulMemorySizeMB = mHWData->mMemorySize;
8861 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8862
8863 // firmware
8864 data.firmwareType = mHWData->mFirmwareType;
8865
8866 // HID
8867 data.pointingHidType = mHWData->mPointingHidType;
8868 data.keyboardHidType = mHWData->mKeyboardHidType;
8869
8870 // chipset
8871 data.chipsetType = mHWData->mChipsetType;
8872
8873 // HPET
8874 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8875
8876 // boot order
8877 data.mapBootOrder.clear();
8878 for (size_t i = 0;
8879 i < RT_ELEMENTS(mHWData->mBootOrder);
8880 ++i)
8881 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8882
8883 // display
8884 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8885 data.cMonitors = mHWData->mMonitorCount;
8886 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8887 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8888
8889 /* VRDEServer settings (optional) */
8890 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8891 if (FAILED(rc)) throw rc;
8892
8893 /* BIOS (required) */
8894 rc = mBIOSSettings->saveSettings(data.biosSettings);
8895 if (FAILED(rc)) throw rc;
8896
8897 /* USB Controller (required) */
8898 rc = mUSBController->saveSettings(data.usbController);
8899 if (FAILED(rc)) throw rc;
8900
8901 /* Network adapters (required) */
8902 data.llNetworkAdapters.clear();
8903 for (ULONG slot = 0;
8904 slot < RT_ELEMENTS(mNetworkAdapters);
8905 ++slot)
8906 {
8907 settings::NetworkAdapter nic;
8908 nic.ulSlot = slot;
8909 rc = mNetworkAdapters[slot]->saveSettings(nic);
8910 if (FAILED(rc)) throw rc;
8911
8912 data.llNetworkAdapters.push_back(nic);
8913 }
8914
8915 /* Serial ports */
8916 data.llSerialPorts.clear();
8917 for (ULONG slot = 0;
8918 slot < RT_ELEMENTS(mSerialPorts);
8919 ++slot)
8920 {
8921 settings::SerialPort s;
8922 s.ulSlot = slot;
8923 rc = mSerialPorts[slot]->saveSettings(s);
8924 if (FAILED(rc)) return rc;
8925
8926 data.llSerialPorts.push_back(s);
8927 }
8928
8929 /* Parallel ports */
8930 data.llParallelPorts.clear();
8931 for (ULONG slot = 0;
8932 slot < RT_ELEMENTS(mParallelPorts);
8933 ++slot)
8934 {
8935 settings::ParallelPort p;
8936 p.ulSlot = slot;
8937 rc = mParallelPorts[slot]->saveSettings(p);
8938 if (FAILED(rc)) return rc;
8939
8940 data.llParallelPorts.push_back(p);
8941 }
8942
8943 /* Audio adapter */
8944 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8945 if (FAILED(rc)) return rc;
8946
8947 /* Shared folders */
8948 data.llSharedFolders.clear();
8949 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8950 it != mHWData->mSharedFolders.end();
8951 ++it)
8952 {
8953 SharedFolder *pSF = *it;
8954 AutoCaller sfCaller(pSF);
8955 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8956 settings::SharedFolder sf;
8957 sf.strName = pSF->getName();
8958 sf.strHostPath = pSF->getHostPath();
8959 sf.fWritable = !!pSF->isWritable();
8960 sf.fAutoMount = !!pSF->isAutoMounted();
8961
8962 data.llSharedFolders.push_back(sf);
8963 }
8964
8965 // clipboard
8966 data.clipboardMode = mHWData->mClipboardMode;
8967
8968 /* Guest */
8969 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8970
8971 // IO settings
8972 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8973 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8974
8975 /* BandwidthControl (required) */
8976 rc = mBandwidthControl->saveSettings(data.ioSettings);
8977 if (FAILED(rc)) throw rc;
8978
8979 /* Host PCI devices */
8980 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
8981 it != mHWData->mPciDeviceAssignments.end();
8982 ++it)
8983 {
8984 ComObjPtr<PciDeviceAttachment> pda = *it;
8985 settings::HostPciDeviceAttachment hpda;
8986
8987 rc = pda->saveSettings(hpda);
8988 if (FAILED(rc)) throw rc;
8989
8990 data.pciAttachments.push_back(hpda);
8991 }
8992
8993
8994 // guest properties
8995 data.llGuestProperties.clear();
8996#ifdef VBOX_WITH_GUEST_PROPS
8997 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8998 it != mHWData->mGuestProperties.end();
8999 ++it)
9000 {
9001 HWData::GuestProperty property = *it;
9002
9003 /* Remove transient guest properties at shutdown unless we
9004 * are saving state */
9005 if ( ( mData->mMachineState == MachineState_PoweredOff
9006 || mData->mMachineState == MachineState_Aborted
9007 || mData->mMachineState == MachineState_Teleported)
9008 && ( property.mFlags & guestProp::TRANSIENT
9009 || property.mFlags & guestProp::TRANSRESET))
9010 continue;
9011 settings::GuestProperty prop;
9012 prop.strName = property.strName;
9013 prop.strValue = property.strValue;
9014 prop.timestamp = property.mTimestamp;
9015 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
9016 guestProp::writeFlags(property.mFlags, szFlags);
9017 prop.strFlags = szFlags;
9018
9019 data.llGuestProperties.push_back(prop);
9020 }
9021
9022 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
9023 /* I presume this doesn't require a backup(). */
9024 mData->mGuestPropertiesModified = FALSE;
9025#endif /* VBOX_WITH_GUEST_PROPS defined */
9026 }
9027 catch(std::bad_alloc &)
9028 {
9029 return E_OUTOFMEMORY;
9030 }
9031
9032 AssertComRC(rc);
9033 return rc;
9034}
9035
9036/**
9037 * Saves the storage controller configuration.
9038 *
9039 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
9040 */
9041HRESULT Machine::saveStorageControllers(settings::Storage &data)
9042{
9043 data.llStorageControllers.clear();
9044
9045 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
9046 it != mStorageControllers->end();
9047 ++it)
9048 {
9049 HRESULT rc;
9050 ComObjPtr<StorageController> pCtl = *it;
9051
9052 settings::StorageController ctl;
9053 ctl.strName = pCtl->getName();
9054 ctl.controllerType = pCtl->getControllerType();
9055 ctl.storageBus = pCtl->getStorageBus();
9056 ctl.ulInstance = pCtl->getInstance();
9057 ctl.fBootable = pCtl->getBootable();
9058
9059 /* Save the port count. */
9060 ULONG portCount;
9061 rc = pCtl->COMGETTER(PortCount)(&portCount);
9062 ComAssertComRCRet(rc, rc);
9063 ctl.ulPortCount = portCount;
9064
9065 /* Save fUseHostIOCache */
9066 BOOL fUseHostIOCache;
9067 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9068 ComAssertComRCRet(rc, rc);
9069 ctl.fUseHostIOCache = !!fUseHostIOCache;
9070
9071 /* Save IDE emulation settings. */
9072 if (ctl.controllerType == StorageControllerType_IntelAhci)
9073 {
9074 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
9075 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
9076 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
9077 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
9078 )
9079 ComAssertComRCRet(rc, rc);
9080 }
9081
9082 /* save the devices now. */
9083 rc = saveStorageDevices(pCtl, ctl);
9084 ComAssertComRCRet(rc, rc);
9085
9086 data.llStorageControllers.push_back(ctl);
9087 }
9088
9089 return S_OK;
9090}
9091
9092/**
9093 * Saves the hard disk configuration.
9094 */
9095HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
9096 settings::StorageController &data)
9097{
9098 MediaData::AttachmentList atts;
9099
9100 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
9101 if (FAILED(rc)) return rc;
9102
9103 data.llAttachedDevices.clear();
9104 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9105 it != atts.end();
9106 ++it)
9107 {
9108 settings::AttachedDevice dev;
9109
9110 MediumAttachment *pAttach = *it;
9111 Medium *pMedium = pAttach->getMedium();
9112
9113 dev.deviceType = pAttach->getType();
9114 dev.lPort = pAttach->getPort();
9115 dev.lDevice = pAttach->getDevice();
9116 if (pMedium)
9117 {
9118 if (pMedium->isHostDrive())
9119 dev.strHostDriveSrc = pMedium->getLocationFull();
9120 else
9121 dev.uuid = pMedium->getId();
9122 dev.fPassThrough = pAttach->getPassthrough();
9123 dev.fTempEject = pAttach->getTempEject();
9124 dev.fNonRotational = pAttach->getNonRotational();
9125 }
9126
9127 dev.strBwGroup = pAttach->getBandwidthGroup();
9128
9129 data.llAttachedDevices.push_back(dev);
9130 }
9131
9132 return S_OK;
9133}
9134
9135/**
9136 * Saves machine state settings as defined by aFlags
9137 * (SaveSTS_* values).
9138 *
9139 * @param aFlags Combination of SaveSTS_* flags.
9140 *
9141 * @note Locks objects for writing.
9142 */
9143HRESULT Machine::saveStateSettings(int aFlags)
9144{
9145 if (aFlags == 0)
9146 return S_OK;
9147
9148 AutoCaller autoCaller(this);
9149 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9150
9151 /* This object's write lock is also necessary to serialize file access
9152 * (prevent concurrent reads and writes) */
9153 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9154
9155 HRESULT rc = S_OK;
9156
9157 Assert(mData->pMachineConfigFile);
9158
9159 try
9160 {
9161 if (aFlags & SaveSTS_CurStateModified)
9162 mData->pMachineConfigFile->fCurrentStateModified = true;
9163
9164 if (aFlags & SaveSTS_StateFilePath)
9165 {
9166 if (!mSSData->strStateFilePath.isEmpty())
9167 /* try to make the file name relative to the settings file dir */
9168 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
9169 else
9170 mData->pMachineConfigFile->strStateFile.setNull();
9171 }
9172
9173 if (aFlags & SaveSTS_StateTimeStamp)
9174 {
9175 Assert( mData->mMachineState != MachineState_Aborted
9176 || mSSData->strStateFilePath.isEmpty());
9177
9178 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
9179
9180 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
9181//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
9182 }
9183
9184 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
9185 }
9186 catch (...)
9187 {
9188 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
9189 }
9190
9191 return rc;
9192}
9193
9194/**
9195 * Ensures that the given medium is added to a media registry. If this machine
9196 * was created with 4.0 or later, then the machine registry is used. Otherwise
9197 * the global VirtualBox media registry is used. If the medium was actually
9198 * added to a registry (because it wasn't in the registry yet), the UUID of
9199 * that registry is added to the given list so that the caller can save the
9200 * registry.
9201 *
9202 * Caller must hold machine read lock!
9203 *
9204 * @param pMedium
9205 * @param llRegistriesThatNeedSaving
9206 * @param puuid Optional buffer that receives the registry UUID that was used.
9207 */
9208void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
9209 GuidList &llRegistriesThatNeedSaving,
9210 Guid *puuid)
9211{
9212 // decide which medium registry to use now that the medium is attached:
9213 Guid uuid;
9214 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
9215 // machine XML is VirtualBox 4.0 or higher:
9216 uuid = getId(); // machine UUID
9217 else
9218 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
9219
9220 AutoCaller autoCaller(pMedium);
9221 if (FAILED(autoCaller.rc())) return;
9222 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9223
9224 if (pMedium->addRegistry(uuid, false /* fRecurse */))
9225 // registry actually changed:
9226 VirtualBox::addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
9227
9228 if (puuid)
9229 *puuid = uuid;
9230}
9231
9232/**
9233 * Creates differencing hard disks for all normal hard disks attached to this
9234 * machine and a new set of attachments to refer to created disks.
9235 *
9236 * Used when taking a snapshot or when deleting the current state. Gets called
9237 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
9238 *
9239 * This method assumes that mMediaData contains the original hard disk attachments
9240 * it needs to create diffs for. On success, these attachments will be replaced
9241 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
9242 * called to delete created diffs which will also rollback mMediaData and restore
9243 * whatever was backed up before calling this method.
9244 *
9245 * Attachments with non-normal hard disks are left as is.
9246 *
9247 * If @a aOnline is @c false then the original hard disks that require implicit
9248 * diffs will be locked for reading. Otherwise it is assumed that they are
9249 * already locked for writing (when the VM was started). Note that in the latter
9250 * case it is responsibility of the caller to lock the newly created diffs for
9251 * writing if this method succeeds.
9252 *
9253 * @param aProgress Progress object to run (must contain at least as
9254 * many operations left as the number of hard disks
9255 * attached).
9256 * @param aOnline Whether the VM was online prior to this operation.
9257 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9258 *
9259 * @note The progress object is not marked as completed, neither on success nor
9260 * on failure. This is a responsibility of the caller.
9261 *
9262 * @note Locks this object for writing.
9263 */
9264HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
9265 ULONG aWeight,
9266 bool aOnline,
9267 GuidList *pllRegistriesThatNeedSaving)
9268{
9269 LogFlowThisFunc(("aOnline=%d\n", aOnline));
9270
9271 AutoCaller autoCaller(this);
9272 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9273
9274 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9275
9276 /* must be in a protective state because we leave the lock below */
9277 AssertReturn( mData->mMachineState == MachineState_Saving
9278 || mData->mMachineState == MachineState_LiveSnapshotting
9279 || mData->mMachineState == MachineState_RestoringSnapshot
9280 || mData->mMachineState == MachineState_DeletingSnapshot
9281 , E_FAIL);
9282
9283 HRESULT rc = S_OK;
9284
9285 MediumLockListMap lockedMediaOffline;
9286 MediumLockListMap *lockedMediaMap;
9287 if (aOnline)
9288 lockedMediaMap = &mData->mSession.mLockedMedia;
9289 else
9290 lockedMediaMap = &lockedMediaOffline;
9291
9292 try
9293 {
9294 if (!aOnline)
9295 {
9296 /* lock all attached hard disks early to detect "in use"
9297 * situations before creating actual diffs */
9298 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9299 it != mMediaData->mAttachments.end();
9300 ++it)
9301 {
9302 MediumAttachment* pAtt = *it;
9303 if (pAtt->getType() == DeviceType_HardDisk)
9304 {
9305 Medium* pMedium = pAtt->getMedium();
9306 Assert(pMedium);
9307
9308 MediumLockList *pMediumLockList(new MediumLockList());
9309 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
9310 false /* fMediumLockWrite */,
9311 NULL,
9312 *pMediumLockList);
9313 if (FAILED(rc))
9314 {
9315 delete pMediumLockList;
9316 throw rc;
9317 }
9318 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
9319 if (FAILED(rc))
9320 {
9321 throw setError(rc,
9322 tr("Collecting locking information for all attached media failed"));
9323 }
9324 }
9325 }
9326
9327 /* Now lock all media. If this fails, nothing is locked. */
9328 rc = lockedMediaMap->Lock();
9329 if (FAILED(rc))
9330 {
9331 throw setError(rc,
9332 tr("Locking of attached media failed"));
9333 }
9334 }
9335
9336 /* remember the current list (note that we don't use backup() since
9337 * mMediaData may be already backed up) */
9338 MediaData::AttachmentList atts = mMediaData->mAttachments;
9339
9340 /* start from scratch */
9341 mMediaData->mAttachments.clear();
9342
9343 /* go through remembered attachments and create diffs for normal hard
9344 * disks and attach them */
9345 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9346 it != atts.end();
9347 ++it)
9348 {
9349 MediumAttachment* pAtt = *it;
9350
9351 DeviceType_T devType = pAtt->getType();
9352 Medium* pMedium = pAtt->getMedium();
9353
9354 if ( devType != DeviceType_HardDisk
9355 || pMedium == NULL
9356 || pMedium->getType() != MediumType_Normal)
9357 {
9358 /* copy the attachment as is */
9359
9360 /** @todo the progress object created in Console::TakeSnaphot
9361 * only expects operations for hard disks. Later other
9362 * device types need to show up in the progress as well. */
9363 if (devType == DeviceType_HardDisk)
9364 {
9365 if (pMedium == NULL)
9366 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9367 aWeight); // weight
9368 else
9369 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9370 pMedium->getBase()->getName().c_str()).raw(),
9371 aWeight); // weight
9372 }
9373
9374 mMediaData->mAttachments.push_back(pAtt);
9375 continue;
9376 }
9377
9378 /* need a diff */
9379 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9380 pMedium->getBase()->getName().c_str()).raw(),
9381 aWeight); // weight
9382
9383 Utf8Str strFullSnapshotFolder;
9384 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9385
9386 ComObjPtr<Medium> diff;
9387 diff.createObject();
9388 // store the diff in the same registry as the parent
9389 // (this cannot fail here because we can't create implicit diffs for
9390 // unregistered images)
9391 Guid uuidRegistryParent;
9392 bool fInRegistry = pMedium->getFirstRegistryMachineId(uuidRegistryParent);
9393 Assert(fInRegistry); NOREF(fInRegistry);
9394 rc = diff->init(mParent,
9395 pMedium->getPreferredDiffFormat(),
9396 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9397 uuidRegistryParent,
9398 pllRegistriesThatNeedSaving);
9399 if (FAILED(rc)) throw rc;
9400
9401 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9402 * the push_back? Looks like we're going to leave medium with the
9403 * wrong kind of lock (general issue with if we fail anywhere at all)
9404 * and an orphaned VDI in the snapshots folder. */
9405
9406 /* update the appropriate lock list */
9407 MediumLockList *pMediumLockList;
9408 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9409 AssertComRCThrowRC(rc);
9410 if (aOnline)
9411 {
9412 rc = pMediumLockList->Update(pMedium, false);
9413 AssertComRCThrowRC(rc);
9414 }
9415
9416 /* leave the lock before the potentially lengthy operation */
9417 alock.leave();
9418 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9419 pMediumLockList,
9420 NULL /* aProgress */,
9421 true /* aWait */,
9422 pllRegistriesThatNeedSaving);
9423 alock.enter();
9424 if (FAILED(rc)) throw rc;
9425
9426 rc = lockedMediaMap->Unlock();
9427 AssertComRCThrowRC(rc);
9428 rc = pMediumLockList->Append(diff, true);
9429 AssertComRCThrowRC(rc);
9430 rc = lockedMediaMap->Lock();
9431 AssertComRCThrowRC(rc);
9432
9433 rc = diff->addBackReference(mData->mUuid);
9434 AssertComRCThrowRC(rc);
9435
9436 /* add a new attachment */
9437 ComObjPtr<MediumAttachment> attachment;
9438 attachment.createObject();
9439 rc = attachment->init(this,
9440 diff,
9441 pAtt->getControllerName(),
9442 pAtt->getPort(),
9443 pAtt->getDevice(),
9444 DeviceType_HardDisk,
9445 true /* aImplicit */,
9446 false /* aPassthrough */,
9447 false /* aTempEject */,
9448 pAtt->getNonRotational(),
9449 pAtt->getBandwidthGroup());
9450 if (FAILED(rc)) throw rc;
9451
9452 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9453 AssertComRCThrowRC(rc);
9454 mMediaData->mAttachments.push_back(attachment);
9455 }
9456 }
9457 catch (HRESULT aRC) { rc = aRC; }
9458
9459 /* unlock all hard disks we locked */
9460 if (!aOnline)
9461 {
9462 ErrorInfoKeeper eik;
9463
9464 HRESULT rc1 = lockedMediaMap->Clear();
9465 AssertComRC(rc1);
9466 }
9467
9468 if (FAILED(rc))
9469 {
9470 MultiResult mrc = rc;
9471
9472 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9473 }
9474
9475 return rc;
9476}
9477
9478/**
9479 * Deletes implicit differencing hard disks created either by
9480 * #createImplicitDiffs() or by #AttachDevice() and rolls back mMediaData.
9481 *
9482 * Note that to delete hard disks created by #AttachDevice() this method is
9483 * called from #fixupMedia() when the changes are rolled back.
9484 *
9485 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9486 *
9487 * @note Locks this object for writing.
9488 */
9489HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9490{
9491 AutoCaller autoCaller(this);
9492 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9493
9494 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9495 LogFlowThisFuncEnter();
9496
9497 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9498
9499 HRESULT rc = S_OK;
9500
9501 MediaData::AttachmentList implicitAtts;
9502
9503 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9504
9505 /* enumerate new attachments */
9506 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9507 it != mMediaData->mAttachments.end();
9508 ++it)
9509 {
9510 ComObjPtr<Medium> hd = (*it)->getMedium();
9511 if (hd.isNull())
9512 continue;
9513
9514 if ((*it)->isImplicit())
9515 {
9516 /* deassociate and mark for deletion */
9517 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
9518 rc = hd->removeBackReference(mData->mUuid);
9519 AssertComRC(rc);
9520 implicitAtts.push_back(*it);
9521 continue;
9522 }
9523
9524 /* was this hard disk attached before? */
9525 if (!findAttachment(oldAtts, hd))
9526 {
9527 /* no: de-associate */
9528 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9529 rc = hd->removeBackReference(mData->mUuid);
9530 AssertComRC(rc);
9531 continue;
9532 }
9533 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9534 }
9535
9536 /* rollback hard disk changes */
9537 mMediaData.rollback();
9538
9539 MultiResult mrc(S_OK);
9540
9541 /* delete unused implicit diffs */
9542 if (implicitAtts.size() != 0)
9543 {
9544 /* will leave the lock before the potentially lengthy
9545 * operation, so protect with the special state (unless already
9546 * protected) */
9547 MachineState_T oldState = mData->mMachineState;
9548 if ( oldState != MachineState_Saving
9549 && oldState != MachineState_LiveSnapshotting
9550 && oldState != MachineState_RestoringSnapshot
9551 && oldState != MachineState_DeletingSnapshot
9552 && oldState != MachineState_DeletingSnapshotOnline
9553 && oldState != MachineState_DeletingSnapshotPaused
9554 )
9555 setMachineState(MachineState_SettingUp);
9556
9557 alock.leave();
9558
9559 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9560 it != implicitAtts.end();
9561 ++it)
9562 {
9563 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9564 ComObjPtr<Medium> hd = (*it)->getMedium();
9565
9566 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9567 pllRegistriesThatNeedSaving);
9568 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9569 mrc = rc;
9570 }
9571
9572 alock.enter();
9573
9574 if (mData->mMachineState == MachineState_SettingUp)
9575 setMachineState(oldState);
9576 }
9577
9578 return mrc;
9579}
9580
9581/**
9582 * Looks through the given list of media attachments for one with the given parameters
9583 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9584 * can be searched as well if needed.
9585 *
9586 * @param list
9587 * @param aControllerName
9588 * @param aControllerPort
9589 * @param aDevice
9590 * @return
9591 */
9592MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9593 IN_BSTR aControllerName,
9594 LONG aControllerPort,
9595 LONG aDevice)
9596{
9597 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9598 it != ll.end();
9599 ++it)
9600 {
9601 MediumAttachment *pAttach = *it;
9602 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9603 return pAttach;
9604 }
9605
9606 return NULL;
9607}
9608
9609/**
9610 * Looks through the given list of media attachments for one with the given parameters
9611 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9612 * can be searched as well if needed.
9613 *
9614 * @param list
9615 * @param aControllerName
9616 * @param aControllerPort
9617 * @param aDevice
9618 * @return
9619 */
9620MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9621 ComObjPtr<Medium> pMedium)
9622{
9623 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9624 it != ll.end();
9625 ++it)
9626 {
9627 MediumAttachment *pAttach = *it;
9628 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9629 if (pMediumThis == pMedium)
9630 return pAttach;
9631 }
9632
9633 return NULL;
9634}
9635
9636/**
9637 * Looks through the given list of media attachments for one with the given parameters
9638 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9639 * can be searched as well if needed.
9640 *
9641 * @param list
9642 * @param aControllerName
9643 * @param aControllerPort
9644 * @param aDevice
9645 * @return
9646 */
9647MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9648 Guid &id)
9649{
9650 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9651 it != ll.end();
9652 ++it)
9653 {
9654 MediumAttachment *pAttach = *it;
9655 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9656 if (pMediumThis->getId() == id)
9657 return pAttach;
9658 }
9659
9660 return NULL;
9661}
9662
9663/**
9664 * Main implementation for Machine::DetachDevice. This also gets called
9665 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9666 *
9667 * @param pAttach Medium attachment to detach.
9668 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9669 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9670 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9671 * @return
9672 */
9673HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9674 AutoWriteLock &writeLock,
9675 Snapshot *pSnapshot,
9676 GuidList *pllRegistriesThatNeedSaving)
9677{
9678 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9679 DeviceType_T mediumType = pAttach->getType();
9680
9681 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9682
9683 if (pAttach->isImplicit())
9684 {
9685 /* attempt to implicitly delete the implicitly created diff */
9686
9687 /// @todo move the implicit flag from MediumAttachment to Medium
9688 /// and forbid any hard disk operation when it is implicit. Or maybe
9689 /// a special media state for it to make it even more simple.
9690
9691 Assert(mMediaData.isBackedUp());
9692
9693 /* will leave the lock before the potentially lengthy operation, so
9694 * protect with the special state */
9695 MachineState_T oldState = mData->mMachineState;
9696 setMachineState(MachineState_SettingUp);
9697
9698 writeLock.release();
9699
9700 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
9701 true /*aWait*/,
9702 pllRegistriesThatNeedSaving);
9703
9704 writeLock.acquire();
9705
9706 setMachineState(oldState);
9707
9708 if (FAILED(rc)) return rc;
9709 }
9710
9711 setModified(IsModified_Storage);
9712 mMediaData.backup();
9713
9714 // we cannot use erase (it) below because backup() above will create
9715 // a copy of the list and make this copy active, but the iterator
9716 // still refers to the original and is not valid for the copy
9717 mMediaData->mAttachments.remove(pAttach);
9718
9719 if (!oldmedium.isNull())
9720 {
9721 // if this is from a snapshot, do not defer detachment to commitMedia()
9722 if (pSnapshot)
9723 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9724 // else if non-hard disk media, do not defer detachment to commitMedia() either
9725 else if (mediumType != DeviceType_HardDisk)
9726 oldmedium->removeBackReference(mData->mUuid);
9727 }
9728
9729 return S_OK;
9730}
9731
9732/**
9733 * Goes thru all media of the given list and
9734 *
9735 * 1) calls detachDevice() on each of them for this machine and
9736 * 2) adds all Medium objects found in the process to the given list,
9737 * depending on cleanupMode.
9738 *
9739 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
9740 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
9741 * media to the list.
9742 *
9743 * This gets called from Machine::Unregister, both for the actual Machine and
9744 * the SnapshotMachine objects that might be found in the snapshots.
9745 *
9746 * Requires caller and locking. The machine lock must be passed in because it
9747 * will be passed on to detachDevice which needs it for temporary unlocking.
9748 *
9749 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9750 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9751 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9752 * otherwise no media get added.
9753 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9754 * @return
9755 */
9756HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9757 Snapshot *pSnapshot,
9758 CleanupMode_T cleanupMode,
9759 MediaList &llMedia)
9760{
9761 Assert(isWriteLockOnCurrentThread());
9762
9763 HRESULT rc;
9764
9765 // make a temporary list because detachDevice invalidates iterators into
9766 // mMediaData->mAttachments
9767 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9768
9769 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9770 it != llAttachments2.end();
9771 ++it)
9772 {
9773 ComObjPtr<MediumAttachment> &pAttach = *it;
9774 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9775
9776 if (!pMedium.isNull())
9777 {
9778 AutoCaller mac(pMedium);
9779 if (FAILED(mac.rc())) return mac.rc();
9780 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
9781 DeviceType_T devType = pMedium->getDeviceType();
9782 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9783 && devType == DeviceType_HardDisk)
9784 || (cleanupMode == CleanupMode_Full)
9785 )
9786 {
9787 llMedia.push_back(pMedium);
9788 ComObjPtr<Medium> pParent = pMedium->getParent();
9789 /*
9790 * Search for medias which are not attached to any machine, but
9791 * in the chain to an attached disk. Mediums are only consided
9792 * if they are:
9793 * - have only one child
9794 * - no references to any machines
9795 * - are of normal medium type
9796 */
9797 while (!pParent.isNull())
9798 {
9799 AutoCaller mac1(pParent);
9800 if (FAILED(mac1.rc())) return mac1.rc();
9801 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
9802 if (pParent->getChildren().size() == 1)
9803 {
9804 if ( pParent->getMachineBackRefCount() == 0
9805 && pParent->getType() == MediumType_Normal
9806 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
9807 llMedia.push_back(pParent);
9808 }else
9809 break;
9810 pParent = pParent->getParent();
9811 }
9812 }
9813 }
9814
9815 // real machine: then we need to use the proper method
9816 rc = detachDevice(pAttach,
9817 writeLock,
9818 pSnapshot,
9819 NULL /* pfNeedsSaveSettings */);
9820
9821 if (FAILED(rc))
9822 return rc;
9823 }
9824
9825 return S_OK;
9826}
9827
9828/**
9829 * Perform deferred hard disk detachments.
9830 *
9831 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9832 * backed up).
9833 *
9834 * If @a aOnline is @c true then this method will also unlock the old hard disks
9835 * for which the new implicit diffs were created and will lock these new diffs for
9836 * writing.
9837 *
9838 * @param aOnline Whether the VM was online prior to this operation.
9839 *
9840 * @note Locks this object for writing!
9841 */
9842void Machine::commitMedia(bool aOnline /*= false*/)
9843{
9844 AutoCaller autoCaller(this);
9845 AssertComRCReturnVoid(autoCaller.rc());
9846
9847 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9848
9849 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9850
9851 HRESULT rc = S_OK;
9852
9853 /* no attach/detach operations -- nothing to do */
9854 if (!mMediaData.isBackedUp())
9855 return;
9856
9857 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9858 bool fMediaNeedsLocking = false;
9859
9860 /* enumerate new attachments */
9861 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9862 it != mMediaData->mAttachments.end();
9863 ++it)
9864 {
9865 MediumAttachment *pAttach = *it;
9866
9867 pAttach->commit();
9868
9869 Medium* pMedium = pAttach->getMedium();
9870 bool fImplicit = pAttach->isImplicit();
9871
9872 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9873 (pMedium) ? pMedium->getName().c_str() : "NULL",
9874 fImplicit));
9875
9876 /** @todo convert all this Machine-based voodoo to MediumAttachment
9877 * based commit logic. */
9878 if (fImplicit)
9879 {
9880 /* convert implicit attachment to normal */
9881 pAttach->setImplicit(false);
9882
9883 if ( aOnline
9884 && pMedium
9885 && pAttach->getType() == DeviceType_HardDisk
9886 )
9887 {
9888 ComObjPtr<Medium> parent = pMedium->getParent();
9889 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9890
9891 /* update the appropriate lock list */
9892 MediumLockList *pMediumLockList;
9893 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9894 AssertComRC(rc);
9895 if (pMediumLockList)
9896 {
9897 /* unlock if there's a need to change the locking */
9898 if (!fMediaNeedsLocking)
9899 {
9900 rc = mData->mSession.mLockedMedia.Unlock();
9901 AssertComRC(rc);
9902 fMediaNeedsLocking = true;
9903 }
9904 rc = pMediumLockList->Update(parent, false);
9905 AssertComRC(rc);
9906 rc = pMediumLockList->Append(pMedium, true);
9907 AssertComRC(rc);
9908 }
9909 }
9910
9911 continue;
9912 }
9913
9914 if (pMedium)
9915 {
9916 /* was this medium attached before? */
9917 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9918 oldIt != oldAtts.end();
9919 ++oldIt)
9920 {
9921 MediumAttachment *pOldAttach = *oldIt;
9922 if (pOldAttach->getMedium() == pMedium)
9923 {
9924 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9925
9926 /* yes: remove from old to avoid de-association */
9927 oldAtts.erase(oldIt);
9928 break;
9929 }
9930 }
9931 }
9932 }
9933
9934 /* enumerate remaining old attachments and de-associate from the
9935 * current machine state */
9936 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9937 it != oldAtts.end();
9938 ++it)
9939 {
9940 MediumAttachment *pAttach = *it;
9941 Medium* pMedium = pAttach->getMedium();
9942
9943 /* Detach only hard disks, since DVD/floppy media is detached
9944 * instantly in MountMedium. */
9945 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9946 {
9947 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9948
9949 /* now de-associate from the current machine state */
9950 rc = pMedium->removeBackReference(mData->mUuid);
9951 AssertComRC(rc);
9952
9953 if (aOnline)
9954 {
9955 /* unlock since medium is not used anymore */
9956 MediumLockList *pMediumLockList;
9957 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9958 AssertComRC(rc);
9959 if (pMediumLockList)
9960 {
9961 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9962 AssertComRC(rc);
9963 }
9964 }
9965 }
9966 }
9967
9968 /* take media locks again so that the locking state is consistent */
9969 if (fMediaNeedsLocking)
9970 {
9971 Assert(aOnline);
9972 rc = mData->mSession.mLockedMedia.Lock();
9973 AssertComRC(rc);
9974 }
9975
9976 /* commit the hard disk changes */
9977 mMediaData.commit();
9978
9979 if (isSessionMachine())
9980 {
9981 /*
9982 * Update the parent machine to point to the new owner.
9983 * This is necessary because the stored parent will point to the
9984 * session machine otherwise and cause crashes or errors later
9985 * when the session machine gets invalid.
9986 */
9987 /** @todo Change the MediumAttachment class to behave like any other
9988 * class in this regard by creating peer MediumAttachment
9989 * objects for session machines and share the data with the peer
9990 * machine.
9991 */
9992 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9993 it != mMediaData->mAttachments.end();
9994 ++it)
9995 {
9996 (*it)->updateParentMachine(mPeer);
9997 }
9998
9999 /* attach new data to the primary machine and reshare it */
10000 mPeer->mMediaData.attach(mMediaData);
10001 }
10002
10003 return;
10004}
10005
10006/**
10007 * Perform deferred deletion of implicitly created diffs.
10008 *
10009 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
10010 * backed up).
10011 *
10012 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
10013 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
10014 *
10015 * @note Locks this object for writing!
10016 *
10017 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
10018 */
10019void Machine::rollbackMedia()
10020{
10021 AutoCaller autoCaller(this);
10022 AssertComRCReturnVoid (autoCaller.rc());
10023
10024 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10025
10026 LogFlowThisFunc(("Entering\n"));
10027
10028 HRESULT rc = S_OK;
10029
10030 /* no attach/detach operations -- nothing to do */
10031 if (!mMediaData.isBackedUp())
10032 return;
10033
10034 /* enumerate new attachments */
10035 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10036 it != mMediaData->mAttachments.end();
10037 ++it)
10038 {
10039 MediumAttachment *pAttach = *it;
10040 /* Fix up the backrefs for DVD/floppy media. */
10041 if (pAttach->getType() != DeviceType_HardDisk)
10042 {
10043 Medium* pMedium = pAttach->getMedium();
10044 if (pMedium)
10045 {
10046 rc = pMedium->removeBackReference(mData->mUuid);
10047 AssertComRC(rc);
10048 }
10049 }
10050
10051 (*it)->rollback();
10052
10053 pAttach = *it;
10054 /* Fix up the backrefs for DVD/floppy media. */
10055 if (pAttach->getType() != DeviceType_HardDisk)
10056 {
10057 Medium* pMedium = pAttach->getMedium();
10058 if (pMedium)
10059 {
10060 rc = pMedium->addBackReference(mData->mUuid);
10061 AssertComRC(rc);
10062 }
10063 }
10064 }
10065
10066 /** @todo convert all this Machine-based voodoo to MediumAttachment
10067 * based rollback logic. */
10068 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
10069 // which gets called if Machine::registeredInit() fails...
10070 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
10071
10072 return;
10073}
10074
10075/**
10076 * Returns true if the settings file is located in the directory named exactly
10077 * as the machine; this means, among other things, that the machine directory
10078 * should be auto-renamed.
10079 *
10080 * @param aSettingsDir if not NULL, the full machine settings file directory
10081 * name will be assigned there.
10082 *
10083 * @note Doesn't lock anything.
10084 * @note Not thread safe (must be called from this object's lock).
10085 */
10086bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
10087{
10088 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
10089 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
10090 if (aSettingsDir)
10091 *aSettingsDir = strMachineDirName;
10092 strMachineDirName.stripPath(); // vmname
10093 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
10094 strConfigFileOnly.stripPath() // vmname.vbox
10095 .stripExt(); // vmname
10096
10097 AssertReturn(!strMachineDirName.isEmpty(), false);
10098 AssertReturn(!strConfigFileOnly.isEmpty(), false);
10099
10100 return strMachineDirName == strConfigFileOnly;
10101}
10102
10103/**
10104 * Discards all changes to machine settings.
10105 *
10106 * @param aNotify Whether to notify the direct session about changes or not.
10107 *
10108 * @note Locks objects for writing!
10109 */
10110void Machine::rollback(bool aNotify)
10111{
10112 AutoCaller autoCaller(this);
10113 AssertComRCReturn(autoCaller.rc(), (void)0);
10114
10115 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10116
10117 if (!mStorageControllers.isNull())
10118 {
10119 if (mStorageControllers.isBackedUp())
10120 {
10121 /* unitialize all new devices (absent in the backed up list). */
10122 StorageControllerList::const_iterator it = mStorageControllers->begin();
10123 StorageControllerList *backedList = mStorageControllers.backedUpData();
10124 while (it != mStorageControllers->end())
10125 {
10126 if ( std::find(backedList->begin(), backedList->end(), *it)
10127 == backedList->end()
10128 )
10129 {
10130 (*it)->uninit();
10131 }
10132 ++it;
10133 }
10134
10135 /* restore the list */
10136 mStorageControllers.rollback();
10137 }
10138
10139 /* rollback any changes to devices after restoring the list */
10140 if (mData->flModifications & IsModified_Storage)
10141 {
10142 StorageControllerList::const_iterator it = mStorageControllers->begin();
10143 while (it != mStorageControllers->end())
10144 {
10145 (*it)->rollback();
10146 ++it;
10147 }
10148 }
10149 }
10150
10151 mUserData.rollback();
10152
10153 mHWData.rollback();
10154
10155 if (mData->flModifications & IsModified_Storage)
10156 rollbackMedia();
10157
10158 if (mBIOSSettings)
10159 mBIOSSettings->rollback();
10160
10161 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
10162 mVRDEServer->rollback();
10163
10164 if (mAudioAdapter)
10165 mAudioAdapter->rollback();
10166
10167 if (mUSBController && (mData->flModifications & IsModified_USB))
10168 mUSBController->rollback();
10169
10170 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
10171 mBandwidthControl->rollback();
10172
10173 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
10174 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
10175 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
10176
10177 if (mData->flModifications & IsModified_NetworkAdapters)
10178 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10179 if ( mNetworkAdapters[slot]
10180 && mNetworkAdapters[slot]->isModified())
10181 {
10182 mNetworkAdapters[slot]->rollback();
10183 networkAdapters[slot] = mNetworkAdapters[slot];
10184 }
10185
10186 if (mData->flModifications & IsModified_SerialPorts)
10187 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10188 if ( mSerialPorts[slot]
10189 && mSerialPorts[slot]->isModified())
10190 {
10191 mSerialPorts[slot]->rollback();
10192 serialPorts[slot] = mSerialPorts[slot];
10193 }
10194
10195 if (mData->flModifications & IsModified_ParallelPorts)
10196 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10197 if ( mParallelPorts[slot]
10198 && mParallelPorts[slot]->isModified())
10199 {
10200 mParallelPorts[slot]->rollback();
10201 parallelPorts[slot] = mParallelPorts[slot];
10202 }
10203
10204 if (aNotify)
10205 {
10206 /* inform the direct session about changes */
10207
10208 ComObjPtr<Machine> that = this;
10209 uint32_t flModifications = mData->flModifications;
10210 alock.leave();
10211
10212 if (flModifications & IsModified_SharedFolders)
10213 that->onSharedFolderChange();
10214
10215 if (flModifications & IsModified_VRDEServer)
10216 that->onVRDEServerChange(/* aRestart */ TRUE);
10217 if (flModifications & IsModified_USB)
10218 that->onUSBControllerChange();
10219
10220 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
10221 if (networkAdapters[slot])
10222 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
10223 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
10224 if (serialPorts[slot])
10225 that->onSerialPortChange(serialPorts[slot]);
10226 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
10227 if (parallelPorts[slot])
10228 that->onParallelPortChange(parallelPorts[slot]);
10229
10230 if (flModifications & IsModified_Storage)
10231 that->onStorageControllerChange();
10232
10233#if 0
10234 if (flModifications & IsModified_BandwidthControl)
10235 that->onBandwidthControlChange();
10236#endif
10237 }
10238}
10239
10240/**
10241 * Commits all the changes to machine settings.
10242 *
10243 * Note that this operation is supposed to never fail.
10244 *
10245 * @note Locks this object and children for writing.
10246 */
10247void Machine::commit()
10248{
10249 AutoCaller autoCaller(this);
10250 AssertComRCReturnVoid(autoCaller.rc());
10251
10252 AutoCaller peerCaller(mPeer);
10253 AssertComRCReturnVoid(peerCaller.rc());
10254
10255 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
10256
10257 /*
10258 * use safe commit to ensure Snapshot machines (that share mUserData)
10259 * will still refer to a valid memory location
10260 */
10261 mUserData.commitCopy();
10262
10263 mHWData.commit();
10264
10265 if (mMediaData.isBackedUp())
10266 commitMedia();
10267
10268 mBIOSSettings->commit();
10269 mVRDEServer->commit();
10270 mAudioAdapter->commit();
10271 mUSBController->commit();
10272 mBandwidthControl->commit();
10273
10274 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10275 mNetworkAdapters[slot]->commit();
10276 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10277 mSerialPorts[slot]->commit();
10278 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10279 mParallelPorts[slot]->commit();
10280
10281 bool commitStorageControllers = false;
10282
10283 if (mStorageControllers.isBackedUp())
10284 {
10285 mStorageControllers.commit();
10286
10287 if (mPeer)
10288 {
10289 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
10290
10291 /* Commit all changes to new controllers (this will reshare data with
10292 * peers for those who have peers) */
10293 StorageControllerList *newList = new StorageControllerList();
10294 StorageControllerList::const_iterator it = mStorageControllers->begin();
10295 while (it != mStorageControllers->end())
10296 {
10297 (*it)->commit();
10298
10299 /* look if this controller has a peer device */
10300 ComObjPtr<StorageController> peer = (*it)->getPeer();
10301 if (!peer)
10302 {
10303 /* no peer means the device is a newly created one;
10304 * create a peer owning data this device share it with */
10305 peer.createObject();
10306 peer->init(mPeer, *it, true /* aReshare */);
10307 }
10308 else
10309 {
10310 /* remove peer from the old list */
10311 mPeer->mStorageControllers->remove(peer);
10312 }
10313 /* and add it to the new list */
10314 newList->push_back(peer);
10315
10316 ++it;
10317 }
10318
10319 /* uninit old peer's controllers that are left */
10320 it = mPeer->mStorageControllers->begin();
10321 while (it != mPeer->mStorageControllers->end())
10322 {
10323 (*it)->uninit();
10324 ++it;
10325 }
10326
10327 /* attach new list of controllers to our peer */
10328 mPeer->mStorageControllers.attach(newList);
10329 }
10330 else
10331 {
10332 /* we have no peer (our parent is the newly created machine);
10333 * just commit changes to devices */
10334 commitStorageControllers = true;
10335 }
10336 }
10337 else
10338 {
10339 /* the list of controllers itself is not changed,
10340 * just commit changes to controllers themselves */
10341 commitStorageControllers = true;
10342 }
10343
10344 if (commitStorageControllers)
10345 {
10346 StorageControllerList::const_iterator it = mStorageControllers->begin();
10347 while (it != mStorageControllers->end())
10348 {
10349 (*it)->commit();
10350 ++it;
10351 }
10352 }
10353
10354 if (isSessionMachine())
10355 {
10356 /* attach new data to the primary machine and reshare it */
10357 mPeer->mUserData.attach(mUserData);
10358 mPeer->mHWData.attach(mHWData);
10359 /* mMediaData is reshared by fixupMedia */
10360 // mPeer->mMediaData.attach(mMediaData);
10361 Assert(mPeer->mMediaData.data() == mMediaData.data());
10362 }
10363}
10364
10365/**
10366 * Copies all the hardware data from the given machine.
10367 *
10368 * Currently, only called when the VM is being restored from a snapshot. In
10369 * particular, this implies that the VM is not running during this method's
10370 * call.
10371 *
10372 * @note This method must be called from under this object's lock.
10373 *
10374 * @note This method doesn't call #commit(), so all data remains backed up and
10375 * unsaved.
10376 */
10377void Machine::copyFrom(Machine *aThat)
10378{
10379 AssertReturnVoid(!isSnapshotMachine());
10380 AssertReturnVoid(aThat->isSnapshotMachine());
10381
10382 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
10383
10384 mHWData.assignCopy(aThat->mHWData);
10385
10386 // create copies of all shared folders (mHWData after attaching a copy
10387 // contains just references to original objects)
10388 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10389 it != mHWData->mSharedFolders.end();
10390 ++it)
10391 {
10392 ComObjPtr<SharedFolder> folder;
10393 folder.createObject();
10394 HRESULT rc = folder->initCopy(getMachine(), *it);
10395 AssertComRC(rc);
10396 *it = folder;
10397 }
10398
10399 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
10400 mVRDEServer->copyFrom(aThat->mVRDEServer);
10401 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
10402 mUSBController->copyFrom(aThat->mUSBController);
10403 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10404
10405 /* create private copies of all controllers */
10406 mStorageControllers.backup();
10407 mStorageControllers->clear();
10408 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10409 it != aThat->mStorageControllers->end();
10410 ++it)
10411 {
10412 ComObjPtr<StorageController> ctrl;
10413 ctrl.createObject();
10414 ctrl->initCopy(this, *it);
10415 mStorageControllers->push_back(ctrl);
10416 }
10417
10418 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10419 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10420 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10421 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10422 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10423 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10424}
10425
10426/**
10427 * Returns whether the given storage controller is hotplug capable.
10428 *
10429 * @returns true if the controller supports hotplugging
10430 * false otherwise.
10431 * @param enmCtrlType The controller type to check for.
10432 */
10433bool Machine::isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
10434{
10435 switch (enmCtrlType)
10436 {
10437 case StorageControllerType_IntelAhci:
10438 return true;
10439 case StorageControllerType_LsiLogic:
10440 case StorageControllerType_LsiLogicSas:
10441 case StorageControllerType_BusLogic:
10442 case StorageControllerType_PIIX3:
10443 case StorageControllerType_PIIX4:
10444 case StorageControllerType_ICH6:
10445 case StorageControllerType_I82078:
10446 default:
10447 return false;
10448 }
10449}
10450
10451#ifdef VBOX_WITH_RESOURCE_USAGE_API
10452
10453void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10454{
10455 AssertReturnVoid(isWriteLockOnCurrentThread());
10456 AssertPtrReturnVoid(aCollector);
10457
10458 pm::CollectorHAL *hal = aCollector->getHAL();
10459 /* Create sub metrics */
10460 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10461 "Percentage of processor time spent in user mode by the VM process.");
10462 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10463 "Percentage of processor time spent in kernel mode by the VM process.");
10464 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10465 "Size of resident portion of VM process in memory.");
10466 /* Create and register base metrics */
10467 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10468 cpuLoadUser, cpuLoadKernel);
10469 aCollector->registerBaseMetric(cpuLoad);
10470 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10471 ramUsageUsed);
10472 aCollector->registerBaseMetric(ramUsage);
10473
10474 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10475 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10476 new pm::AggregateAvg()));
10477 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10478 new pm::AggregateMin()));
10479 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10480 new pm::AggregateMax()));
10481 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10482 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10483 new pm::AggregateAvg()));
10484 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10485 new pm::AggregateMin()));
10486 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10487 new pm::AggregateMax()));
10488
10489 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10490 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10491 new pm::AggregateAvg()));
10492 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10493 new pm::AggregateMin()));
10494 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10495 new pm::AggregateMax()));
10496
10497
10498 /* Guest metrics collector */
10499 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10500 aCollector->registerGuest(mCollectorGuest);
10501 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10502 this, __PRETTY_FUNCTION__, mCollectorGuest));
10503
10504 /* Create sub metrics */
10505 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10506 "Percentage of processor time spent in user mode as seen by the guest.");
10507 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10508 "Percentage of processor time spent in kernel mode as seen by the guest.");
10509 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10510 "Percentage of processor time spent idling as seen by the guest.");
10511
10512 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10513 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10514 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10515 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10516 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10517 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10518
10519 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10520
10521 /* Create and register base metrics */
10522 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10523 guestLoadUser, guestLoadKernel, guestLoadIdle);
10524 aCollector->registerBaseMetric(guestCpuLoad);
10525
10526 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10527 guestMemTotal, guestMemFree,
10528 guestMemBalloon, guestMemShared,
10529 guestMemCache, guestPagedTotal);
10530 aCollector->registerBaseMetric(guestCpuMem);
10531
10532 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10533 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10534 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10535 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
10536
10537 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
10538 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
10539 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
10540 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
10541
10542 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
10543 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
10544 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
10545 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
10546
10547 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
10548 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
10549 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
10550 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
10551
10552 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
10553 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
10554 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
10555 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
10556
10557 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
10558 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
10559 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
10560 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
10561
10562 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
10563 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
10564 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
10565 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
10566
10567 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
10568 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
10569 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
10570 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
10571
10572 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
10573 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
10574 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
10575 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
10576}
10577
10578void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
10579{
10580 AssertReturnVoid(isWriteLockOnCurrentThread());
10581
10582 if (aCollector)
10583 {
10584 aCollector->unregisterMetricsFor(aMachine);
10585 aCollector->unregisterBaseMetricsFor(aMachine);
10586 }
10587}
10588
10589#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10590
10591
10592////////////////////////////////////////////////////////////////////////////////
10593
10594DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
10595
10596HRESULT SessionMachine::FinalConstruct()
10597{
10598 LogFlowThisFunc(("\n"));
10599
10600#if defined(RT_OS_WINDOWS)
10601 mIPCSem = NULL;
10602#elif defined(RT_OS_OS2)
10603 mIPCSem = NULLHANDLE;
10604#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10605 mIPCSem = -1;
10606#else
10607# error "Port me!"
10608#endif
10609
10610 return BaseFinalConstruct();
10611}
10612
10613void SessionMachine::FinalRelease()
10614{
10615 LogFlowThisFunc(("\n"));
10616
10617 uninit(Uninit::Unexpected);
10618
10619 BaseFinalRelease();
10620}
10621
10622/**
10623 * @note Must be called only by Machine::openSession() from its own write lock.
10624 */
10625HRESULT SessionMachine::init(Machine *aMachine)
10626{
10627 LogFlowThisFuncEnter();
10628 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10629
10630 AssertReturn(aMachine, E_INVALIDARG);
10631
10632 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10633
10634 /* Enclose the state transition NotReady->InInit->Ready */
10635 AutoInitSpan autoInitSpan(this);
10636 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10637
10638 /* create the interprocess semaphore */
10639#if defined(RT_OS_WINDOWS)
10640 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10641 for (size_t i = 0; i < mIPCSemName.length(); i++)
10642 if (mIPCSemName.raw()[i] == '\\')
10643 mIPCSemName.raw()[i] = '/';
10644 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10645 ComAssertMsgRet(mIPCSem,
10646 ("Cannot create IPC mutex '%ls', err=%d",
10647 mIPCSemName.raw(), ::GetLastError()),
10648 E_FAIL);
10649#elif defined(RT_OS_OS2)
10650 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10651 aMachine->mData->mUuid.raw());
10652 mIPCSemName = ipcSem;
10653 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10654 ComAssertMsgRet(arc == NO_ERROR,
10655 ("Cannot create IPC mutex '%s', arc=%ld",
10656 ipcSem.c_str(), arc),
10657 E_FAIL);
10658#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10659# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10660# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10661 /** @todo Check that this still works correctly. */
10662 AssertCompileSize(key_t, 8);
10663# else
10664 AssertCompileSize(key_t, 4);
10665# endif
10666 key_t key;
10667 mIPCSem = -1;
10668 mIPCKey = "0";
10669 for (uint32_t i = 0; i < 1 << 24; i++)
10670 {
10671 key = ((uint32_t)'V' << 24) | i;
10672 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10673 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10674 {
10675 mIPCSem = sem;
10676 if (sem >= 0)
10677 mIPCKey = BstrFmt("%u", key);
10678 break;
10679 }
10680 }
10681# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10682 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10683 char *pszSemName = NULL;
10684 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10685 key_t key = ::ftok(pszSemName, 'V');
10686 RTStrFree(pszSemName);
10687
10688 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10689# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10690
10691 int errnoSave = errno;
10692 if (mIPCSem < 0 && errnoSave == ENOSYS)
10693 {
10694 setError(E_FAIL,
10695 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10696 "support for SysV IPC. Check the host kernel configuration for "
10697 "CONFIG_SYSVIPC=y"));
10698 return E_FAIL;
10699 }
10700 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10701 * the IPC semaphores */
10702 if (mIPCSem < 0 && errnoSave == ENOSPC)
10703 {
10704#ifdef RT_OS_LINUX
10705 setError(E_FAIL,
10706 tr("Cannot create IPC semaphore because the system limit for the "
10707 "maximum number of semaphore sets (SEMMNI), or the system wide "
10708 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10709 "current set of SysV IPC semaphores can be determined from "
10710 "the file /proc/sysvipc/sem"));
10711#else
10712 setError(E_FAIL,
10713 tr("Cannot create IPC semaphore because the system-imposed limit "
10714 "on the maximum number of allowed semaphores or semaphore "
10715 "identifiers system-wide would be exceeded"));
10716#endif
10717 return E_FAIL;
10718 }
10719 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10720 E_FAIL);
10721 /* set the initial value to 1 */
10722 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10723 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10724 E_FAIL);
10725#else
10726# error "Port me!"
10727#endif
10728
10729 /* memorize the peer Machine */
10730 unconst(mPeer) = aMachine;
10731 /* share the parent pointer */
10732 unconst(mParent) = aMachine->mParent;
10733
10734 /* take the pointers to data to share */
10735 mData.share(aMachine->mData);
10736 mSSData.share(aMachine->mSSData);
10737
10738 mUserData.share(aMachine->mUserData);
10739 mHWData.share(aMachine->mHWData);
10740 mMediaData.share(aMachine->mMediaData);
10741
10742 mStorageControllers.allocate();
10743 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10744 it != aMachine->mStorageControllers->end();
10745 ++it)
10746 {
10747 ComObjPtr<StorageController> ctl;
10748 ctl.createObject();
10749 ctl->init(this, *it);
10750 mStorageControllers->push_back(ctl);
10751 }
10752
10753 unconst(mBIOSSettings).createObject();
10754 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10755 /* create another VRDEServer object that will be mutable */
10756 unconst(mVRDEServer).createObject();
10757 mVRDEServer->init(this, aMachine->mVRDEServer);
10758 /* create another audio adapter object that will be mutable */
10759 unconst(mAudioAdapter).createObject();
10760 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10761 /* create a list of serial ports that will be mutable */
10762 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10763 {
10764 unconst(mSerialPorts[slot]).createObject();
10765 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10766 }
10767 /* create a list of parallel ports that will be mutable */
10768 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10769 {
10770 unconst(mParallelPorts[slot]).createObject();
10771 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10772 }
10773 /* create another USB controller object that will be mutable */
10774 unconst(mUSBController).createObject();
10775 mUSBController->init(this, aMachine->mUSBController);
10776
10777 /* create a list of network adapters that will be mutable */
10778 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10779 {
10780 unconst(mNetworkAdapters[slot]).createObject();
10781 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10782 }
10783
10784 /* create another bandwidth control object that will be mutable */
10785 unconst(mBandwidthControl).createObject();
10786 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10787
10788 /* default is to delete saved state on Saved -> PoweredOff transition */
10789 mRemoveSavedState = true;
10790
10791 /* Confirm a successful initialization when it's the case */
10792 autoInitSpan.setSucceeded();
10793
10794 LogFlowThisFuncLeave();
10795 return S_OK;
10796}
10797
10798/**
10799 * Uninitializes this session object. If the reason is other than
10800 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10801 *
10802 * @param aReason uninitialization reason
10803 *
10804 * @note Locks mParent + this object for writing.
10805 */
10806void SessionMachine::uninit(Uninit::Reason aReason)
10807{
10808 LogFlowThisFuncEnter();
10809 LogFlowThisFunc(("reason=%d\n", aReason));
10810
10811 /*
10812 * Strongly reference ourselves to prevent this object deletion after
10813 * mData->mSession.mMachine.setNull() below (which can release the last
10814 * reference and call the destructor). Important: this must be done before
10815 * accessing any members (and before AutoUninitSpan that does it as well).
10816 * This self reference will be released as the very last step on return.
10817 */
10818 ComObjPtr<SessionMachine> selfRef = this;
10819
10820 /* Enclose the state transition Ready->InUninit->NotReady */
10821 AutoUninitSpan autoUninitSpan(this);
10822 if (autoUninitSpan.uninitDone())
10823 {
10824 LogFlowThisFunc(("Already uninitialized\n"));
10825 LogFlowThisFuncLeave();
10826 return;
10827 }
10828
10829 if (autoUninitSpan.initFailed())
10830 {
10831 /* We've been called by init() because it's failed. It's not really
10832 * necessary (nor it's safe) to perform the regular uninit sequence
10833 * below, the following is enough.
10834 */
10835 LogFlowThisFunc(("Initialization failed.\n"));
10836#if defined(RT_OS_WINDOWS)
10837 if (mIPCSem)
10838 ::CloseHandle(mIPCSem);
10839 mIPCSem = NULL;
10840#elif defined(RT_OS_OS2)
10841 if (mIPCSem != NULLHANDLE)
10842 ::DosCloseMutexSem(mIPCSem);
10843 mIPCSem = NULLHANDLE;
10844#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10845 if (mIPCSem >= 0)
10846 ::semctl(mIPCSem, 0, IPC_RMID);
10847 mIPCSem = -1;
10848# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10849 mIPCKey = "0";
10850# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10851#else
10852# error "Port me!"
10853#endif
10854 uninitDataAndChildObjects();
10855 mData.free();
10856 unconst(mParent) = NULL;
10857 unconst(mPeer) = NULL;
10858 LogFlowThisFuncLeave();
10859 return;
10860 }
10861
10862 MachineState_T lastState;
10863 {
10864 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10865 lastState = mData->mMachineState;
10866 }
10867 NOREF(lastState);
10868
10869#ifdef VBOX_WITH_USB
10870 // release all captured USB devices, but do this before requesting the locks below
10871 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10872 {
10873 /* Console::captureUSBDevices() is called in the VM process only after
10874 * setting the machine state to Starting or Restoring.
10875 * Console::detachAllUSBDevices() will be called upon successful
10876 * termination. So, we need to release USB devices only if there was
10877 * an abnormal termination of a running VM.
10878 *
10879 * This is identical to SessionMachine::DetachAllUSBDevices except
10880 * for the aAbnormal argument. */
10881 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10882 AssertComRC(rc);
10883 NOREF(rc);
10884
10885 USBProxyService *service = mParent->host()->usbProxyService();
10886 if (service)
10887 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10888 }
10889#endif /* VBOX_WITH_USB */
10890
10891 // we need to lock this object in uninit() because the lock is shared
10892 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10893 // and others need mParent lock, and USB needs host lock.
10894 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10895
10896 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10897 this, __PRETTY_FUNCTION__, mCollectorGuest));
10898 if (mCollectorGuest)
10899 {
10900 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
10901 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
10902 mCollectorGuest = NULL;
10903 }
10904#if 0
10905 // Trigger async cleanup tasks, avoid doing things here which are not
10906 // vital to be done immediately and maybe need more locks. This calls
10907 // Machine::unregisterMetrics().
10908 mParent->onMachineUninit(mPeer);
10909#else
10910 /*
10911 * It is safe to call Machine::unregisterMetrics() here because
10912 * PerformanceCollector::samplerCallback no longer accesses guest methods
10913 * holding the lock.
10914 */
10915 unregisterMetrics(mParent->performanceCollector(), mPeer);
10916#endif
10917
10918 if (aReason == Uninit::Abnormal)
10919 {
10920 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10921 Global::IsOnlineOrTransient(lastState)));
10922
10923 /* reset the state to Aborted */
10924 if (mData->mMachineState != MachineState_Aborted)
10925 setMachineState(MachineState_Aborted);
10926 }
10927
10928 // any machine settings modified?
10929 if (mData->flModifications)
10930 {
10931 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10932 rollback(false /* aNotify */);
10933 }
10934
10935 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
10936 || !mConsoleTaskData.mSnapshot);
10937 if (!mConsoleTaskData.strStateFilePath.isEmpty())
10938 {
10939 LogWarningThisFunc(("canceling failed save state request!\n"));
10940 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10941 }
10942 else if (!mConsoleTaskData.mSnapshot.isNull())
10943 {
10944 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10945
10946 /* delete all differencing hard disks created (this will also attach
10947 * their parents back by rolling back mMediaData) */
10948 rollbackMedia();
10949
10950 // delete the saved state file (it might have been already created)
10951 // AFTER killing the snapshot so that releaseSavedStateFile() won't
10952 // think it's still in use
10953 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
10954 mConsoleTaskData.mSnapshot->uninit();
10955 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
10956 }
10957
10958 if (!mData->mSession.mType.isEmpty())
10959 {
10960 /* mType is not null when this machine's process has been started by
10961 * Machine::LaunchVMProcess(), therefore it is our child. We
10962 * need to queue the PID to reap the process (and avoid zombies on
10963 * Linux). */
10964 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10965 mParent->addProcessToReap(mData->mSession.mPid);
10966 }
10967
10968 mData->mSession.mPid = NIL_RTPROCESS;
10969
10970 if (aReason == Uninit::Unexpected)
10971 {
10972 /* Uninitialization didn't come from #checkForDeath(), so tell the
10973 * client watcher thread to update the set of machines that have open
10974 * sessions. */
10975 mParent->updateClientWatcher();
10976 }
10977
10978 /* uninitialize all remote controls */
10979 if (mData->mSession.mRemoteControls.size())
10980 {
10981 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10982 mData->mSession.mRemoteControls.size()));
10983
10984 Data::Session::RemoteControlList::iterator it =
10985 mData->mSession.mRemoteControls.begin();
10986 while (it != mData->mSession.mRemoteControls.end())
10987 {
10988 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10989 HRESULT rc = (*it)->Uninitialize();
10990 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10991 if (FAILED(rc))
10992 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10993 ++it;
10994 }
10995 mData->mSession.mRemoteControls.clear();
10996 }
10997
10998 /*
10999 * An expected uninitialization can come only from #checkForDeath().
11000 * Otherwise it means that something's gone really wrong (for example,
11001 * the Session implementation has released the VirtualBox reference
11002 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
11003 * etc). However, it's also possible, that the client releases the IPC
11004 * semaphore correctly (i.e. before it releases the VirtualBox reference),
11005 * but the VirtualBox release event comes first to the server process.
11006 * This case is practically possible, so we should not assert on an
11007 * unexpected uninit, just log a warning.
11008 */
11009
11010 if ((aReason == Uninit::Unexpected))
11011 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
11012
11013 if (aReason != Uninit::Normal)
11014 {
11015 mData->mSession.mDirectControl.setNull();
11016 }
11017 else
11018 {
11019 /* this must be null here (see #OnSessionEnd()) */
11020 Assert(mData->mSession.mDirectControl.isNull());
11021 Assert(mData->mSession.mState == SessionState_Unlocking);
11022 Assert(!mData->mSession.mProgress.isNull());
11023 }
11024 if (mData->mSession.mProgress)
11025 {
11026 if (aReason == Uninit::Normal)
11027 mData->mSession.mProgress->notifyComplete(S_OK);
11028 else
11029 mData->mSession.mProgress->notifyComplete(E_FAIL,
11030 COM_IIDOF(ISession),
11031 getComponentName(),
11032 tr("The VM session was aborted"));
11033 mData->mSession.mProgress.setNull();
11034 }
11035
11036 /* remove the association between the peer machine and this session machine */
11037 Assert( (SessionMachine*)mData->mSession.mMachine == this
11038 || aReason == Uninit::Unexpected);
11039
11040 /* reset the rest of session data */
11041 mData->mSession.mMachine.setNull();
11042 mData->mSession.mState = SessionState_Unlocked;
11043 mData->mSession.mType.setNull();
11044
11045 /* close the interprocess semaphore before leaving the exclusive lock */
11046#if defined(RT_OS_WINDOWS)
11047 if (mIPCSem)
11048 ::CloseHandle(mIPCSem);
11049 mIPCSem = NULL;
11050#elif defined(RT_OS_OS2)
11051 if (mIPCSem != NULLHANDLE)
11052 ::DosCloseMutexSem(mIPCSem);
11053 mIPCSem = NULLHANDLE;
11054#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11055 if (mIPCSem >= 0)
11056 ::semctl(mIPCSem, 0, IPC_RMID);
11057 mIPCSem = -1;
11058# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11059 mIPCKey = "0";
11060# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
11061#else
11062# error "Port me!"
11063#endif
11064
11065 /* fire an event */
11066 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
11067
11068 uninitDataAndChildObjects();
11069
11070 /* free the essential data structure last */
11071 mData.free();
11072
11073#if 1 /** @todo Please review this change! (bird) */
11074 /* drop the exclusive lock before setting the below two to NULL */
11075 multilock.release();
11076#else
11077 /* leave the exclusive lock before setting the below two to NULL */
11078 multilock.leave();
11079#endif
11080
11081 unconst(mParent) = NULL;
11082 unconst(mPeer) = NULL;
11083
11084 LogFlowThisFuncLeave();
11085}
11086
11087// util::Lockable interface
11088////////////////////////////////////////////////////////////////////////////////
11089
11090/**
11091 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
11092 * with the primary Machine instance (mPeer).
11093 */
11094RWLockHandle *SessionMachine::lockHandle() const
11095{
11096 AssertReturn(mPeer != NULL, NULL);
11097 return mPeer->lockHandle();
11098}
11099
11100// IInternalMachineControl methods
11101////////////////////////////////////////////////////////////////////////////////
11102
11103/**
11104 * @note Locks this object for writing.
11105 */
11106STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
11107{
11108 AutoCaller autoCaller(this);
11109 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11110
11111 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11112
11113 mRemoveSavedState = aRemove;
11114
11115 return S_OK;
11116}
11117
11118/**
11119 * @note Locks the same as #setMachineState() does.
11120 */
11121STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
11122{
11123 return setMachineState(aMachineState);
11124}
11125
11126/**
11127 * @note Locks this object for reading.
11128 */
11129STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
11130{
11131 AutoCaller autoCaller(this);
11132 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11133
11134 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11135
11136#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
11137 mIPCSemName.cloneTo(aId);
11138 return S_OK;
11139#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11140# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11141 mIPCKey.cloneTo(aId);
11142# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11143 mData->m_strConfigFileFull.cloneTo(aId);
11144# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11145 return S_OK;
11146#else
11147# error "Port me!"
11148#endif
11149}
11150
11151/**
11152 * @note Locks this object for writing.
11153 */
11154STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
11155{
11156 LogFlowThisFunc(("aProgress=%p\n", aProgress));
11157 AutoCaller autoCaller(this);
11158 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11159
11160 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11161
11162 if (mData->mSession.mState != SessionState_Locked)
11163 return VBOX_E_INVALID_OBJECT_STATE;
11164
11165 if (!mData->mSession.mProgress.isNull())
11166 mData->mSession.mProgress->setOtherProgressObject(aProgress);
11167
11168 LogFlowThisFunc(("returns S_OK.\n"));
11169 return S_OK;
11170}
11171
11172/**
11173 * @note Locks this object for writing.
11174 */
11175STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
11176{
11177 AutoCaller autoCaller(this);
11178 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11179
11180 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11181
11182 if (mData->mSession.mState != SessionState_Locked)
11183 return VBOX_E_INVALID_OBJECT_STATE;
11184
11185 /* Finalize the LaunchVMProcess progress object. */
11186 if (mData->mSession.mProgress)
11187 {
11188 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
11189 mData->mSession.mProgress.setNull();
11190 }
11191
11192 if (SUCCEEDED((HRESULT)iResult))
11193 {
11194#ifdef VBOX_WITH_RESOURCE_USAGE_API
11195 /* The VM has been powered up successfully, so it makes sense
11196 * now to offer the performance metrics for a running machine
11197 * object. Doing it earlier wouldn't be safe. */
11198 registerMetrics(mParent->performanceCollector(), mPeer,
11199 mData->mSession.mPid);
11200#endif /* VBOX_WITH_RESOURCE_USAGE_API */
11201 }
11202
11203 return S_OK;
11204}
11205
11206/**
11207 * @note Locks this object for writing.
11208 */
11209STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
11210{
11211 LogFlowThisFuncEnter();
11212
11213 CheckComArgOutPointerValid(aProgress);
11214
11215 AutoCaller autoCaller(this);
11216 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11217
11218 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11219
11220 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
11221 E_FAIL);
11222
11223 /* create a progress object to track operation completion */
11224 ComObjPtr<Progress> pProgress;
11225 pProgress.createObject();
11226 pProgress->init(getVirtualBox(),
11227 static_cast<IMachine *>(this) /* aInitiator */,
11228 Bstr(tr("Stopping the virtual machine")).raw(),
11229 FALSE /* aCancelable */);
11230
11231 /* fill in the console task data */
11232 mConsoleTaskData.mLastState = mData->mMachineState;
11233 mConsoleTaskData.mProgress = pProgress;
11234
11235 /* set the state to Stopping (this is expected by Console::PowerDown()) */
11236 setMachineState(MachineState_Stopping);
11237
11238 pProgress.queryInterfaceTo(aProgress);
11239
11240 return S_OK;
11241}
11242
11243/**
11244 * @note Locks this object for writing.
11245 */
11246STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
11247{
11248 LogFlowThisFuncEnter();
11249
11250 AutoCaller autoCaller(this);
11251 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11252
11253 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11254
11255 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
11256 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
11257 && mConsoleTaskData.mLastState != MachineState_Null,
11258 E_FAIL);
11259
11260 /*
11261 * On failure, set the state to the state we had when BeginPoweringDown()
11262 * was called (this is expected by Console::PowerDown() and the associated
11263 * task). On success the VM process already changed the state to
11264 * MachineState_PoweredOff, so no need to do anything.
11265 */
11266 if (FAILED(iResult))
11267 setMachineState(mConsoleTaskData.mLastState);
11268
11269 /* notify the progress object about operation completion */
11270 Assert(mConsoleTaskData.mProgress);
11271 if (SUCCEEDED(iResult))
11272 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11273 else
11274 {
11275 Utf8Str strErrMsg(aErrMsg);
11276 if (strErrMsg.length())
11277 mConsoleTaskData.mProgress->notifyComplete(iResult,
11278 COM_IIDOF(ISession),
11279 getComponentName(),
11280 strErrMsg.c_str());
11281 else
11282 mConsoleTaskData.mProgress->notifyComplete(iResult);
11283 }
11284
11285 /* clear out the temporary saved state data */
11286 mConsoleTaskData.mLastState = MachineState_Null;
11287 mConsoleTaskData.mProgress.setNull();
11288
11289 LogFlowThisFuncLeave();
11290 return S_OK;
11291}
11292
11293
11294/**
11295 * Goes through the USB filters of the given machine to see if the given
11296 * device matches any filter or not.
11297 *
11298 * @note Locks the same as USBController::hasMatchingFilter() does.
11299 */
11300STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
11301 BOOL *aMatched,
11302 ULONG *aMaskedIfs)
11303{
11304 LogFlowThisFunc(("\n"));
11305
11306 CheckComArgNotNull(aUSBDevice);
11307 CheckComArgOutPointerValid(aMatched);
11308
11309 AutoCaller autoCaller(this);
11310 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11311
11312#ifdef VBOX_WITH_USB
11313 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
11314#else
11315 NOREF(aUSBDevice);
11316 NOREF(aMaskedIfs);
11317 *aMatched = FALSE;
11318#endif
11319
11320 return S_OK;
11321}
11322
11323/**
11324 * @note Locks the same as Host::captureUSBDevice() does.
11325 */
11326STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
11327{
11328 LogFlowThisFunc(("\n"));
11329
11330 AutoCaller autoCaller(this);
11331 AssertComRCReturnRC(autoCaller.rc());
11332
11333#ifdef VBOX_WITH_USB
11334 /* if captureDeviceForVM() fails, it must have set extended error info */
11335 clearError();
11336 MultiResult rc = mParent->host()->checkUSBProxyService();
11337 if (FAILED(rc)) return rc;
11338
11339 USBProxyService *service = mParent->host()->usbProxyService();
11340 AssertReturn(service, E_FAIL);
11341 return service->captureDeviceForVM(this, Guid(aId).ref());
11342#else
11343 NOREF(aId);
11344 return E_NOTIMPL;
11345#endif
11346}
11347
11348/**
11349 * @note Locks the same as Host::detachUSBDevice() does.
11350 */
11351STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
11352{
11353 LogFlowThisFunc(("\n"));
11354
11355 AutoCaller autoCaller(this);
11356 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11357
11358#ifdef VBOX_WITH_USB
11359 USBProxyService *service = mParent->host()->usbProxyService();
11360 AssertReturn(service, E_FAIL);
11361 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
11362#else
11363 NOREF(aId);
11364 NOREF(aDone);
11365 return E_NOTIMPL;
11366#endif
11367}
11368
11369/**
11370 * Inserts all machine filters to the USB proxy service and then calls
11371 * Host::autoCaptureUSBDevices().
11372 *
11373 * Called by Console from the VM process upon VM startup.
11374 *
11375 * @note Locks what called methods lock.
11376 */
11377STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
11378{
11379 LogFlowThisFunc(("\n"));
11380
11381 AutoCaller autoCaller(this);
11382 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11383
11384#ifdef VBOX_WITH_USB
11385 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
11386 AssertComRC(rc);
11387 NOREF(rc);
11388
11389 USBProxyService *service = mParent->host()->usbProxyService();
11390 AssertReturn(service, E_FAIL);
11391 return service->autoCaptureDevicesForVM(this);
11392#else
11393 return S_OK;
11394#endif
11395}
11396
11397/**
11398 * Removes all machine filters from the USB proxy service and then calls
11399 * Host::detachAllUSBDevices().
11400 *
11401 * Called by Console from the VM process upon normal VM termination or by
11402 * SessionMachine::uninit() upon abnormal VM termination (from under the
11403 * Machine/SessionMachine lock).
11404 *
11405 * @note Locks what called methods lock.
11406 */
11407STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
11408{
11409 LogFlowThisFunc(("\n"));
11410
11411 AutoCaller autoCaller(this);
11412 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11413
11414#ifdef VBOX_WITH_USB
11415 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11416 AssertComRC(rc);
11417 NOREF(rc);
11418
11419 USBProxyService *service = mParent->host()->usbProxyService();
11420 AssertReturn(service, E_FAIL);
11421 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
11422#else
11423 NOREF(aDone);
11424 return S_OK;
11425#endif
11426}
11427
11428/**
11429 * @note Locks this object for writing.
11430 */
11431STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
11432 IProgress **aProgress)
11433{
11434 LogFlowThisFuncEnter();
11435
11436 AssertReturn(aSession, E_INVALIDARG);
11437 AssertReturn(aProgress, E_INVALIDARG);
11438
11439 AutoCaller autoCaller(this);
11440
11441 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11442 /*
11443 * We don't assert below because it might happen that a non-direct session
11444 * informs us it is closed right after we've been uninitialized -- it's ok.
11445 */
11446 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11447
11448 /* get IInternalSessionControl interface */
11449 ComPtr<IInternalSessionControl> control(aSession);
11450
11451 ComAssertRet(!control.isNull(), E_INVALIDARG);
11452
11453 /* Creating a Progress object requires the VirtualBox lock, and
11454 * thus locking it here is required by the lock order rules. */
11455 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
11456
11457 if (control == mData->mSession.mDirectControl)
11458 {
11459 ComAssertRet(aProgress, E_POINTER);
11460
11461 /* The direct session is being normally closed by the client process
11462 * ----------------------------------------------------------------- */
11463
11464 /* go to the closing state (essential for all open*Session() calls and
11465 * for #checkForDeath()) */
11466 Assert(mData->mSession.mState == SessionState_Locked);
11467 mData->mSession.mState = SessionState_Unlocking;
11468
11469 /* set direct control to NULL to release the remote instance */
11470 mData->mSession.mDirectControl.setNull();
11471 LogFlowThisFunc(("Direct control is set to NULL\n"));
11472
11473 if (mData->mSession.mProgress)
11474 {
11475 /* finalize the progress, someone might wait if a frontend
11476 * closes the session before powering on the VM. */
11477 mData->mSession.mProgress->notifyComplete(E_FAIL,
11478 COM_IIDOF(ISession),
11479 getComponentName(),
11480 tr("The VM session was closed before any attempt to power it on"));
11481 mData->mSession.mProgress.setNull();
11482 }
11483
11484 /* Create the progress object the client will use to wait until
11485 * #checkForDeath() is called to uninitialize this session object after
11486 * it releases the IPC semaphore.
11487 * Note! Because we're "reusing" mProgress here, this must be a proxy
11488 * object just like for LaunchVMProcess. */
11489 Assert(mData->mSession.mProgress.isNull());
11490 ComObjPtr<ProgressProxy> progress;
11491 progress.createObject();
11492 ComPtr<IUnknown> pPeer(mPeer);
11493 progress->init(mParent, pPeer,
11494 Bstr(tr("Closing session")).raw(),
11495 FALSE /* aCancelable */);
11496 progress.queryInterfaceTo(aProgress);
11497 mData->mSession.mProgress = progress;
11498 }
11499 else
11500 {
11501 /* the remote session is being normally closed */
11502 Data::Session::RemoteControlList::iterator it =
11503 mData->mSession.mRemoteControls.begin();
11504 while (it != mData->mSession.mRemoteControls.end())
11505 {
11506 if (control == *it)
11507 break;
11508 ++it;
11509 }
11510 BOOL found = it != mData->mSession.mRemoteControls.end();
11511 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11512 E_INVALIDARG);
11513 mData->mSession.mRemoteControls.remove(*it);
11514 }
11515
11516 LogFlowThisFuncLeave();
11517 return S_OK;
11518}
11519
11520/**
11521 * @note Locks this object for writing.
11522 */
11523STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11524{
11525 LogFlowThisFuncEnter();
11526
11527 CheckComArgOutPointerValid(aProgress);
11528 CheckComArgOutPointerValid(aStateFilePath);
11529
11530 AutoCaller autoCaller(this);
11531 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11532
11533 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11534
11535 AssertReturn( mData->mMachineState == MachineState_Paused
11536 && mConsoleTaskData.mLastState == MachineState_Null
11537 && mConsoleTaskData.strStateFilePath.isEmpty(),
11538 E_FAIL);
11539
11540 /* create a progress object to track operation completion */
11541 ComObjPtr<Progress> pProgress;
11542 pProgress.createObject();
11543 pProgress->init(getVirtualBox(),
11544 static_cast<IMachine *>(this) /* aInitiator */,
11545 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
11546 FALSE /* aCancelable */);
11547
11548 Utf8Str strStateFilePath;
11549 /* stateFilePath is null when the machine is not running */
11550 if (mData->mMachineState == MachineState_Paused)
11551 composeSavedStateFilename(strStateFilePath);
11552
11553 /* fill in the console task data */
11554 mConsoleTaskData.mLastState = mData->mMachineState;
11555 mConsoleTaskData.strStateFilePath = strStateFilePath;
11556 mConsoleTaskData.mProgress = pProgress;
11557
11558 /* set the state to Saving (this is expected by Console::SaveState()) */
11559 setMachineState(MachineState_Saving);
11560
11561 strStateFilePath.cloneTo(aStateFilePath);
11562 pProgress.queryInterfaceTo(aProgress);
11563
11564 return S_OK;
11565}
11566
11567/**
11568 * @note Locks mParent + this object for writing.
11569 */
11570STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
11571{
11572 LogFlowThisFunc(("\n"));
11573
11574 AutoCaller autoCaller(this);
11575 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11576
11577 /* endSavingState() need mParent lock */
11578 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11579
11580 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
11581 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
11582 && mConsoleTaskData.mLastState != MachineState_Null
11583 && !mConsoleTaskData.strStateFilePath.isEmpty(),
11584 E_FAIL);
11585
11586 /*
11587 * On failure, set the state to the state we had when BeginSavingState()
11588 * was called (this is expected by Console::SaveState() and the associated
11589 * task). On success the VM process already changed the state to
11590 * MachineState_Saved, so no need to do anything.
11591 */
11592 if (FAILED(iResult))
11593 setMachineState(mConsoleTaskData.mLastState);
11594
11595 return endSavingState(iResult, aErrMsg);
11596}
11597
11598/**
11599 * @note Locks this object for writing.
11600 */
11601STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
11602{
11603 LogFlowThisFunc(("\n"));
11604
11605 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
11606
11607 AutoCaller autoCaller(this);
11608 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11609
11610 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11611
11612 AssertReturn( mData->mMachineState == MachineState_PoweredOff
11613 || mData->mMachineState == MachineState_Teleported
11614 || mData->mMachineState == MachineState_Aborted
11615 , E_FAIL); /** @todo setError. */
11616
11617 Utf8Str stateFilePathFull = aSavedStateFile;
11618 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
11619 if (RT_FAILURE(vrc))
11620 return setError(VBOX_E_FILE_ERROR,
11621 tr("Invalid saved state file path '%ls' (%Rrc)"),
11622 aSavedStateFile,
11623 vrc);
11624
11625 mSSData->strStateFilePath = stateFilePathFull;
11626
11627 /* The below setMachineState() will detect the state transition and will
11628 * update the settings file */
11629
11630 return setMachineState(MachineState_Saved);
11631}
11632
11633STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
11634 ComSafeArrayOut(BSTR, aValues),
11635 ComSafeArrayOut(LONG64, aTimestamps),
11636 ComSafeArrayOut(BSTR, aFlags))
11637{
11638 LogFlowThisFunc(("\n"));
11639
11640#ifdef VBOX_WITH_GUEST_PROPS
11641 using namespace guestProp;
11642
11643 AutoCaller autoCaller(this);
11644 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11645
11646 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11647
11648 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
11649 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
11650 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
11651 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
11652
11653 size_t cEntries = mHWData->mGuestProperties.size();
11654 com::SafeArray<BSTR> names(cEntries);
11655 com::SafeArray<BSTR> values(cEntries);
11656 com::SafeArray<LONG64> timestamps(cEntries);
11657 com::SafeArray<BSTR> flags(cEntries);
11658 unsigned i = 0;
11659 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
11660 it != mHWData->mGuestProperties.end();
11661 ++it)
11662 {
11663 char szFlags[MAX_FLAGS_LEN + 1];
11664 it->strName.cloneTo(&names[i]);
11665 it->strValue.cloneTo(&values[i]);
11666 timestamps[i] = it->mTimestamp;
11667 /* If it is NULL, keep it NULL. */
11668 if (it->mFlags)
11669 {
11670 writeFlags(it->mFlags, szFlags);
11671 Bstr(szFlags).cloneTo(&flags[i]);
11672 }
11673 else
11674 flags[i] = NULL;
11675 ++i;
11676 }
11677 names.detachTo(ComSafeArrayOutArg(aNames));
11678 values.detachTo(ComSafeArrayOutArg(aValues));
11679 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11680 flags.detachTo(ComSafeArrayOutArg(aFlags));
11681 return S_OK;
11682#else
11683 ReturnComNotImplemented();
11684#endif
11685}
11686
11687STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11688 IN_BSTR aValue,
11689 LONG64 aTimestamp,
11690 IN_BSTR aFlags)
11691{
11692 LogFlowThisFunc(("\n"));
11693
11694#ifdef VBOX_WITH_GUEST_PROPS
11695 using namespace guestProp;
11696
11697 CheckComArgStrNotEmptyOrNull(aName);
11698 CheckComArgMaybeNull(aValue);
11699 CheckComArgMaybeNull(aFlags);
11700
11701 try
11702 {
11703 /*
11704 * Convert input up front.
11705 */
11706 Utf8Str utf8Name(aName);
11707 uint32_t fFlags = NILFLAG;
11708 if (aFlags)
11709 {
11710 Utf8Str utf8Flags(aFlags);
11711 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11712 AssertRCReturn(vrc, E_INVALIDARG);
11713 }
11714
11715 /*
11716 * Now grab the object lock, validate the state and do the update.
11717 */
11718 AutoCaller autoCaller(this);
11719 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11720
11721 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11722
11723 switch (mData->mMachineState)
11724 {
11725 case MachineState_Paused:
11726 case MachineState_Running:
11727 case MachineState_Teleporting:
11728 case MachineState_TeleportingPausedVM:
11729 case MachineState_LiveSnapshotting:
11730 case MachineState_DeletingSnapshotOnline:
11731 case MachineState_DeletingSnapshotPaused:
11732 case MachineState_Saving:
11733 break;
11734
11735 default:
11736#ifndef DEBUG_sunlover
11737 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11738 VBOX_E_INVALID_VM_STATE);
11739#else
11740 return VBOX_E_INVALID_VM_STATE;
11741#endif
11742 }
11743
11744 setModified(IsModified_MachineData);
11745 mHWData.backup();
11746
11747 /** @todo r=bird: The careful memory handling doesn't work out here because
11748 * the catch block won't undo any damage we've done. So, if push_back throws
11749 * bad_alloc then you've lost the value.
11750 *
11751 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11752 * since values that changes actually bubbles to the end of the list. Using
11753 * something that has an efficient lookup and can tolerate a bit of updates
11754 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11755 * combination of RTStrCache (for sharing names and getting uniqueness into
11756 * the bargain) and hash/tree is another. */
11757 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11758 iter != mHWData->mGuestProperties.end();
11759 ++iter)
11760 if (utf8Name == iter->strName)
11761 {
11762 mHWData->mGuestProperties.erase(iter);
11763 mData->mGuestPropertiesModified = TRUE;
11764 break;
11765 }
11766 if (aValue != NULL)
11767 {
11768 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11769 mHWData->mGuestProperties.push_back(property);
11770 mData->mGuestPropertiesModified = TRUE;
11771 }
11772
11773 /*
11774 * Send a callback notification if appropriate
11775 */
11776 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11777 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11778 RTSTR_MAX,
11779 utf8Name.c_str(),
11780 RTSTR_MAX, NULL)
11781 )
11782 {
11783 alock.leave();
11784
11785 mParent->onGuestPropertyChange(mData->mUuid,
11786 aName,
11787 aValue,
11788 aFlags);
11789 }
11790 }
11791 catch (...)
11792 {
11793 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11794 }
11795 return S_OK;
11796#else
11797 ReturnComNotImplemented();
11798#endif
11799}
11800
11801STDMETHODIMP SessionMachine::EjectMedium(IMediumAttachment *aAttachment,
11802 IMediumAttachment **aNewAttachment)
11803{
11804 CheckComArgNotNull(aAttachment);
11805 CheckComArgOutPointerValid(aNewAttachment);
11806
11807 AutoCaller autoCaller(this);
11808 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11809
11810 // request the host lock first, since might be calling Host methods for getting host drives;
11811 // next, protect the media tree all the while we're in here, as well as our member variables
11812 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
11813 this->lockHandle(),
11814 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
11815
11816 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(aAttachment);
11817
11818 Bstr ctrlName;
11819 LONG lPort;
11820 LONG lDevice;
11821 bool fTempEject;
11822 {
11823 AutoCaller autoAttachCaller(this);
11824 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
11825
11826 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
11827
11828 /* Need to query the details first, as the IMediumAttachment reference
11829 * might be to the original settings, which we are going to change. */
11830 ctrlName = pAttach->getControllerName();
11831 lPort = pAttach->getPort();
11832 lDevice = pAttach->getDevice();
11833 fTempEject = pAttach->getTempEject();
11834 }
11835
11836 if (!fTempEject)
11837 {
11838 /* Remember previously mounted medium. The medium before taking the
11839 * backup is not necessarily the same thing. */
11840 ComObjPtr<Medium> oldmedium;
11841 oldmedium = pAttach->getMedium();
11842
11843 setModified(IsModified_Storage);
11844 mMediaData.backup();
11845
11846 // The backup operation makes the pAttach reference point to the
11847 // old settings. Re-get the correct reference.
11848 pAttach = findAttachment(mMediaData->mAttachments,
11849 ctrlName.raw(),
11850 lPort,
11851 lDevice);
11852
11853 {
11854 AutoCaller autoAttachCaller(this);
11855 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
11856
11857 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
11858 if (!oldmedium.isNull())
11859 oldmedium->removeBackReference(mData->mUuid);
11860
11861 pAttach->updateMedium(NULL);
11862 pAttach->updateEjected();
11863 }
11864
11865 setModified(IsModified_Storage);
11866 }
11867 else
11868 {
11869 {
11870 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
11871 pAttach->updateEjected();
11872 }
11873 }
11874
11875 pAttach.queryInterfaceTo(aNewAttachment);
11876
11877 return S_OK;
11878}
11879
11880// public methods only for internal purposes
11881/////////////////////////////////////////////////////////////////////////////
11882
11883/**
11884 * Called from the client watcher thread to check for expected or unexpected
11885 * death of the client process that has a direct session to this machine.
11886 *
11887 * On Win32 and on OS/2, this method is called only when we've got the
11888 * mutex (i.e. the client has either died or terminated normally) so it always
11889 * returns @c true (the client is terminated, the session machine is
11890 * uninitialized).
11891 *
11892 * On other platforms, the method returns @c true if the client process has
11893 * terminated normally or abnormally and the session machine was uninitialized,
11894 * and @c false if the client process is still alive.
11895 *
11896 * @note Locks this object for writing.
11897 */
11898bool SessionMachine::checkForDeath()
11899{
11900 Uninit::Reason reason;
11901 bool terminated = false;
11902
11903 /* Enclose autoCaller with a block because calling uninit() from under it
11904 * will deadlock. */
11905 {
11906 AutoCaller autoCaller(this);
11907 if (!autoCaller.isOk())
11908 {
11909 /* return true if not ready, to cause the client watcher to exclude
11910 * the corresponding session from watching */
11911 LogFlowThisFunc(("Already uninitialized!\n"));
11912 return true;
11913 }
11914
11915 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11916
11917 /* Determine the reason of death: if the session state is Closing here,
11918 * everything is fine. Otherwise it means that the client did not call
11919 * OnSessionEnd() before it released the IPC semaphore. This may happen
11920 * either because the client process has abnormally terminated, or
11921 * because it simply forgot to call ISession::Close() before exiting. We
11922 * threat the latter also as an abnormal termination (see
11923 * Session::uninit() for details). */
11924 reason = mData->mSession.mState == SessionState_Unlocking ?
11925 Uninit::Normal :
11926 Uninit::Abnormal;
11927
11928#if defined(RT_OS_WINDOWS)
11929
11930 AssertMsg(mIPCSem, ("semaphore must be created"));
11931
11932 /* release the IPC mutex */
11933 ::ReleaseMutex(mIPCSem);
11934
11935 terminated = true;
11936
11937#elif defined(RT_OS_OS2)
11938
11939 AssertMsg(mIPCSem, ("semaphore must be created"));
11940
11941 /* release the IPC mutex */
11942 ::DosReleaseMutexSem(mIPCSem);
11943
11944 terminated = true;
11945
11946#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11947
11948 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11949
11950 int val = ::semctl(mIPCSem, 0, GETVAL);
11951 if (val > 0)
11952 {
11953 /* the semaphore is signaled, meaning the session is terminated */
11954 terminated = true;
11955 }
11956
11957#else
11958# error "Port me!"
11959#endif
11960
11961 } /* AutoCaller block */
11962
11963 if (terminated)
11964 uninit(reason);
11965
11966 return terminated;
11967}
11968
11969/**
11970 * @note Locks this object for reading.
11971 */
11972HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11973{
11974 LogFlowThisFunc(("\n"));
11975
11976 AutoCaller autoCaller(this);
11977 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11978
11979 ComPtr<IInternalSessionControl> directControl;
11980 {
11981 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11982 directControl = mData->mSession.mDirectControl;
11983 }
11984
11985 /* ignore notifications sent after #OnSessionEnd() is called */
11986 if (!directControl)
11987 return S_OK;
11988
11989 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11990}
11991
11992/**
11993 * @note Locks this object for reading.
11994 */
11995HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11996 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
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 * instead acting like callback we ask IVirtualBox deliver corresponding event
12014 */
12015
12016 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
12017 return S_OK;
12018}
12019
12020/**
12021 * @note Locks this object for reading.
12022 */
12023HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
12024{
12025 LogFlowThisFunc(("\n"));
12026
12027 AutoCaller autoCaller(this);
12028 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12029
12030 ComPtr<IInternalSessionControl> directControl;
12031 {
12032 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12033 directControl = mData->mSession.mDirectControl;
12034 }
12035
12036 /* ignore notifications sent after #OnSessionEnd() is called */
12037 if (!directControl)
12038 return S_OK;
12039
12040 return directControl->OnSerialPortChange(serialPort);
12041}
12042
12043/**
12044 * @note Locks this object for reading.
12045 */
12046HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
12047{
12048 LogFlowThisFunc(("\n"));
12049
12050 AutoCaller autoCaller(this);
12051 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12052
12053 ComPtr<IInternalSessionControl> directControl;
12054 {
12055 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12056 directControl = mData->mSession.mDirectControl;
12057 }
12058
12059 /* ignore notifications sent after #OnSessionEnd() is called */
12060 if (!directControl)
12061 return S_OK;
12062
12063 return directControl->OnParallelPortChange(parallelPort);
12064}
12065
12066/**
12067 * @note Locks this object for reading.
12068 */
12069HRESULT SessionMachine::onStorageControllerChange()
12070{
12071 LogFlowThisFunc(("\n"));
12072
12073 AutoCaller autoCaller(this);
12074 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12075
12076 ComPtr<IInternalSessionControl> directControl;
12077 {
12078 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12079 directControl = mData->mSession.mDirectControl;
12080 }
12081
12082 /* ignore notifications sent after #OnSessionEnd() is called */
12083 if (!directControl)
12084 return S_OK;
12085
12086 return directControl->OnStorageControllerChange();
12087}
12088
12089/**
12090 * @note Locks this object for reading.
12091 */
12092HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
12093{
12094 LogFlowThisFunc(("\n"));
12095
12096 AutoCaller autoCaller(this);
12097 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12098
12099 ComPtr<IInternalSessionControl> directControl;
12100 {
12101 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12102 directControl = mData->mSession.mDirectControl;
12103 }
12104
12105 /* ignore notifications sent after #OnSessionEnd() is called */
12106 if (!directControl)
12107 return S_OK;
12108
12109 return directControl->OnMediumChange(aAttachment, aForce);
12110}
12111
12112/**
12113 * @note Locks this object for reading.
12114 */
12115HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
12116{
12117 LogFlowThisFunc(("\n"));
12118
12119 AutoCaller autoCaller(this);
12120 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12121
12122 ComPtr<IInternalSessionControl> directControl;
12123 {
12124 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12125 directControl = mData->mSession.mDirectControl;
12126 }
12127
12128 /* ignore notifications sent after #OnSessionEnd() is called */
12129 if (!directControl)
12130 return S_OK;
12131
12132 return directControl->OnCPUChange(aCPU, aRemove);
12133}
12134
12135HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
12136{
12137 LogFlowThisFunc(("\n"));
12138
12139 AutoCaller autoCaller(this);
12140 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12141
12142 ComPtr<IInternalSessionControl> directControl;
12143 {
12144 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12145 directControl = mData->mSession.mDirectControl;
12146 }
12147
12148 /* ignore notifications sent after #OnSessionEnd() is called */
12149 if (!directControl)
12150 return S_OK;
12151
12152 return directControl->OnCPUExecutionCapChange(aExecutionCap);
12153}
12154
12155/**
12156 * @note Locks this object for reading.
12157 */
12158HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
12159{
12160 LogFlowThisFunc(("\n"));
12161
12162 AutoCaller autoCaller(this);
12163 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12164
12165 ComPtr<IInternalSessionControl> directControl;
12166 {
12167 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12168 directControl = mData->mSession.mDirectControl;
12169 }
12170
12171 /* ignore notifications sent after #OnSessionEnd() is called */
12172 if (!directControl)
12173 return S_OK;
12174
12175 return directControl->OnVRDEServerChange(aRestart);
12176}
12177
12178/**
12179 * @note Locks this object for reading.
12180 */
12181HRESULT SessionMachine::onUSBControllerChange()
12182{
12183 LogFlowThisFunc(("\n"));
12184
12185 AutoCaller autoCaller(this);
12186 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12187
12188 ComPtr<IInternalSessionControl> directControl;
12189 {
12190 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12191 directControl = mData->mSession.mDirectControl;
12192 }
12193
12194 /* ignore notifications sent after #OnSessionEnd() is called */
12195 if (!directControl)
12196 return S_OK;
12197
12198 return directControl->OnUSBControllerChange();
12199}
12200
12201/**
12202 * @note Locks this object for reading.
12203 */
12204HRESULT SessionMachine::onSharedFolderChange()
12205{
12206 LogFlowThisFunc(("\n"));
12207
12208 AutoCaller autoCaller(this);
12209 AssertComRCReturnRC(autoCaller.rc());
12210
12211 ComPtr<IInternalSessionControl> directControl;
12212 {
12213 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12214 directControl = mData->mSession.mDirectControl;
12215 }
12216
12217 /* ignore notifications sent after #OnSessionEnd() is called */
12218 if (!directControl)
12219 return S_OK;
12220
12221 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
12222}
12223
12224/**
12225 * @note Locks this object for reading.
12226 */
12227HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
12228{
12229 LogFlowThisFunc(("\n"));
12230
12231 AutoCaller autoCaller(this);
12232 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12233
12234 ComPtr<IInternalSessionControl> directControl;
12235 {
12236 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12237 directControl = mData->mSession.mDirectControl;
12238 }
12239
12240 /* ignore notifications sent after #OnSessionEnd() is called */
12241 if (!directControl)
12242 return S_OK;
12243
12244 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
12245}
12246
12247/**
12248 * @note Locks this object for reading.
12249 */
12250HRESULT SessionMachine::onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove)
12251{
12252 LogFlowThisFunc(("\n"));
12253
12254 AutoCaller autoCaller(this);
12255 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12256
12257 ComPtr<IInternalSessionControl> directControl;
12258 {
12259 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12260 directControl = mData->mSession.mDirectControl;
12261 }
12262
12263 /* ignore notifications sent after #OnSessionEnd() is called */
12264 if (!directControl)
12265 return S_OK;
12266
12267 return directControl->OnStorageDeviceChange(aAttachment, aRemove);
12268}
12269
12270/**
12271 * Returns @c true if this machine's USB controller reports it has a matching
12272 * filter for the given USB device and @c false otherwise.
12273 *
12274 * @note Caller must have requested machine read lock.
12275 */
12276bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
12277{
12278 AutoCaller autoCaller(this);
12279 /* silently return if not ready -- this method may be called after the
12280 * direct machine session has been called */
12281 if (!autoCaller.isOk())
12282 return false;
12283
12284
12285#ifdef VBOX_WITH_USB
12286 switch (mData->mMachineState)
12287 {
12288 case MachineState_Starting:
12289 case MachineState_Restoring:
12290 case MachineState_TeleportingIn:
12291 case MachineState_Paused:
12292 case MachineState_Running:
12293 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
12294 * elsewhere... */
12295 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
12296 default: break;
12297 }
12298#else
12299 NOREF(aDevice);
12300 NOREF(aMaskedIfs);
12301#endif
12302 return false;
12303}
12304
12305/**
12306 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12307 */
12308HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
12309 IVirtualBoxErrorInfo *aError,
12310 ULONG aMaskedIfs)
12311{
12312 LogFlowThisFunc(("\n"));
12313
12314 AutoCaller autoCaller(this);
12315
12316 /* This notification may happen after the machine object has been
12317 * uninitialized (the session was closed), so don't assert. */
12318 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12319
12320 ComPtr<IInternalSessionControl> directControl;
12321 {
12322 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12323 directControl = mData->mSession.mDirectControl;
12324 }
12325
12326 /* fail on notifications sent after #OnSessionEnd() is called, it is
12327 * expected by the caller */
12328 if (!directControl)
12329 return E_FAIL;
12330
12331 /* No locks should be held at this point. */
12332 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12333 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12334
12335 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
12336}
12337
12338/**
12339 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12340 */
12341HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
12342 IVirtualBoxErrorInfo *aError)
12343{
12344 LogFlowThisFunc(("\n"));
12345
12346 AutoCaller autoCaller(this);
12347
12348 /* This notification may happen after the machine object has been
12349 * uninitialized (the session was closed), so don't assert. */
12350 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12351
12352 ComPtr<IInternalSessionControl> directControl;
12353 {
12354 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12355 directControl = mData->mSession.mDirectControl;
12356 }
12357
12358 /* fail on notifications sent after #OnSessionEnd() is called, it is
12359 * expected by the caller */
12360 if (!directControl)
12361 return E_FAIL;
12362
12363 /* No locks should be held at this point. */
12364 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12365 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12366
12367 return directControl->OnUSBDeviceDetach(aId, aError);
12368}
12369
12370// protected methods
12371/////////////////////////////////////////////////////////////////////////////
12372
12373/**
12374 * Helper method to finalize saving the state.
12375 *
12376 * @note Must be called from under this object's lock.
12377 *
12378 * @param aRc S_OK if the snapshot has been taken successfully
12379 * @param aErrMsg human readable error message for failure
12380 *
12381 * @note Locks mParent + this objects for writing.
12382 */
12383HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
12384{
12385 LogFlowThisFuncEnter();
12386
12387 AutoCaller autoCaller(this);
12388 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12389
12390 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12391
12392 HRESULT rc = S_OK;
12393
12394 if (SUCCEEDED(aRc))
12395 {
12396 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
12397
12398 /* save all VM settings */
12399 rc = saveSettings(NULL);
12400 // no need to check whether VirtualBox.xml needs saving also since
12401 // we can't have a name change pending at this point
12402 }
12403 else
12404 {
12405 // delete the saved state file (it might have been already created);
12406 // we need not check whether this is shared with a snapshot here because
12407 // we certainly created this saved state file here anew
12408 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
12409 }
12410
12411 /* notify the progress object about operation completion */
12412 Assert(mConsoleTaskData.mProgress);
12413 if (SUCCEEDED(aRc))
12414 mConsoleTaskData.mProgress->notifyComplete(S_OK);
12415 else
12416 {
12417 if (aErrMsg.length())
12418 mConsoleTaskData.mProgress->notifyComplete(aRc,
12419 COM_IIDOF(ISession),
12420 getComponentName(),
12421 aErrMsg.c_str());
12422 else
12423 mConsoleTaskData.mProgress->notifyComplete(aRc);
12424 }
12425
12426 /* clear out the temporary saved state data */
12427 mConsoleTaskData.mLastState = MachineState_Null;
12428 mConsoleTaskData.strStateFilePath.setNull();
12429 mConsoleTaskData.mProgress.setNull();
12430
12431 LogFlowThisFuncLeave();
12432 return rc;
12433}
12434
12435/**
12436 * Deletes the given file if it is no longer in use by either the current machine state
12437 * (if the machine is "saved") or any of the machine's snapshots.
12438 *
12439 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
12440 * but is different for each SnapshotMachine. When calling this, the order of calling this
12441 * function on the one hand and changing that variable OR the snapshots tree on the other hand
12442 * is therefore critical. I know, it's all rather messy.
12443 *
12444 * @param strStateFile
12445 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
12446 */
12447void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
12448 Snapshot *pSnapshotToIgnore)
12449{
12450 // it is safe to delete this saved state file if it is not currently in use by the machine ...
12451 if ( (strStateFile.isNotEmpty())
12452 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
12453 )
12454 // ... and it must also not be shared with other snapshots
12455 if ( !mData->mFirstSnapshot
12456 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
12457 // this checks the SnapshotMachine's state file paths
12458 )
12459 RTFileDelete(strStateFile.c_str());
12460}
12461
12462/**
12463 * Locks the attached media.
12464 *
12465 * All attached hard disks are locked for writing and DVD/floppy are locked for
12466 * reading. Parents of attached hard disks (if any) are locked for reading.
12467 *
12468 * This method also performs accessibility check of all media it locks: if some
12469 * media is inaccessible, the method will return a failure and a bunch of
12470 * extended error info objects per each inaccessible medium.
12471 *
12472 * Note that this method is atomic: if it returns a success, all media are
12473 * locked as described above; on failure no media is locked at all (all
12474 * succeeded individual locks will be undone).
12475 *
12476 * This method is intended to be called when the machine is in Starting or
12477 * Restoring state and asserts otherwise.
12478 *
12479 * The locks made by this method must be undone by calling #unlockMedia() when
12480 * no more needed.
12481 */
12482HRESULT SessionMachine::lockMedia()
12483{
12484 AutoCaller autoCaller(this);
12485 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12486
12487 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12488
12489 AssertReturn( mData->mMachineState == MachineState_Starting
12490 || mData->mMachineState == MachineState_Restoring
12491 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
12492 /* bail out if trying to lock things with already set up locking */
12493 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
12494
12495 clearError();
12496 MultiResult mrc(S_OK);
12497
12498 /* Collect locking information for all medium objects attached to the VM. */
12499 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
12500 it != mMediaData->mAttachments.end();
12501 ++it)
12502 {
12503 MediumAttachment* pAtt = *it;
12504 DeviceType_T devType = pAtt->getType();
12505 Medium *pMedium = pAtt->getMedium();
12506
12507 MediumLockList *pMediumLockList(new MediumLockList());
12508 // There can be attachments without a medium (floppy/dvd), and thus
12509 // it's impossible to create a medium lock list. It still makes sense
12510 // to have the empty medium lock list in the map in case a medium is
12511 // attached later.
12512 if (pMedium != NULL)
12513 {
12514 MediumType_T mediumType = pMedium->getType();
12515 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
12516 || mediumType == MediumType_Shareable;
12517 bool fIsVitalImage = (devType == DeviceType_HardDisk);
12518
12519 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
12520 !fIsReadOnlyLock /* fMediumLockWrite */,
12521 NULL,
12522 *pMediumLockList);
12523 if (FAILED(mrc))
12524 {
12525 delete pMediumLockList;
12526 mData->mSession.mLockedMedia.Clear();
12527 break;
12528 }
12529 }
12530
12531 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
12532 if (FAILED(rc))
12533 {
12534 mData->mSession.mLockedMedia.Clear();
12535 mrc = setError(rc,
12536 tr("Collecting locking information for all attached media failed"));
12537 break;
12538 }
12539 }
12540
12541 if (SUCCEEDED(mrc))
12542 {
12543 /* Now lock all media. If this fails, nothing is locked. */
12544 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12545 if (FAILED(rc))
12546 {
12547 mrc = setError(rc,
12548 tr("Locking of attached media failed"));
12549 }
12550 }
12551
12552 return mrc;
12553}
12554
12555/**
12556 * Undoes the locks made by by #lockMedia().
12557 */
12558void SessionMachine::unlockMedia()
12559{
12560 AutoCaller autoCaller(this);
12561 AssertComRCReturnVoid(autoCaller.rc());
12562
12563 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12564
12565 /* we may be holding important error info on the current thread;
12566 * preserve it */
12567 ErrorInfoKeeper eik;
12568
12569 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12570 AssertComRC(rc);
12571}
12572
12573/**
12574 * Helper to change the machine state (reimplementation).
12575 *
12576 * @note Locks this object for writing.
12577 */
12578HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12579{
12580 LogFlowThisFuncEnter();
12581 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12582
12583 AutoCaller autoCaller(this);
12584 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12585
12586 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12587
12588 MachineState_T oldMachineState = mData->mMachineState;
12589
12590 AssertMsgReturn(oldMachineState != aMachineState,
12591 ("oldMachineState=%s, aMachineState=%s\n",
12592 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12593 E_FAIL);
12594
12595 HRESULT rc = S_OK;
12596
12597 int stsFlags = 0;
12598 bool deleteSavedState = false;
12599
12600 /* detect some state transitions */
12601
12602 if ( ( oldMachineState == MachineState_Saved
12603 && aMachineState == MachineState_Restoring)
12604 || ( ( oldMachineState == MachineState_PoweredOff
12605 || oldMachineState == MachineState_Teleported
12606 || oldMachineState == MachineState_Aborted
12607 )
12608 && ( aMachineState == MachineState_TeleportingIn
12609 || aMachineState == MachineState_Starting
12610 )
12611 )
12612 )
12613 {
12614 /* The EMT thread is about to start */
12615
12616 /* Nothing to do here for now... */
12617
12618 /// @todo NEWMEDIA don't let mDVDDrive and other children
12619 /// change anything when in the Starting/Restoring state
12620 }
12621 else if ( ( oldMachineState == MachineState_Running
12622 || oldMachineState == MachineState_Paused
12623 || oldMachineState == MachineState_Teleporting
12624 || oldMachineState == MachineState_LiveSnapshotting
12625 || oldMachineState == MachineState_Stuck
12626 || oldMachineState == MachineState_Starting
12627 || oldMachineState == MachineState_Stopping
12628 || oldMachineState == MachineState_Saving
12629 || oldMachineState == MachineState_Restoring
12630 || oldMachineState == MachineState_TeleportingPausedVM
12631 || oldMachineState == MachineState_TeleportingIn
12632 )
12633 && ( aMachineState == MachineState_PoweredOff
12634 || aMachineState == MachineState_Saved
12635 || aMachineState == MachineState_Teleported
12636 || aMachineState == MachineState_Aborted
12637 )
12638 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
12639 * snapshot */
12640 && ( mConsoleTaskData.mSnapshot.isNull()
12641 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
12642 )
12643 )
12644 {
12645 /* The EMT thread has just stopped, unlock attached media. Note that as
12646 * opposed to locking that is done from Console, we do unlocking here
12647 * because the VM process may have aborted before having a chance to
12648 * properly unlock all media it locked. */
12649
12650 unlockMedia();
12651 }
12652
12653 if (oldMachineState == MachineState_Restoring)
12654 {
12655 if (aMachineState != MachineState_Saved)
12656 {
12657 /*
12658 * delete the saved state file once the machine has finished
12659 * restoring from it (note that Console sets the state from
12660 * Restoring to Saved if the VM couldn't restore successfully,
12661 * to give the user an ability to fix an error and retry --
12662 * we keep the saved state file in this case)
12663 */
12664 deleteSavedState = true;
12665 }
12666 }
12667 else if ( oldMachineState == MachineState_Saved
12668 && ( aMachineState == MachineState_PoweredOff
12669 || aMachineState == MachineState_Aborted
12670 || aMachineState == MachineState_Teleported
12671 )
12672 )
12673 {
12674 /*
12675 * delete the saved state after Console::ForgetSavedState() is called
12676 * or if the VM process (owning a direct VM session) crashed while the
12677 * VM was Saved
12678 */
12679
12680 /// @todo (dmik)
12681 // Not sure that deleting the saved state file just because of the
12682 // client death before it attempted to restore the VM is a good
12683 // thing. But when it crashes we need to go to the Aborted state
12684 // which cannot have the saved state file associated... The only
12685 // way to fix this is to make the Aborted condition not a VM state
12686 // but a bool flag: i.e., when a crash occurs, set it to true and
12687 // change the state to PoweredOff or Saved depending on the
12688 // saved state presence.
12689
12690 deleteSavedState = true;
12691 mData->mCurrentStateModified = TRUE;
12692 stsFlags |= SaveSTS_CurStateModified;
12693 }
12694
12695 if ( aMachineState == MachineState_Starting
12696 || aMachineState == MachineState_Restoring
12697 || aMachineState == MachineState_TeleportingIn
12698 )
12699 {
12700 /* set the current state modified flag to indicate that the current
12701 * state is no more identical to the state in the
12702 * current snapshot */
12703 if (!mData->mCurrentSnapshot.isNull())
12704 {
12705 mData->mCurrentStateModified = TRUE;
12706 stsFlags |= SaveSTS_CurStateModified;
12707 }
12708 }
12709
12710 if (deleteSavedState)
12711 {
12712 if (mRemoveSavedState)
12713 {
12714 Assert(!mSSData->strStateFilePath.isEmpty());
12715
12716 // it is safe to delete the saved state file if ...
12717 if ( !mData->mFirstSnapshot // ... we have no snapshots or
12718 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
12719 // ... none of the snapshots share the saved state file
12720 )
12721 RTFileDelete(mSSData->strStateFilePath.c_str());
12722 }
12723
12724 mSSData->strStateFilePath.setNull();
12725 stsFlags |= SaveSTS_StateFilePath;
12726 }
12727
12728 /* redirect to the underlying peer machine */
12729 mPeer->setMachineState(aMachineState);
12730
12731 if ( aMachineState == MachineState_PoweredOff
12732 || aMachineState == MachineState_Teleported
12733 || aMachineState == MachineState_Aborted
12734 || aMachineState == MachineState_Saved)
12735 {
12736 /* the machine has stopped execution
12737 * (or the saved state file was adopted) */
12738 stsFlags |= SaveSTS_StateTimeStamp;
12739 }
12740
12741 if ( ( oldMachineState == MachineState_PoweredOff
12742 || oldMachineState == MachineState_Aborted
12743 || oldMachineState == MachineState_Teleported
12744 )
12745 && aMachineState == MachineState_Saved)
12746 {
12747 /* the saved state file was adopted */
12748 Assert(!mSSData->strStateFilePath.isEmpty());
12749 stsFlags |= SaveSTS_StateFilePath;
12750 }
12751
12752#ifdef VBOX_WITH_GUEST_PROPS
12753 if ( aMachineState == MachineState_PoweredOff
12754 || aMachineState == MachineState_Aborted
12755 || aMachineState == MachineState_Teleported)
12756 {
12757 /* Make sure any transient guest properties get removed from the
12758 * property store on shutdown. */
12759
12760 HWData::GuestPropertyList::iterator it;
12761 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
12762 if (!fNeedsSaving)
12763 for (it = mHWData->mGuestProperties.begin();
12764 it != mHWData->mGuestProperties.end(); ++it)
12765 if ( (it->mFlags & guestProp::TRANSIENT)
12766 || (it->mFlags & guestProp::TRANSRESET))
12767 {
12768 fNeedsSaving = true;
12769 break;
12770 }
12771 if (fNeedsSaving)
12772 {
12773 mData->mCurrentStateModified = TRUE;
12774 stsFlags |= SaveSTS_CurStateModified;
12775 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
12776 }
12777 }
12778#endif
12779
12780 rc = saveStateSettings(stsFlags);
12781
12782 if ( ( oldMachineState != MachineState_PoweredOff
12783 && oldMachineState != MachineState_Aborted
12784 && oldMachineState != MachineState_Teleported
12785 )
12786 && ( aMachineState == MachineState_PoweredOff
12787 || aMachineState == MachineState_Aborted
12788 || aMachineState == MachineState_Teleported
12789 )
12790 )
12791 {
12792 /* we've been shut down for any reason */
12793 /* no special action so far */
12794 }
12795
12796 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
12797 LogFlowThisFuncLeave();
12798 return rc;
12799}
12800
12801/**
12802 * Sends the current machine state value to the VM process.
12803 *
12804 * @note Locks this object for reading, then calls a client process.
12805 */
12806HRESULT SessionMachine::updateMachineStateOnClient()
12807{
12808 AutoCaller autoCaller(this);
12809 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12810
12811 ComPtr<IInternalSessionControl> directControl;
12812 {
12813 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12814 AssertReturn(!!mData, E_FAIL);
12815 directControl = mData->mSession.mDirectControl;
12816
12817 /* directControl may be already set to NULL here in #OnSessionEnd()
12818 * called too early by the direct session process while there is still
12819 * some operation (like deleting the snapshot) in progress. The client
12820 * process in this case is waiting inside Session::close() for the
12821 * "end session" process object to complete, while #uninit() called by
12822 * #checkForDeath() on the Watcher thread is waiting for the pending
12823 * operation to complete. For now, we accept this inconsistent behavior
12824 * and simply do nothing here. */
12825
12826 if (mData->mSession.mState == SessionState_Unlocking)
12827 return S_OK;
12828
12829 AssertReturn(!directControl.isNull(), E_FAIL);
12830 }
12831
12832 return directControl->UpdateMachineState(mData->mMachineState);
12833}
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