VirtualBox

source: vbox/trunk/src/VBox/Main/MachineImpl.cpp@ 34263

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

Main: always write release logs into Logs subfolder of machine's folder

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