VirtualBox

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

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

VBoxHeadless/win: enable SVC in VBoxSVC, add SVC to host installer

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

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