VirtualBox

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

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

Main, FE/VBoxManage: Make it possible to mark specific controllers as bootable which means that the BIOS can access devices attached to the controller to boot from it

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 384.7 KB
Line 
1/* $Id: MachineImpl.cpp 34010 2010-11-11 20:17:47Z 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 /* Check 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 rc = setError(VBOX_E_OBJECT_IN_USE,
5245 tr("Another storage controller '%s' is already marked as bootable"),
5246 aCtrl->getName().c_str());
5247 break;
5248 }
5249 }
5250 }
5251
5252 if (SUCCEEDED(rc))
5253 {
5254 ctrl->setBootable(fBootable);
5255 setModified(IsModified_Storage);
5256 }
5257 }
5258
5259 if (SUCCEEDED(rc))
5260 {
5261 /* inform the direct session if any */
5262 alock.leave();
5263 onStorageControllerChange();
5264 }
5265
5266 return rc;
5267}
5268
5269STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5270{
5271 CheckComArgStrNotEmptyOrNull(aName);
5272
5273 AutoCaller autoCaller(this);
5274 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5275
5276 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5277
5278 HRESULT rc = checkStateDependency(MutableStateDep);
5279 if (FAILED(rc)) return rc;
5280
5281 ComObjPtr<StorageController> ctrl;
5282 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5283 if (FAILED(rc)) return rc;
5284
5285 /* We can remove the controller only if there is no device attached. */
5286 /* check if the device slot is already busy */
5287 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5288 it != mMediaData->mAttachments.end();
5289 ++it)
5290 {
5291 if ((*it)->getControllerName() == aName)
5292 return setError(VBOX_E_OBJECT_IN_USE,
5293 tr("Storage controller named '%ls' has still devices attached"),
5294 aName);
5295 }
5296
5297 /* We can remove it now. */
5298 setModified(IsModified_Storage);
5299 mStorageControllers.backup();
5300
5301 ctrl->unshare();
5302
5303 mStorageControllers->remove(ctrl);
5304
5305 /* inform the direct session if any */
5306 alock.leave();
5307 onStorageControllerChange();
5308
5309 return S_OK;
5310}
5311
5312STDMETHODIMP Machine::QuerySavedGuestSize(ULONG uScreenId, ULONG *puWidth, ULONG *puHeight)
5313{
5314 LogFlowThisFunc(("\n"));
5315
5316 CheckComArgNotNull(puWidth);
5317 CheckComArgNotNull(puHeight);
5318
5319 uint32_t u32Width = 0;
5320 uint32_t u32Height = 0;
5321
5322 int vrc = readSavedGuestSize(mSSData->mStateFilePath, uScreenId, &u32Width, &u32Height);
5323 if (RT_FAILURE(vrc))
5324 return setError(VBOX_E_IPRT_ERROR,
5325 tr("Saved guest size is not available (%Rrc)"),
5326 vrc);
5327
5328 *puWidth = u32Width;
5329 *puHeight = u32Height;
5330
5331 return S_OK;
5332}
5333
5334STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5335{
5336 LogFlowThisFunc(("\n"));
5337
5338 CheckComArgNotNull(aSize);
5339 CheckComArgNotNull(aWidth);
5340 CheckComArgNotNull(aHeight);
5341
5342 if (aScreenId != 0)
5343 return E_NOTIMPL;
5344
5345 AutoCaller autoCaller(this);
5346 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5347
5348 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5349
5350 uint8_t *pu8Data = NULL;
5351 uint32_t cbData = 0;
5352 uint32_t u32Width = 0;
5353 uint32_t u32Height = 0;
5354
5355 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5356
5357 if (RT_FAILURE(vrc))
5358 return setError(VBOX_E_IPRT_ERROR,
5359 tr("Saved screenshot data is not available (%Rrc)"),
5360 vrc);
5361
5362 *aSize = cbData;
5363 *aWidth = u32Width;
5364 *aHeight = u32Height;
5365
5366 freeSavedDisplayScreenshot(pu8Data);
5367
5368 return S_OK;
5369}
5370
5371STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5372{
5373 LogFlowThisFunc(("\n"));
5374
5375 CheckComArgNotNull(aWidth);
5376 CheckComArgNotNull(aHeight);
5377 CheckComArgOutSafeArrayPointerValid(aData);
5378
5379 if (aScreenId != 0)
5380 return E_NOTIMPL;
5381
5382 AutoCaller autoCaller(this);
5383 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5384
5385 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5386
5387 uint8_t *pu8Data = NULL;
5388 uint32_t cbData = 0;
5389 uint32_t u32Width = 0;
5390 uint32_t u32Height = 0;
5391
5392 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5393
5394 if (RT_FAILURE(vrc))
5395 return setError(VBOX_E_IPRT_ERROR,
5396 tr("Saved screenshot data is not available (%Rrc)"),
5397 vrc);
5398
5399 *aWidth = u32Width;
5400 *aHeight = u32Height;
5401
5402 com::SafeArray<BYTE> bitmap(cbData);
5403 /* Convert pixels to format expected by the API caller. */
5404 if (aBGR)
5405 {
5406 /* [0] B, [1] G, [2] R, [3] A. */
5407 for (unsigned i = 0; i < cbData; i += 4)
5408 {
5409 bitmap[i] = pu8Data[i];
5410 bitmap[i + 1] = pu8Data[i + 1];
5411 bitmap[i + 2] = pu8Data[i + 2];
5412 bitmap[i + 3] = 0xff;
5413 }
5414 }
5415 else
5416 {
5417 /* [0] R, [1] G, [2] B, [3] A. */
5418 for (unsigned i = 0; i < cbData; i += 4)
5419 {
5420 bitmap[i] = pu8Data[i + 2];
5421 bitmap[i + 1] = pu8Data[i + 1];
5422 bitmap[i + 2] = pu8Data[i];
5423 bitmap[i + 3] = 0xff;
5424 }
5425 }
5426 bitmap.detachTo(ComSafeArrayOutArg(aData));
5427
5428 freeSavedDisplayScreenshot(pu8Data);
5429
5430 return S_OK;
5431}
5432
5433
5434STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5435{
5436 LogFlowThisFunc(("\n"));
5437
5438 CheckComArgNotNull(aWidth);
5439 CheckComArgNotNull(aHeight);
5440 CheckComArgOutSafeArrayPointerValid(aData);
5441
5442 if (aScreenId != 0)
5443 return E_NOTIMPL;
5444
5445 AutoCaller autoCaller(this);
5446 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5447
5448 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5449
5450 uint8_t *pu8Data = NULL;
5451 uint32_t cbData = 0;
5452 uint32_t u32Width = 0;
5453 uint32_t u32Height = 0;
5454
5455 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5456
5457 if (RT_FAILURE(vrc))
5458 return setError(VBOX_E_IPRT_ERROR,
5459 tr("Saved screenshot data is not available (%Rrc)"),
5460 vrc);
5461
5462 *aWidth = u32Width;
5463 *aHeight = u32Height;
5464
5465 uint8_t *pu8PNG = NULL;
5466 uint32_t cbPNG = 0;
5467 uint32_t cxPNG = 0;
5468 uint32_t cyPNG = 0;
5469
5470 DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
5471
5472 com::SafeArray<BYTE> screenData(cbPNG);
5473 screenData.initFrom(pu8PNG, cbPNG);
5474 RTMemFree(pu8PNG);
5475
5476 screenData.detachTo(ComSafeArrayOutArg(aData));
5477
5478 freeSavedDisplayScreenshot(pu8Data);
5479
5480 return S_OK;
5481}
5482
5483STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5484{
5485 LogFlowThisFunc(("\n"));
5486
5487 CheckComArgNotNull(aSize);
5488 CheckComArgNotNull(aWidth);
5489 CheckComArgNotNull(aHeight);
5490
5491 if (aScreenId != 0)
5492 return E_NOTIMPL;
5493
5494 AutoCaller autoCaller(this);
5495 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5496
5497 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5498
5499 uint8_t *pu8Data = NULL;
5500 uint32_t cbData = 0;
5501 uint32_t u32Width = 0;
5502 uint32_t u32Height = 0;
5503
5504 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5505
5506 if (RT_FAILURE(vrc))
5507 return setError(VBOX_E_IPRT_ERROR,
5508 tr("Saved screenshot data is not available (%Rrc)"),
5509 vrc);
5510
5511 *aSize = cbData;
5512 *aWidth = u32Width;
5513 *aHeight = u32Height;
5514
5515 freeSavedDisplayScreenshot(pu8Data);
5516
5517 return S_OK;
5518}
5519
5520STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5521{
5522 LogFlowThisFunc(("\n"));
5523
5524 CheckComArgNotNull(aWidth);
5525 CheckComArgNotNull(aHeight);
5526 CheckComArgOutSafeArrayPointerValid(aData);
5527
5528 if (aScreenId != 0)
5529 return E_NOTIMPL;
5530
5531 AutoCaller autoCaller(this);
5532 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5533
5534 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5535
5536 uint8_t *pu8Data = NULL;
5537 uint32_t cbData = 0;
5538 uint32_t u32Width = 0;
5539 uint32_t u32Height = 0;
5540
5541 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5542
5543 if (RT_FAILURE(vrc))
5544 return setError(VBOX_E_IPRT_ERROR,
5545 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
5546 vrc);
5547
5548 *aWidth = u32Width;
5549 *aHeight = u32Height;
5550
5551 com::SafeArray<BYTE> png(cbData);
5552 png.initFrom(pu8Data, cbData);
5553 png.detachTo(ComSafeArrayOutArg(aData));
5554
5555 freeSavedDisplayScreenshot(pu8Data);
5556
5557 return S_OK;
5558}
5559
5560STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5561{
5562 HRESULT rc = S_OK;
5563 LogFlowThisFunc(("\n"));
5564
5565 AutoCaller autoCaller(this);
5566 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5567
5568 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5569
5570 if (!mHWData->mCPUHotPlugEnabled)
5571 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5572
5573 if (aCpu >= mHWData->mCPUCount)
5574 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5575
5576 if (mHWData->mCPUAttached[aCpu])
5577 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5578
5579 alock.release();
5580 rc = onCPUChange(aCpu, false);
5581 alock.acquire();
5582 if (FAILED(rc)) return rc;
5583
5584 setModified(IsModified_MachineData);
5585 mHWData.backup();
5586 mHWData->mCPUAttached[aCpu] = true;
5587
5588 /* Save settings if online */
5589 if (Global::IsOnline(mData->mMachineState))
5590 saveSettings(NULL);
5591
5592 return S_OK;
5593}
5594
5595STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5596{
5597 HRESULT rc = S_OK;
5598 LogFlowThisFunc(("\n"));
5599
5600 AutoCaller autoCaller(this);
5601 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5602
5603 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5604
5605 if (!mHWData->mCPUHotPlugEnabled)
5606 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5607
5608 if (aCpu >= SchemaDefs::MaxCPUCount)
5609 return setError(E_INVALIDARG,
5610 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5611 SchemaDefs::MaxCPUCount);
5612
5613 if (!mHWData->mCPUAttached[aCpu])
5614 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5615
5616 /* CPU 0 can't be detached */
5617 if (aCpu == 0)
5618 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5619
5620 alock.release();
5621 rc = onCPUChange(aCpu, true);
5622 alock.acquire();
5623 if (FAILED(rc)) return rc;
5624
5625 setModified(IsModified_MachineData);
5626 mHWData.backup();
5627 mHWData->mCPUAttached[aCpu] = false;
5628
5629 /* Save settings if online */
5630 if (Global::IsOnline(mData->mMachineState))
5631 saveSettings(NULL);
5632
5633 return S_OK;
5634}
5635
5636STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5637{
5638 LogFlowThisFunc(("\n"));
5639
5640 CheckComArgNotNull(aCpuAttached);
5641
5642 *aCpuAttached = false;
5643
5644 AutoCaller autoCaller(this);
5645 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5646
5647 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5648
5649 /* If hotplug is enabled the CPU is always enabled. */
5650 if (!mHWData->mCPUHotPlugEnabled)
5651 {
5652 if (aCpu < mHWData->mCPUCount)
5653 *aCpuAttached = true;
5654 }
5655 else
5656 {
5657 if (aCpu < SchemaDefs::MaxCPUCount)
5658 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5659 }
5660
5661 return S_OK;
5662}
5663
5664STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5665{
5666 CheckComArgOutPointerValid(aName);
5667
5668 AutoCaller autoCaller(this);
5669 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5670
5671 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5672
5673 Utf8Str log = queryLogFilename(aIdx);
5674 if (!RTFileExists(log.c_str()))
5675 log.setNull();
5676 log.cloneTo(aName);
5677
5678 return S_OK;
5679}
5680
5681STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
5682{
5683 LogFlowThisFunc(("\n"));
5684 CheckComArgOutSafeArrayPointerValid(aData);
5685 if (aSize < 0)
5686 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
5687
5688 AutoCaller autoCaller(this);
5689 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5690
5691 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5692
5693 HRESULT rc = S_OK;
5694 Utf8Str log = queryLogFilename(aIdx);
5695
5696 /* do not unnecessarily hold the lock while doing something which does
5697 * not need the lock and potentially takes a long time. */
5698 alock.release();
5699
5700 /* Limit the chunk size to 32K for now, as that gives better performance
5701 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5702 * One byte expands to approx. 25 bytes of breathtaking XML. */
5703 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5704 com::SafeArray<BYTE> logData(cbData);
5705
5706 RTFILE LogFile;
5707 int vrc = RTFileOpen(&LogFile, log.c_str(),
5708 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5709 if (RT_SUCCESS(vrc))
5710 {
5711 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5712 if (RT_SUCCESS(vrc))
5713 logData.resize(cbData);
5714 else
5715 rc = setError(VBOX_E_IPRT_ERROR,
5716 tr("Could not read log file '%s' (%Rrc)"),
5717 log.c_str(), vrc);
5718 RTFileClose(LogFile);
5719 }
5720 else
5721 rc = setError(VBOX_E_IPRT_ERROR,
5722 tr("Could not open log file '%s' (%Rrc)"),
5723 log.c_str(), vrc);
5724
5725 if (FAILED(rc))
5726 logData.resize(0);
5727 logData.detachTo(ComSafeArrayOutArg(aData));
5728
5729 return rc;
5730}
5731
5732
5733// public methods for internal purposes
5734/////////////////////////////////////////////////////////////////////////////
5735
5736/**
5737 * Adds the given IsModified_* flag to the dirty flags of the machine.
5738 * This must be called either during loadSettings or under the machine write lock.
5739 * @param fl
5740 */
5741void Machine::setModified(uint32_t fl)
5742{
5743 mData->flModifications |= fl;
5744}
5745
5746/**
5747 * Saves the registry entry of this machine to the given configuration node.
5748 *
5749 * @param aEntryNode Node to save the registry entry to.
5750 *
5751 * @note locks this object for reading.
5752 */
5753HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5754{
5755 AutoLimitedCaller autoCaller(this);
5756 AssertComRCReturnRC(autoCaller.rc());
5757
5758 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5759
5760 data.uuid = mData->mUuid;
5761 data.strSettingsFile = mData->m_strConfigFile;
5762
5763 return S_OK;
5764}
5765
5766/**
5767 * Calculates the absolute path of the given path taking the directory of the
5768 * machine settings file as the current directory.
5769 *
5770 * @param aPath Path to calculate the absolute path for.
5771 * @param aResult Where to put the result (used only on success, can be the
5772 * same Utf8Str instance as passed in @a aPath).
5773 * @return IPRT result.
5774 *
5775 * @note Locks this object for reading.
5776 */
5777int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5778{
5779 AutoCaller autoCaller(this);
5780 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5781
5782 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5783
5784 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5785
5786 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5787
5788 strSettingsDir.stripFilename();
5789 char folder[RTPATH_MAX];
5790 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5791 if (RT_SUCCESS(vrc))
5792 aResult = folder;
5793
5794 return vrc;
5795}
5796
5797/**
5798 * Copies strSource to strTarget, making it relative to the machine folder
5799 * if it is a subdirectory thereof, or simply copying it otherwise.
5800 *
5801 * @param strSource Path to evaluate and copy.
5802 * @param strTarget Buffer to receive target path.
5803 *
5804 * @note Locks this object for reading.
5805 */
5806void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5807 Utf8Str &strTarget)
5808{
5809 AutoCaller autoCaller(this);
5810 AssertComRCReturn(autoCaller.rc(), (void)0);
5811
5812 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5813
5814 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5815 // use strTarget as a temporary buffer to hold the machine settings dir
5816 strTarget = mData->m_strConfigFileFull;
5817 strTarget.stripFilename();
5818 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5819 // is relative: then append what's left
5820 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
5821 else
5822 // is not relative: then overwrite
5823 strTarget = strSource;
5824}
5825
5826/**
5827 * Returns the full path to the machine's log folder in the
5828 * \a aLogFolder argument.
5829 */
5830void Machine::getLogFolder(Utf8Str &aLogFolder)
5831{
5832 AutoCaller autoCaller(this);
5833 AssertComRCReturnVoid(autoCaller.rc());
5834
5835 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5836
5837 Utf8Str settingsDir;
5838 if (isInOwnDir(&settingsDir))
5839 /* Log folder is <Machines>/<VM_Name>/Logs */
5840 aLogFolder = settingsDir;
5841 else
5842 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5843 calculateFullPath(mUserData->s.strSnapshotFolder, aLogFolder);
5844
5845 aLogFolder.append(RTPATH_DELIMITER);
5846 aLogFolder.append("Logs");
5847}
5848
5849/**
5850 * Returns the full path to the machine's log file for an given index.
5851 */
5852Utf8Str Machine::queryLogFilename(ULONG idx)
5853{
5854 Utf8Str logFolder;
5855 getLogFolder(logFolder);
5856 Assert(logFolder.length());
5857 Utf8Str log;
5858 if (idx == 0)
5859 log = Utf8StrFmt("%s%cVBox.log",
5860 logFolder.c_str(), RTPATH_DELIMITER);
5861 else
5862 log = Utf8StrFmt("%s%cVBox.log.%d",
5863 logFolder.c_str(), RTPATH_DELIMITER, idx);
5864 return log;
5865}
5866
5867/**
5868 * @note Locks this object for writing, calls the client process
5869 * (inside the lock).
5870 */
5871HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5872 IN_BSTR aType,
5873 IN_BSTR aEnvironment,
5874 ProgressProxy *aProgress)
5875{
5876 LogFlowThisFuncEnter();
5877
5878 AssertReturn(aControl, E_FAIL);
5879 AssertReturn(aProgress, E_FAIL);
5880
5881 AutoCaller autoCaller(this);
5882 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5883
5884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5885
5886 if (!mData->mRegistered)
5887 return setError(E_UNEXPECTED,
5888 tr("The machine '%s' is not registered"),
5889 mUserData->s.strName.c_str());
5890
5891 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5892
5893 if ( mData->mSession.mState == SessionState_Locked
5894 || mData->mSession.mState == SessionState_Spawning
5895 || mData->mSession.mState == SessionState_Unlocking)
5896 return setError(VBOX_E_INVALID_OBJECT_STATE,
5897 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
5898 mUserData->s.strName.c_str());
5899
5900 /* may not be busy */
5901 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5902
5903 /* get the path to the executable */
5904 char szPath[RTPATH_MAX];
5905 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5906 size_t sz = strlen(szPath);
5907 szPath[sz++] = RTPATH_DELIMITER;
5908 szPath[sz] = 0;
5909 char *cmd = szPath + sz;
5910 sz = RTPATH_MAX - sz;
5911
5912 int vrc = VINF_SUCCESS;
5913 RTPROCESS pid = NIL_RTPROCESS;
5914
5915 RTENV env = RTENV_DEFAULT;
5916
5917 if (aEnvironment != NULL && *aEnvironment)
5918 {
5919 char *newEnvStr = NULL;
5920
5921 do
5922 {
5923 /* clone the current environment */
5924 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5925 AssertRCBreakStmt(vrc2, vrc = vrc2);
5926
5927 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5928 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5929
5930 /* put new variables to the environment
5931 * (ignore empty variable names here since RTEnv API
5932 * intentionally doesn't do that) */
5933 char *var = newEnvStr;
5934 for (char *p = newEnvStr; *p; ++p)
5935 {
5936 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5937 {
5938 *p = '\0';
5939 if (*var)
5940 {
5941 char *val = strchr(var, '=');
5942 if (val)
5943 {
5944 *val++ = '\0';
5945 vrc2 = RTEnvSetEx(env, var, val);
5946 }
5947 else
5948 vrc2 = RTEnvUnsetEx(env, var);
5949 if (RT_FAILURE(vrc2))
5950 break;
5951 }
5952 var = p + 1;
5953 }
5954 }
5955 if (RT_SUCCESS(vrc2) && *var)
5956 vrc2 = RTEnvPutEx(env, var);
5957
5958 AssertRCBreakStmt(vrc2, vrc = vrc2);
5959 }
5960 while (0);
5961
5962 if (newEnvStr != NULL)
5963 RTStrFree(newEnvStr);
5964 }
5965
5966 Utf8Str strType(aType);
5967
5968 /* Qt is default */
5969#ifdef VBOX_WITH_QTGUI
5970 if (strType == "gui" || strType == "GUI/Qt")
5971 {
5972# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5973 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5974# else
5975 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5976# endif
5977 Assert(sz >= sizeof(VirtualBox_exe));
5978 strcpy(cmd, VirtualBox_exe);
5979
5980 Utf8Str idStr = mData->mUuid.toString();
5981 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5982 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5983 }
5984#else /* !VBOX_WITH_QTGUI */
5985 if (0)
5986 ;
5987#endif /* VBOX_WITH_QTGUI */
5988
5989 else
5990
5991#ifdef VBOX_WITH_VBOXSDL
5992 if (strType == "sdl" || strType == "GUI/SDL")
5993 {
5994 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5995 Assert(sz >= sizeof(VBoxSDL_exe));
5996 strcpy(cmd, VBoxSDL_exe);
5997
5998 Utf8Str idStr = mData->mUuid.toString();
5999 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6000 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6001 }
6002#else /* !VBOX_WITH_VBOXSDL */
6003 if (0)
6004 ;
6005#endif /* !VBOX_WITH_VBOXSDL */
6006
6007 else
6008
6009#ifdef VBOX_WITH_HEADLESS
6010 if ( strType == "headless"
6011 || strType == "capture"
6012 || strType == "vrdp" /* Deprecated. Same as headless. */
6013 )
6014 {
6015 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6016 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6017 * and a VM works even if the server has not been installed.
6018 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6019 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6020 * differently in 4.0 and 3.x.
6021 */
6022 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6023 Assert(sz >= sizeof(VBoxHeadless_exe));
6024 strcpy(cmd, VBoxHeadless_exe);
6025
6026 Utf8Str idStr = mData->mUuid.toString();
6027 /* Leave space for "--capture" arg. */
6028 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0, 0 };
6029 if (strType == "capture")
6030 {
6031 unsigned pos = RT_ELEMENTS(args) - 2;
6032 args[pos] = "--capture";
6033 }
6034 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6035 }
6036#else /* !VBOX_WITH_HEADLESS */
6037 if (0)
6038 ;
6039#endif /* !VBOX_WITH_HEADLESS */
6040 else
6041 {
6042 RTEnvDestroy(env);
6043 return setError(E_INVALIDARG,
6044 tr("Invalid session type: '%s'"),
6045 strType.c_str());
6046 }
6047
6048 RTEnvDestroy(env);
6049
6050 if (RT_FAILURE(vrc))
6051 return setError(VBOX_E_IPRT_ERROR,
6052 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6053 mUserData->s.strName.c_str(), vrc);
6054
6055 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6056
6057 /*
6058 * Note that we don't leave the lock here before calling the client,
6059 * because it doesn't need to call us back if called with a NULL argument.
6060 * Leaving the lock here is dangerous because we didn't prepare the
6061 * launch data yet, but the client we've just started may happen to be
6062 * too fast and call openSession() that will fail (because of PID, etc.),
6063 * so that the Machine will never get out of the Spawning session state.
6064 */
6065
6066 /* inform the session that it will be a remote one */
6067 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6068 HRESULT rc = aControl->AssignMachine(NULL);
6069 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6070
6071 if (FAILED(rc))
6072 {
6073 /* restore the session state */
6074 mData->mSession.mState = SessionState_Unlocked;
6075 /* The failure may occur w/o any error info (from RPC), so provide one */
6076 return setError(VBOX_E_VM_ERROR,
6077 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6078 }
6079
6080 /* attach launch data to the machine */
6081 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6082 mData->mSession.mRemoteControls.push_back (aControl);
6083 mData->mSession.mProgress = aProgress;
6084 mData->mSession.mPid = pid;
6085 mData->mSession.mState = SessionState_Spawning;
6086 mData->mSession.mType = strType;
6087
6088 LogFlowThisFuncLeave();
6089 return S_OK;
6090}
6091
6092/**
6093 * Returns @c true if the given machine has an open direct session and returns
6094 * the session machine instance and additional session data (on some platforms)
6095 * if so.
6096 *
6097 * Note that when the method returns @c false, the arguments remain unchanged.
6098 *
6099 * @param aMachine Session machine object.
6100 * @param aControl Direct session control object (optional).
6101 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6102 *
6103 * @note locks this object for reading.
6104 */
6105#if defined(RT_OS_WINDOWS)
6106bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6107 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6108 HANDLE *aIPCSem /*= NULL*/,
6109 bool aAllowClosing /*= false*/)
6110#elif defined(RT_OS_OS2)
6111bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6112 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6113 HMTX *aIPCSem /*= NULL*/,
6114 bool aAllowClosing /*= false*/)
6115#else
6116bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6117 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6118 bool aAllowClosing /*= false*/)
6119#endif
6120{
6121 AutoLimitedCaller autoCaller(this);
6122 AssertComRCReturn(autoCaller.rc(), false);
6123
6124 /* just return false for inaccessible machines */
6125 if (autoCaller.state() != Ready)
6126 return false;
6127
6128 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6129
6130 if ( mData->mSession.mState == SessionState_Locked
6131 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6132 )
6133 {
6134 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6135
6136 aMachine = mData->mSession.mMachine;
6137
6138 if (aControl != NULL)
6139 *aControl = mData->mSession.mDirectControl;
6140
6141#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6142 /* Additional session data */
6143 if (aIPCSem != NULL)
6144 *aIPCSem = aMachine->mIPCSem;
6145#endif
6146 return true;
6147 }
6148
6149 return false;
6150}
6151
6152/**
6153 * Returns @c true if the given machine has an spawning direct session and
6154 * returns and additional session data (on some platforms) if so.
6155 *
6156 * Note that when the method returns @c false, the arguments remain unchanged.
6157 *
6158 * @param aPID PID of the spawned direct session process.
6159 *
6160 * @note locks this object for reading.
6161 */
6162#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6163bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6164#else
6165bool Machine::isSessionSpawning()
6166#endif
6167{
6168 AutoLimitedCaller autoCaller(this);
6169 AssertComRCReturn(autoCaller.rc(), false);
6170
6171 /* just return false for inaccessible machines */
6172 if (autoCaller.state() != Ready)
6173 return false;
6174
6175 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6176
6177 if (mData->mSession.mState == SessionState_Spawning)
6178 {
6179#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6180 /* Additional session data */
6181 if (aPID != NULL)
6182 {
6183 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6184 *aPID = mData->mSession.mPid;
6185 }
6186#endif
6187 return true;
6188 }
6189
6190 return false;
6191}
6192
6193/**
6194 * Called from the client watcher thread to check for unexpected client process
6195 * death during Session_Spawning state (e.g. before it successfully opened a
6196 * direct session).
6197 *
6198 * On Win32 and on OS/2, this method is called only when we've got the
6199 * direct client's process termination notification, so it always returns @c
6200 * true.
6201 *
6202 * On other platforms, this method returns @c true if the client process is
6203 * terminated and @c false if it's still alive.
6204 *
6205 * @note Locks this object for writing.
6206 */
6207bool Machine::checkForSpawnFailure()
6208{
6209 AutoCaller autoCaller(this);
6210 if (!autoCaller.isOk())
6211 {
6212 /* nothing to do */
6213 LogFlowThisFunc(("Already uninitialized!\n"));
6214 return true;
6215 }
6216
6217 /* VirtualBox::addProcessToReap() needs a write lock */
6218 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6219
6220 if (mData->mSession.mState != SessionState_Spawning)
6221 {
6222 /* nothing to do */
6223 LogFlowThisFunc(("Not spawning any more!\n"));
6224 return true;
6225 }
6226
6227 HRESULT rc = S_OK;
6228
6229#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6230
6231 /* the process was already unexpectedly terminated, we just need to set an
6232 * error and finalize session spawning */
6233 rc = setError(E_FAIL,
6234 tr("The virtual machine '%ls' has terminated unexpectedly during startup"),
6235 getName().c_str());
6236#else
6237
6238 /* PID not yet initialized, skip check. */
6239 if (mData->mSession.mPid == NIL_RTPROCESS)
6240 return false;
6241
6242 RTPROCSTATUS status;
6243 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6244 &status);
6245
6246 if (vrc != VERR_PROCESS_RUNNING)
6247 {
6248 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6249 rc = setError(E_FAIL,
6250 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6251 getName().c_str(), status.iStatus);
6252 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6253 rc = setError(E_FAIL,
6254 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6255 getName().c_str(), status.iStatus);
6256 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6257 rc = setError(E_FAIL,
6258 tr("The virtual machine '%s' has terminated abnormally"),
6259 getName().c_str(), status.iStatus);
6260 else
6261 rc = setError(E_FAIL,
6262 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6263 getName().c_str(), rc);
6264 }
6265
6266#endif
6267
6268 if (FAILED(rc))
6269 {
6270 /* Close the remote session, remove the remote control from the list
6271 * and reset session state to Closed (@note keep the code in sync with
6272 * the relevant part in checkForSpawnFailure()). */
6273
6274 Assert(mData->mSession.mRemoteControls.size() == 1);
6275 if (mData->mSession.mRemoteControls.size() == 1)
6276 {
6277 ErrorInfoKeeper eik;
6278 mData->mSession.mRemoteControls.front()->Uninitialize();
6279 }
6280
6281 mData->mSession.mRemoteControls.clear();
6282 mData->mSession.mState = SessionState_Unlocked;
6283
6284 /* finalize the progress after setting the state */
6285 if (!mData->mSession.mProgress.isNull())
6286 {
6287 mData->mSession.mProgress->notifyComplete(rc);
6288 mData->mSession.mProgress.setNull();
6289 }
6290
6291 mParent->addProcessToReap(mData->mSession.mPid);
6292 mData->mSession.mPid = NIL_RTPROCESS;
6293
6294 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6295 return true;
6296 }
6297
6298 return false;
6299}
6300
6301/**
6302 * Checks whether the machine can be registered. If so, commits and saves
6303 * all settings.
6304 *
6305 * @note Must be called from mParent's write lock. Locks this object and
6306 * children for writing.
6307 */
6308HRESULT Machine::prepareRegister()
6309{
6310 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6311
6312 AutoLimitedCaller autoCaller(this);
6313 AssertComRCReturnRC(autoCaller.rc());
6314
6315 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6316
6317 /* wait for state dependents to drop to zero */
6318 ensureNoStateDependencies();
6319
6320 if (!mData->mAccessible)
6321 return setError(VBOX_E_INVALID_OBJECT_STATE,
6322 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6323 mUserData->s.strName.c_str(),
6324 mData->mUuid.toString().c_str());
6325
6326 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6327
6328 if (mData->mRegistered)
6329 return setError(VBOX_E_INVALID_OBJECT_STATE,
6330 tr("The machine '%s' with UUID {%s} is already registered"),
6331 mUserData->s.strName.c_str(),
6332 mData->mUuid.toString().c_str());
6333
6334 HRESULT rc = S_OK;
6335
6336 // Ensure the settings are saved. If we are going to be registered and
6337 // no config file exists yet, create it by calling saveSettings() too.
6338 if ( (mData->flModifications)
6339 || (!mData->pMachineConfigFile->fileExists())
6340 )
6341 {
6342 rc = saveSettings(NULL);
6343 // no need to check whether VirtualBox.xml needs saving too since
6344 // we can't have a machine XML file rename pending
6345 if (FAILED(rc)) return rc;
6346 }
6347
6348 /* more config checking goes here */
6349
6350 if (SUCCEEDED(rc))
6351 {
6352 /* we may have had implicit modifications we want to fix on success */
6353 commit();
6354
6355 mData->mRegistered = true;
6356 }
6357 else
6358 {
6359 /* we may have had implicit modifications we want to cancel on failure*/
6360 rollback(false /* aNotify */);
6361 }
6362
6363 return rc;
6364}
6365
6366/**
6367 * Increases the number of objects dependent on the machine state or on the
6368 * registered state. Guarantees that these two states will not change at least
6369 * until #releaseStateDependency() is called.
6370 *
6371 * Depending on the @a aDepType value, additional state checks may be made.
6372 * These checks will set extended error info on failure. See
6373 * #checkStateDependency() for more info.
6374 *
6375 * If this method returns a failure, the dependency is not added and the caller
6376 * is not allowed to rely on any particular machine state or registration state
6377 * value and may return the failed result code to the upper level.
6378 *
6379 * @param aDepType Dependency type to add.
6380 * @param aState Current machine state (NULL if not interested).
6381 * @param aRegistered Current registered state (NULL if not interested).
6382 *
6383 * @note Locks this object for writing.
6384 */
6385HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6386 MachineState_T *aState /* = NULL */,
6387 BOOL *aRegistered /* = NULL */)
6388{
6389 AutoCaller autoCaller(this);
6390 AssertComRCReturnRC(autoCaller.rc());
6391
6392 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6393
6394 HRESULT rc = checkStateDependency(aDepType);
6395 if (FAILED(rc)) return rc;
6396
6397 {
6398 if (mData->mMachineStateChangePending != 0)
6399 {
6400 /* ensureNoStateDependencies() is waiting for state dependencies to
6401 * drop to zero so don't add more. It may make sense to wait a bit
6402 * and retry before reporting an error (since the pending state
6403 * transition should be really quick) but let's just assert for
6404 * now to see if it ever happens on practice. */
6405
6406 AssertFailed();
6407
6408 return setError(E_ACCESSDENIED,
6409 tr("Machine state change is in progress. Please retry the operation later."));
6410 }
6411
6412 ++mData->mMachineStateDeps;
6413 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6414 }
6415
6416 if (aState)
6417 *aState = mData->mMachineState;
6418 if (aRegistered)
6419 *aRegistered = mData->mRegistered;
6420
6421 return S_OK;
6422}
6423
6424/**
6425 * Decreases the number of objects dependent on the machine state.
6426 * Must always complete the #addStateDependency() call after the state
6427 * dependency is no more necessary.
6428 */
6429void Machine::releaseStateDependency()
6430{
6431 AutoCaller autoCaller(this);
6432 AssertComRCReturnVoid(autoCaller.rc());
6433
6434 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6435
6436 /* releaseStateDependency() w/o addStateDependency()? */
6437 AssertReturnVoid(mData->mMachineStateDeps != 0);
6438 -- mData->mMachineStateDeps;
6439
6440 if (mData->mMachineStateDeps == 0)
6441 {
6442 /* inform ensureNoStateDependencies() that there are no more deps */
6443 if (mData->mMachineStateChangePending != 0)
6444 {
6445 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6446 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6447 }
6448 }
6449}
6450
6451// protected methods
6452/////////////////////////////////////////////////////////////////////////////
6453
6454/**
6455 * Performs machine state checks based on the @a aDepType value. If a check
6456 * fails, this method will set extended error info, otherwise it will return
6457 * S_OK. It is supposed, that on failure, the caller will immediately return
6458 * the return value of this method to the upper level.
6459 *
6460 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6461 *
6462 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6463 * current state of this machine object allows to change settings of the
6464 * machine (i.e. the machine is not registered, or registered but not running
6465 * and not saved). It is useful to call this method from Machine setters
6466 * before performing any change.
6467 *
6468 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6469 * as for MutableStateDep except that if the machine is saved, S_OK is also
6470 * returned. This is useful in setters which allow changing machine
6471 * properties when it is in the saved state.
6472 *
6473 * @param aDepType Dependency type to check.
6474 *
6475 * @note Non Machine based classes should use #addStateDependency() and
6476 * #releaseStateDependency() methods or the smart AutoStateDependency
6477 * template.
6478 *
6479 * @note This method must be called from under this object's read or write
6480 * lock.
6481 */
6482HRESULT Machine::checkStateDependency(StateDependency aDepType)
6483{
6484 switch (aDepType)
6485 {
6486 case AnyStateDep:
6487 {
6488 break;
6489 }
6490 case MutableStateDep:
6491 {
6492 if ( mData->mRegistered
6493 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6494 || ( mData->mMachineState != MachineState_Paused
6495 && mData->mMachineState != MachineState_Running
6496 && mData->mMachineState != MachineState_Aborted
6497 && mData->mMachineState != MachineState_Teleported
6498 && mData->mMachineState != MachineState_PoweredOff
6499 )
6500 )
6501 )
6502 return setError(VBOX_E_INVALID_VM_STATE,
6503 tr("The machine is not mutable (state is %s)"),
6504 Global::stringifyMachineState(mData->mMachineState));
6505 break;
6506 }
6507 case MutableOrSavedStateDep:
6508 {
6509 if ( mData->mRegistered
6510 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6511 || ( mData->mMachineState != MachineState_Paused
6512 && mData->mMachineState != MachineState_Running
6513 && mData->mMachineState != MachineState_Aborted
6514 && mData->mMachineState != MachineState_Teleported
6515 && mData->mMachineState != MachineState_Saved
6516 && mData->mMachineState != MachineState_PoweredOff
6517 )
6518 )
6519 )
6520 return setError(VBOX_E_INVALID_VM_STATE,
6521 tr("The machine is not mutable (state is %s)"),
6522 Global::stringifyMachineState(mData->mMachineState));
6523 break;
6524 }
6525 }
6526
6527 return S_OK;
6528}
6529
6530/**
6531 * Helper to initialize all associated child objects and allocate data
6532 * structures.
6533 *
6534 * This method must be called as a part of the object's initialization procedure
6535 * (usually done in the #init() method).
6536 *
6537 * @note Must be called only from #init() or from #registeredInit().
6538 */
6539HRESULT Machine::initDataAndChildObjects()
6540{
6541 AutoCaller autoCaller(this);
6542 AssertComRCReturnRC(autoCaller.rc());
6543 AssertComRCReturn(autoCaller.state() == InInit ||
6544 autoCaller.state() == Limited, E_FAIL);
6545
6546 AssertReturn(!mData->mAccessible, E_FAIL);
6547
6548 /* allocate data structures */
6549 mSSData.allocate();
6550 mUserData.allocate();
6551 mHWData.allocate();
6552 mMediaData.allocate();
6553 mStorageControllers.allocate();
6554
6555 /* initialize mOSTypeId */
6556 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6557
6558 /* create associated BIOS settings object */
6559 unconst(mBIOSSettings).createObject();
6560 mBIOSSettings->init(this);
6561
6562 /* create an associated VRDE object (default is disabled) */
6563 unconst(mVRDEServer).createObject();
6564 mVRDEServer->init(this);
6565
6566 /* create associated serial port objects */
6567 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6568 {
6569 unconst(mSerialPorts[slot]).createObject();
6570 mSerialPorts[slot]->init(this, slot);
6571 }
6572
6573 /* create associated parallel port objects */
6574 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6575 {
6576 unconst(mParallelPorts[slot]).createObject();
6577 mParallelPorts[slot]->init(this, slot);
6578 }
6579
6580 /* create the audio adapter object (always present, default is disabled) */
6581 unconst(mAudioAdapter).createObject();
6582 mAudioAdapter->init(this);
6583
6584 /* create the USB controller object (always present, default is disabled) */
6585 unconst(mUSBController).createObject();
6586 mUSBController->init(this);
6587
6588 /* create associated network adapter objects */
6589 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6590 {
6591 unconst(mNetworkAdapters[slot]).createObject();
6592 mNetworkAdapters[slot]->init(this, slot);
6593 }
6594
6595 return S_OK;
6596}
6597
6598/**
6599 * Helper to uninitialize all associated child objects and to free all data
6600 * structures.
6601 *
6602 * This method must be called as a part of the object's uninitialization
6603 * procedure (usually done in the #uninit() method).
6604 *
6605 * @note Must be called only from #uninit() or from #registeredInit().
6606 */
6607void Machine::uninitDataAndChildObjects()
6608{
6609 AutoCaller autoCaller(this);
6610 AssertComRCReturnVoid(autoCaller.rc());
6611 AssertComRCReturnVoid( autoCaller.state() == InUninit
6612 || autoCaller.state() == Limited);
6613
6614 /* tell all our other child objects we've been uninitialized */
6615
6616 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6617 {
6618 if (mNetworkAdapters[slot])
6619 {
6620 mNetworkAdapters[slot]->uninit();
6621 unconst(mNetworkAdapters[slot]).setNull();
6622 }
6623 }
6624
6625 if (mUSBController)
6626 {
6627 mUSBController->uninit();
6628 unconst(mUSBController).setNull();
6629 }
6630
6631 if (mAudioAdapter)
6632 {
6633 mAudioAdapter->uninit();
6634 unconst(mAudioAdapter).setNull();
6635 }
6636
6637 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6638 {
6639 if (mParallelPorts[slot])
6640 {
6641 mParallelPorts[slot]->uninit();
6642 unconst(mParallelPorts[slot]).setNull();
6643 }
6644 }
6645
6646 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6647 {
6648 if (mSerialPorts[slot])
6649 {
6650 mSerialPorts[slot]->uninit();
6651 unconst(mSerialPorts[slot]).setNull();
6652 }
6653 }
6654
6655 if (mVRDEServer)
6656 {
6657 mVRDEServer->uninit();
6658 unconst(mVRDEServer).setNull();
6659 }
6660
6661 if (mBIOSSettings)
6662 {
6663 mBIOSSettings->uninit();
6664 unconst(mBIOSSettings).setNull();
6665 }
6666
6667 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6668 * instance is uninitialized; SessionMachine instances refer to real
6669 * Machine hard disks). This is necessary for a clean re-initialization of
6670 * the VM after successfully re-checking the accessibility state. Note
6671 * that in case of normal Machine or SnapshotMachine uninitialization (as
6672 * a result of unregistering or deleting the snapshot), outdated hard
6673 * disk attachments will already be uninitialized and deleted, so this
6674 * code will not affect them. */
6675 if ( !!mMediaData
6676 && (!isSessionMachine())
6677 )
6678 {
6679 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6680 it != mMediaData->mAttachments.end();
6681 ++it)
6682 {
6683 ComObjPtr<Medium> hd = (*it)->getMedium();
6684 if (hd.isNull())
6685 continue;
6686 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6687 AssertComRC(rc);
6688 }
6689 }
6690
6691 if (!isSessionMachine() && !isSnapshotMachine())
6692 {
6693 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6694 if (mData->mFirstSnapshot)
6695 {
6696 // snapshots tree is protected by media write lock; strictly
6697 // this isn't necessary here since we're deleting the entire
6698 // machine, but otherwise we assert in Snapshot::uninit()
6699 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6700 mData->mFirstSnapshot->uninit();
6701 mData->mFirstSnapshot.setNull();
6702 }
6703
6704 mData->mCurrentSnapshot.setNull();
6705 }
6706
6707 /* free data structures (the essential mData structure is not freed here
6708 * since it may be still in use) */
6709 mMediaData.free();
6710 mStorageControllers.free();
6711 mHWData.free();
6712 mUserData.free();
6713 mSSData.free();
6714}
6715
6716/**
6717 * Returns a pointer to the Machine object for this machine that acts like a
6718 * parent for complex machine data objects such as shared folders, etc.
6719 *
6720 * For primary Machine objects and for SnapshotMachine objects, returns this
6721 * object's pointer itself. For SessionMachine objects, returns the peer
6722 * (primary) machine pointer.
6723 */
6724Machine* Machine::getMachine()
6725{
6726 if (isSessionMachine())
6727 return (Machine*)mPeer;
6728 return this;
6729}
6730
6731/**
6732 * Makes sure that there are no machine state dependents. If necessary, waits
6733 * for the number of dependents to drop to zero.
6734 *
6735 * Make sure this method is called from under this object's write lock to
6736 * guarantee that no new dependents may be added when this method returns
6737 * control to the caller.
6738 *
6739 * @note Locks this object for writing. The lock will be released while waiting
6740 * (if necessary).
6741 *
6742 * @warning To be used only in methods that change the machine state!
6743 */
6744void Machine::ensureNoStateDependencies()
6745{
6746 AssertReturnVoid(isWriteLockOnCurrentThread());
6747
6748 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6749
6750 /* Wait for all state dependents if necessary */
6751 if (mData->mMachineStateDeps != 0)
6752 {
6753 /* lazy semaphore creation */
6754 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6755 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6756
6757 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6758 mData->mMachineStateDeps));
6759
6760 ++mData->mMachineStateChangePending;
6761
6762 /* reset the semaphore before waiting, the last dependent will signal
6763 * it */
6764 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6765
6766 alock.leave();
6767
6768 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6769
6770 alock.enter();
6771
6772 -- mData->mMachineStateChangePending;
6773 }
6774}
6775
6776/**
6777 * Changes the machine state and informs callbacks.
6778 *
6779 * This method is not intended to fail so it either returns S_OK or asserts (and
6780 * returns a failure).
6781 *
6782 * @note Locks this object for writing.
6783 */
6784HRESULT Machine::setMachineState(MachineState_T aMachineState)
6785{
6786 LogFlowThisFuncEnter();
6787 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6788
6789 AutoCaller autoCaller(this);
6790 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6791
6792 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6793
6794 /* wait for state dependents to drop to zero */
6795 ensureNoStateDependencies();
6796
6797 if (mData->mMachineState != aMachineState)
6798 {
6799 mData->mMachineState = aMachineState;
6800
6801 RTTimeNow(&mData->mLastStateChange);
6802
6803 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6804 }
6805
6806 LogFlowThisFuncLeave();
6807 return S_OK;
6808}
6809
6810/**
6811 * Searches for a shared folder with the given logical name
6812 * in the collection of shared folders.
6813 *
6814 * @param aName logical name of the shared folder
6815 * @param aSharedFolder where to return the found object
6816 * @param aSetError whether to set the error info if the folder is
6817 * not found
6818 * @return
6819 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6820 *
6821 * @note
6822 * must be called from under the object's lock!
6823 */
6824HRESULT Machine::findSharedFolder(CBSTR aName,
6825 ComObjPtr<SharedFolder> &aSharedFolder,
6826 bool aSetError /* = false */)
6827{
6828 bool found = false;
6829 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6830 !found && it != mHWData->mSharedFolders.end();
6831 ++it)
6832 {
6833 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6834 found = (*it)->getName() == aName;
6835 if (found)
6836 aSharedFolder = *it;
6837 }
6838
6839 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6840
6841 if (aSetError && !found)
6842 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6843
6844 return rc;
6845}
6846
6847/**
6848 * Initializes all machine instance data from the given settings structures
6849 * from XML. The exception is the machine UUID which needs special handling
6850 * depending on the caller's use case, so the caller needs to set that herself.
6851 *
6852 * This gets called in several contexts during machine initialization:
6853 *
6854 * -- When machine XML exists on disk already and needs to be loaded into memory,
6855 * for example, from registeredInit() to load all registered machines on
6856 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
6857 * attached to the machine should be part of some media registry already.
6858 *
6859 * -- During OVF import, when a machine config has been constructed from an
6860 * OVF file. In this case, puuidRegistry is set to the machine UUID to
6861 * ensure that the media listed as attachments in the config (which have
6862 * been imported from the OVF) receive the correct registry ID.
6863 *
6864 * @param config Machine settings from XML.
6865 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
6866 * @return
6867 */
6868HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
6869 const Guid *puuidRegistry)
6870{
6871 // copy name, description, OS type, teleporter, UTC etc.
6872 mUserData->s = config.machineUserData;
6873
6874 // look up the object by Id to check it is valid
6875 ComPtr<IGuestOSType> guestOSType;
6876 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
6877 guestOSType.asOutParam());
6878 if (FAILED(rc)) return rc;
6879
6880 // stateFile (optional)
6881 if (config.strStateFile.isEmpty())
6882 mSSData->mStateFilePath.setNull();
6883 else
6884 {
6885 Utf8Str stateFilePathFull(config.strStateFile);
6886 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6887 if (RT_FAILURE(vrc))
6888 return setError(E_FAIL,
6889 tr("Invalid saved state file path '%s' (%Rrc)"),
6890 config.strStateFile.c_str(),
6891 vrc);
6892 mSSData->mStateFilePath = stateFilePathFull;
6893 }
6894
6895 // snapshot folder needs special processing so set it again
6896 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
6897 if (FAILED(rc)) return rc;
6898
6899 /* currentStateModified (optional, default is true) */
6900 mData->mCurrentStateModified = config.fCurrentStateModified;
6901
6902 mData->mLastStateChange = config.timeLastStateChange;
6903
6904 /*
6905 * note: all mUserData members must be assigned prior this point because
6906 * we need to commit changes in order to let mUserData be shared by all
6907 * snapshot machine instances.
6908 */
6909 mUserData.commitCopy();
6910
6911 // machine registry, if present (must be loaded before snapshots)
6912 if (config.canHaveOwnMediaRegistry())
6913 {
6914 // determine machine folder
6915 Utf8Str strMachineFolder = getSettingsFileFull();
6916 strMachineFolder.stripFilename();
6917 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
6918 config.mediaRegistry,
6919 strMachineFolder);
6920 if (FAILED(rc)) return rc;
6921 }
6922
6923 /* Snapshot node (optional) */
6924 size_t cRootSnapshots;
6925 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6926 {
6927 // there must be only one root snapshot
6928 Assert(cRootSnapshots == 1);
6929
6930 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6931
6932 rc = loadSnapshot(snap,
6933 config.uuidCurrentSnapshot,
6934 NULL); // no parent == first snapshot
6935 if (FAILED(rc)) return rc;
6936 }
6937
6938 // hardware data
6939 rc = loadHardware(config.hardwareMachine);
6940 if (FAILED(rc)) return rc;
6941
6942 // load storage controllers
6943 rc = loadStorageControllers(config.storageMachine,
6944 puuidRegistry,
6945 NULL /* puuidSnapshot */);
6946 if (FAILED(rc)) return rc;
6947
6948 /*
6949 * NOTE: the assignment below must be the last thing to do,
6950 * otherwise it will be not possible to change the settings
6951 * somewhere in the code above because all setters will be
6952 * blocked by checkStateDependency(MutableStateDep).
6953 */
6954
6955 /* set the machine state to Aborted or Saved when appropriate */
6956 if (config.fAborted)
6957 {
6958 Assert(!mSSData->mStateFilePath.isEmpty());
6959 mSSData->mStateFilePath.setNull();
6960
6961 /* no need to use setMachineState() during init() */
6962 mData->mMachineState = MachineState_Aborted;
6963 }
6964 else if (!mSSData->mStateFilePath.isEmpty())
6965 {
6966 /* no need to use setMachineState() during init() */
6967 mData->mMachineState = MachineState_Saved;
6968 }
6969
6970 // after loading settings, we are no longer different from the XML on disk
6971 mData->flModifications = 0;
6972
6973 return S_OK;
6974}
6975
6976/**
6977 * Recursively loads all snapshots starting from the given.
6978 *
6979 * @param aNode <Snapshot> node.
6980 * @param aCurSnapshotId Current snapshot ID from the settings file.
6981 * @param aParentSnapshot Parent snapshot.
6982 */
6983HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6984 const Guid &aCurSnapshotId,
6985 Snapshot *aParentSnapshot)
6986{
6987 AssertReturn(!isSnapshotMachine(), E_FAIL);
6988 AssertReturn(!isSessionMachine(), E_FAIL);
6989
6990 HRESULT rc = S_OK;
6991
6992 Utf8Str strStateFile;
6993 if (!data.strStateFile.isEmpty())
6994 {
6995 /* optional */
6996 strStateFile = data.strStateFile;
6997 int vrc = calculateFullPath(strStateFile, strStateFile);
6998 if (RT_FAILURE(vrc))
6999 return setError(E_FAIL,
7000 tr("Invalid saved state file path '%s' (%Rrc)"),
7001 strStateFile.c_str(),
7002 vrc);
7003 }
7004
7005 /* create a snapshot machine object */
7006 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7007 pSnapshotMachine.createObject();
7008 rc = pSnapshotMachine->init(this,
7009 data.hardware,
7010 data.storage,
7011 data.uuid.ref(),
7012 strStateFile);
7013 if (FAILED(rc)) return rc;
7014
7015 /* create a snapshot object */
7016 ComObjPtr<Snapshot> pSnapshot;
7017 pSnapshot.createObject();
7018 /* initialize the snapshot */
7019 rc = pSnapshot->init(mParent, // VirtualBox object
7020 data.uuid,
7021 data.strName,
7022 data.strDescription,
7023 data.timestamp,
7024 pSnapshotMachine,
7025 aParentSnapshot);
7026 if (FAILED(rc)) return rc;
7027
7028 /* memorize the first snapshot if necessary */
7029 if (!mData->mFirstSnapshot)
7030 mData->mFirstSnapshot = pSnapshot;
7031
7032 /* memorize the current snapshot when appropriate */
7033 if ( !mData->mCurrentSnapshot
7034 && pSnapshot->getId() == aCurSnapshotId
7035 )
7036 mData->mCurrentSnapshot = pSnapshot;
7037
7038 // now create the children
7039 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7040 it != data.llChildSnapshots.end();
7041 ++it)
7042 {
7043 const settings::Snapshot &childData = *it;
7044 // recurse
7045 rc = loadSnapshot(childData,
7046 aCurSnapshotId,
7047 pSnapshot); // parent = the one we created above
7048 if (FAILED(rc)) return rc;
7049 }
7050
7051 return rc;
7052}
7053
7054/**
7055 * @param aNode <Hardware> node.
7056 */
7057HRESULT Machine::loadHardware(const settings::Hardware &data)
7058{
7059 AssertReturn(!isSessionMachine(), E_FAIL);
7060
7061 HRESULT rc = S_OK;
7062
7063 try
7064 {
7065 /* The hardware version attribute (optional). */
7066 mHWData->mHWVersion = data.strVersion;
7067 mHWData->mHardwareUUID = data.uuid;
7068
7069 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7070 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7071 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7072 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7073 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7074 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7075 mHWData->mPAEEnabled = data.fPAE;
7076 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7077
7078 mHWData->mCPUCount = data.cCPUs;
7079 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7080 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7081
7082 // cpu
7083 if (mHWData->mCPUHotPlugEnabled)
7084 {
7085 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7086 it != data.llCpus.end();
7087 ++it)
7088 {
7089 const settings::Cpu &cpu = *it;
7090
7091 mHWData->mCPUAttached[cpu.ulId] = true;
7092 }
7093 }
7094
7095 // cpuid leafs
7096 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7097 it != data.llCpuIdLeafs.end();
7098 ++it)
7099 {
7100 const settings::CpuIdLeaf &leaf = *it;
7101
7102 switch (leaf.ulId)
7103 {
7104 case 0x0:
7105 case 0x1:
7106 case 0x2:
7107 case 0x3:
7108 case 0x4:
7109 case 0x5:
7110 case 0x6:
7111 case 0x7:
7112 case 0x8:
7113 case 0x9:
7114 case 0xA:
7115 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7116 break;
7117
7118 case 0x80000000:
7119 case 0x80000001:
7120 case 0x80000002:
7121 case 0x80000003:
7122 case 0x80000004:
7123 case 0x80000005:
7124 case 0x80000006:
7125 case 0x80000007:
7126 case 0x80000008:
7127 case 0x80000009:
7128 case 0x8000000A:
7129 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7130 break;
7131
7132 default:
7133 /* just ignore */
7134 break;
7135 }
7136 }
7137
7138 mHWData->mMemorySize = data.ulMemorySizeMB;
7139 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7140
7141 // boot order
7142 for (size_t i = 0;
7143 i < RT_ELEMENTS(mHWData->mBootOrder);
7144 i++)
7145 {
7146 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7147 if (it == data.mapBootOrder.end())
7148 mHWData->mBootOrder[i] = DeviceType_Null;
7149 else
7150 mHWData->mBootOrder[i] = it->second;
7151 }
7152
7153 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7154 mHWData->mMonitorCount = data.cMonitors;
7155 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7156 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7157 mHWData->mFirmwareType = data.firmwareType;
7158 mHWData->mPointingHidType = data.pointingHidType;
7159 mHWData->mKeyboardHidType = data.keyboardHidType;
7160 mHWData->mChipsetType = data.chipsetType;
7161 mHWData->mHpetEnabled = data.fHpetEnabled;
7162
7163 /* VRDEServer */
7164 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7165 if (FAILED(rc)) return rc;
7166
7167 /* BIOS */
7168 rc = mBIOSSettings->loadSettings(data.biosSettings);
7169 if (FAILED(rc)) return rc;
7170
7171 /* USB Controller */
7172 rc = mUSBController->loadSettings(data.usbController);
7173 if (FAILED(rc)) return rc;
7174
7175 // network adapters
7176 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7177 it != data.llNetworkAdapters.end();
7178 ++it)
7179 {
7180 const settings::NetworkAdapter &nic = *it;
7181
7182 /* slot unicity is guaranteed by XML Schema */
7183 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7184 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7185 if (FAILED(rc)) return rc;
7186 }
7187
7188 // serial ports
7189 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7190 it != data.llSerialPorts.end();
7191 ++it)
7192 {
7193 const settings::SerialPort &s = *it;
7194
7195 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7196 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7197 if (FAILED(rc)) return rc;
7198 }
7199
7200 // parallel ports (optional)
7201 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7202 it != data.llParallelPorts.end();
7203 ++it)
7204 {
7205 const settings::ParallelPort &p = *it;
7206
7207 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7208 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7209 if (FAILED(rc)) return rc;
7210 }
7211
7212 /* AudioAdapter */
7213 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7214 if (FAILED(rc)) return rc;
7215
7216 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7217 it != data.llSharedFolders.end();
7218 ++it)
7219 {
7220 const settings::SharedFolder &sf = *it;
7221 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7222 Bstr(sf.strHostPath).raw(),
7223 sf.fWritable, sf.fAutoMount);
7224 if (FAILED(rc)) return rc;
7225 }
7226
7227 // Clipboard
7228 mHWData->mClipboardMode = data.clipboardMode;
7229
7230 // guest settings
7231 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7232
7233 // IO settings
7234 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7235 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7236
7237#ifdef VBOX_WITH_GUEST_PROPS
7238 /* Guest properties (optional) */
7239 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7240 it != data.llGuestProperties.end();
7241 ++it)
7242 {
7243 const settings::GuestProperty &prop = *it;
7244 uint32_t fFlags = guestProp::NILFLAG;
7245 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7246 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7247 mHWData->mGuestProperties.push_back(property);
7248 }
7249
7250 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7251#endif /* VBOX_WITH_GUEST_PROPS defined */
7252 }
7253 catch(std::bad_alloc &)
7254 {
7255 return E_OUTOFMEMORY;
7256 }
7257
7258 AssertComRC(rc);
7259 return rc;
7260}
7261
7262/**
7263 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7264 *
7265 * @param data
7266 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7267 * @param puuidSnapshot
7268 * @return
7269 */
7270HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7271 const Guid *puuidRegistry,
7272 const Guid *puuidSnapshot)
7273{
7274 AssertReturn(!isSessionMachine(), E_FAIL);
7275
7276 HRESULT rc = S_OK;
7277
7278 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7279 it != data.llStorageControllers.end();
7280 ++it)
7281 {
7282 const settings::StorageController &ctlData = *it;
7283
7284 ComObjPtr<StorageController> pCtl;
7285 /* Try to find one with the name first. */
7286 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7287 if (SUCCEEDED(rc))
7288 return setError(VBOX_E_OBJECT_IN_USE,
7289 tr("Storage controller named '%s' already exists"),
7290 ctlData.strName.c_str());
7291
7292 pCtl.createObject();
7293 rc = pCtl->init(this,
7294 ctlData.strName,
7295 ctlData.storageBus,
7296 ctlData.ulInstance,
7297 ctlData.fBootable);
7298 if (FAILED(rc)) return rc;
7299
7300 mStorageControllers->push_back(pCtl);
7301
7302 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7303 if (FAILED(rc)) return rc;
7304
7305 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7306 if (FAILED(rc)) return rc;
7307
7308 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7309 if (FAILED(rc)) return rc;
7310
7311 /* Set IDE emulation settings (only for AHCI controller). */
7312 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7313 {
7314 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7315 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7316 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7317 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7318 )
7319 return rc;
7320 }
7321
7322 /* Load the attached devices now. */
7323 rc = loadStorageDevices(pCtl,
7324 ctlData,
7325 puuidRegistry,
7326 puuidSnapshot);
7327 if (FAILED(rc)) return rc;
7328 }
7329
7330 return S_OK;
7331}
7332
7333/**
7334 * Called from loadStorageControllers for a controller's devices.
7335 *
7336 * @param aStorageController
7337 * @param data
7338 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7339 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7340 * @return
7341 */
7342HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7343 const settings::StorageController &data,
7344 const Guid *puuidRegistry,
7345 const Guid *puuidSnapshot)
7346{
7347 HRESULT rc = S_OK;
7348
7349 /* paranoia: detect duplicate attachments */
7350 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7351 it != data.llAttachedDevices.end();
7352 ++it)
7353 {
7354 const settings::AttachedDevice &ad = *it;
7355
7356 for (settings::AttachedDevicesList::const_iterator it2 = it;
7357 it2 != data.llAttachedDevices.end();
7358 ++it2)
7359 {
7360 if (it == it2)
7361 continue;
7362
7363 const settings::AttachedDevice &ad2 = *it2;
7364
7365 if ( ad.lPort == ad2.lPort
7366 && ad.lDevice == ad2.lDevice)
7367 {
7368 return setError(E_FAIL,
7369 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7370 aStorageController->getName().c_str(),
7371 ad.lPort,
7372 ad.lDevice,
7373 mUserData->s.strName.c_str());
7374 }
7375 }
7376 }
7377
7378 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7379 it != data.llAttachedDevices.end();
7380 ++it)
7381 {
7382 const settings::AttachedDevice &dev = *it;
7383 ComObjPtr<Medium> medium;
7384
7385 switch (dev.deviceType)
7386 {
7387 case DeviceType_Floppy:
7388 case DeviceType_DVD:
7389 rc = mParent->findRemoveableMedium(dev.deviceType, dev.uuid, false /* fRefresh */, medium);
7390 if (FAILED(rc))
7391 return rc;
7392 break;
7393
7394 case DeviceType_HardDisk:
7395 {
7396 /* find a hard disk by UUID */
7397 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7398 if (FAILED(rc))
7399 {
7400 if (isSnapshotMachine())
7401 {
7402 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7403 // so the user knows that the bad disk is in a snapshot somewhere
7404 com::ErrorInfo info;
7405 return setError(E_FAIL,
7406 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7407 puuidSnapshot->raw(),
7408 info.getText().raw());
7409 }
7410 else
7411 return rc;
7412 }
7413
7414 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7415
7416 if (medium->getType() == MediumType_Immutable)
7417 {
7418 if (isSnapshotMachine())
7419 return setError(E_FAIL,
7420 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7421 "of the virtual machine '%s' ('%s')"),
7422 medium->getLocationFull().c_str(),
7423 dev.uuid.raw(),
7424 puuidSnapshot->raw(),
7425 mUserData->s.strName.c_str(),
7426 mData->m_strConfigFileFull.c_str());
7427
7428 return setError(E_FAIL,
7429 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7430 medium->getLocationFull().c_str(),
7431 dev.uuid.raw(),
7432 mUserData->s.strName.c_str(),
7433 mData->m_strConfigFileFull.c_str());
7434 }
7435
7436 if ( !isSnapshotMachine()
7437 && medium->getChildren().size() != 0
7438 )
7439 return setError(E_FAIL,
7440 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7441 "because it has %d differencing child hard disks"),
7442 medium->getLocationFull().c_str(),
7443 dev.uuid.raw(),
7444 mUserData->s.strName.c_str(),
7445 mData->m_strConfigFileFull.c_str(),
7446 medium->getChildren().size());
7447
7448 if (findAttachment(mMediaData->mAttachments,
7449 medium))
7450 return setError(E_FAIL,
7451 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7452 medium->getLocationFull().c_str(),
7453 dev.uuid.raw(),
7454 mUserData->s.strName.c_str(),
7455 mData->m_strConfigFileFull.c_str());
7456
7457 break;
7458 }
7459
7460 default:
7461 return setError(E_FAIL,
7462 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7463 medium->getLocationFull().c_str(),
7464 mUserData->s.strName.c_str(),
7465 mData->m_strConfigFileFull.c_str());
7466 }
7467
7468 if (FAILED(rc))
7469 break;
7470
7471 const Bstr controllerName = aStorageController->getName();
7472 ComObjPtr<MediumAttachment> pAttachment;
7473 pAttachment.createObject();
7474 rc = pAttachment->init(this,
7475 medium,
7476 controllerName,
7477 dev.lPort,
7478 dev.lDevice,
7479 dev.deviceType,
7480 dev.fPassThrough,
7481 dev.ulBandwidthLimit);
7482 if (FAILED(rc)) break;
7483
7484 /* associate the medium with this machine and snapshot */
7485 if (!medium.isNull())
7486 {
7487 if (isSnapshotMachine())
7488 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7489 else
7490 rc = medium->addBackReference(mData->mUuid);
7491
7492 if (puuidRegistry)
7493 // caller wants registry ID to be set on all attached media (OVF import case)
7494 medium->addRegistry(*puuidRegistry);
7495 }
7496
7497 if (FAILED(rc))
7498 break;
7499
7500 /* back up mMediaData to let registeredInit() properly rollback on failure
7501 * (= limited accessibility) */
7502 setModified(IsModified_Storage);
7503 mMediaData.backup();
7504 mMediaData->mAttachments.push_back(pAttachment);
7505 }
7506
7507 return rc;
7508}
7509
7510/**
7511 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7512 *
7513 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7514 * @param aSnapshot where to return the found snapshot
7515 * @param aSetError true to set extended error info on failure
7516 */
7517HRESULT Machine::findSnapshotById(const Guid &aId,
7518 ComObjPtr<Snapshot> &aSnapshot,
7519 bool aSetError /* = false */)
7520{
7521 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7522
7523 if (!mData->mFirstSnapshot)
7524 {
7525 if (aSetError)
7526 return setError(E_FAIL, tr("This machine does not have any snapshots"));
7527 return E_FAIL;
7528 }
7529
7530 if (aId.isEmpty())
7531 aSnapshot = mData->mFirstSnapshot;
7532 else
7533 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
7534
7535 if (!aSnapshot)
7536 {
7537 if (aSetError)
7538 return setError(E_FAIL,
7539 tr("Could not find a snapshot with UUID {%s}"),
7540 aId.toString().c_str());
7541 return E_FAIL;
7542 }
7543
7544 return S_OK;
7545}
7546
7547/**
7548 * Returns the snapshot with the given name or fails of no such snapshot.
7549 *
7550 * @param aName snapshot name to find
7551 * @param aSnapshot where to return the found snapshot
7552 * @param aSetError true to set extended error info on failure
7553 */
7554HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
7555 ComObjPtr<Snapshot> &aSnapshot,
7556 bool aSetError /* = false */)
7557{
7558 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
7559
7560 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7561
7562 if (!mData->mFirstSnapshot)
7563 {
7564 if (aSetError)
7565 return setError(VBOX_E_OBJECT_NOT_FOUND,
7566 tr("This machine does not have any snapshots"));
7567 return VBOX_E_OBJECT_NOT_FOUND;
7568 }
7569
7570 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
7571
7572 if (!aSnapshot)
7573 {
7574 if (aSetError)
7575 return setError(VBOX_E_OBJECT_NOT_FOUND,
7576 tr("Could not find a snapshot named '%s'"), strName.c_str());
7577 return VBOX_E_OBJECT_NOT_FOUND;
7578 }
7579
7580 return S_OK;
7581}
7582
7583/**
7584 * Returns a storage controller object with the given name.
7585 *
7586 * @param aName storage controller name to find
7587 * @param aStorageController where to return the found storage controller
7588 * @param aSetError true to set extended error info on failure
7589 */
7590HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7591 ComObjPtr<StorageController> &aStorageController,
7592 bool aSetError /* = false */)
7593{
7594 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7595
7596 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7597 it != mStorageControllers->end();
7598 ++it)
7599 {
7600 if ((*it)->getName() == aName)
7601 {
7602 aStorageController = (*it);
7603 return S_OK;
7604 }
7605 }
7606
7607 if (aSetError)
7608 return setError(VBOX_E_OBJECT_NOT_FOUND,
7609 tr("Could not find a storage controller named '%s'"),
7610 aName.c_str());
7611 return VBOX_E_OBJECT_NOT_FOUND;
7612}
7613
7614HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7615 MediaData::AttachmentList &atts)
7616{
7617 AutoCaller autoCaller(this);
7618 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7619
7620 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7621
7622 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7623 it != mMediaData->mAttachments.end();
7624 ++it)
7625 {
7626 const ComObjPtr<MediumAttachment> &pAtt = *it;
7627
7628 // should never happen, but deal with NULL pointers in the list.
7629 AssertStmt(!pAtt.isNull(), continue);
7630
7631 // getControllerName() needs caller+read lock
7632 AutoCaller autoAttCaller(pAtt);
7633 if (FAILED(autoAttCaller.rc()))
7634 {
7635 atts.clear();
7636 return autoAttCaller.rc();
7637 }
7638 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7639
7640 if (pAtt->getControllerName() == aName)
7641 atts.push_back(pAtt);
7642 }
7643
7644 return S_OK;
7645}
7646
7647/**
7648 * Helper for #saveSettings. Cares about renaming the settings directory and
7649 * file if the machine name was changed and about creating a new settings file
7650 * if this is a new machine.
7651 *
7652 * @note Must be never called directly but only from #saveSettings().
7653 */
7654HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7655{
7656 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7657
7658 HRESULT rc = S_OK;
7659
7660 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7661
7662 /* attempt to rename the settings file if machine name is changed */
7663 if ( mUserData->s.fNameSync
7664 && mUserData.isBackedUp()
7665 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7666 )
7667 {
7668 bool dirRenamed = false;
7669 bool fileRenamed = false;
7670
7671 Utf8Str configFile, newConfigFile;
7672 Utf8Str configDir, newConfigDir;
7673
7674 do
7675 {
7676 int vrc = VINF_SUCCESS;
7677
7678 Utf8Str name = mUserData.backedUpData()->s.strName;
7679 Utf8Str newName = mUserData->s.strName;
7680
7681 configFile = mData->m_strConfigFileFull;
7682
7683 /* first, rename the directory if it matches the machine name */
7684 configDir = configFile;
7685 configDir.stripFilename();
7686 newConfigDir = configDir;
7687 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7688 {
7689 newConfigDir.stripFilename();
7690 newConfigDir.append(RTPATH_DELIMITER);
7691 newConfigDir.append(newName);
7692 /* new dir and old dir cannot be equal here because of 'if'
7693 * above and because name != newName */
7694 Assert(configDir != newConfigDir);
7695 if (!fSettingsFileIsNew)
7696 {
7697 /* perform real rename only if the machine is not new */
7698 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7699 if (RT_FAILURE(vrc))
7700 {
7701 rc = setError(E_FAIL,
7702 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7703 configDir.c_str(),
7704 newConfigDir.c_str(),
7705 vrc);
7706 break;
7707 }
7708 dirRenamed = true;
7709 }
7710 }
7711
7712 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
7713 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7714
7715 /* then try to rename the settings file itself */
7716 if (newConfigFile != configFile)
7717 {
7718 /* get the path to old settings file in renamed directory */
7719 configFile = Utf8StrFmt("%s%c%s",
7720 newConfigDir.c_str(),
7721 RTPATH_DELIMITER,
7722 RTPathFilename(configFile.c_str()));
7723 if (!fSettingsFileIsNew)
7724 {
7725 /* perform real rename only if the machine is not new */
7726 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7727 if (RT_FAILURE(vrc))
7728 {
7729 rc = setError(E_FAIL,
7730 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7731 configFile.c_str(),
7732 newConfigFile.c_str(),
7733 vrc);
7734 break;
7735 }
7736 fileRenamed = true;
7737 }
7738 }
7739
7740 // update m_strConfigFileFull amd mConfigFile
7741 mData->m_strConfigFileFull = newConfigFile;
7742 // compute the relative path too
7743 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7744
7745 // store the old and new so that VirtualBox::saveSettings() can update
7746 // the media registry
7747 if ( mData->mRegistered
7748 && configDir != newConfigDir)
7749 {
7750 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7751
7752 if (pfNeedsGlobalSaveSettings)
7753 *pfNeedsGlobalSaveSettings = true;
7754 }
7755
7756 /* update the saved state file path */
7757 Utf8Str path = mSSData->mStateFilePath;
7758 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7759 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
7760 newConfigDir.c_str(),
7761 path.c_str() + configDir.length());
7762
7763 /* Update saved state file paths of all online snapshots.
7764 * Note that saveSettings() will recognize name change
7765 * and will save all snapshots in this case. */
7766 if (mData->mFirstSnapshot)
7767 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7768 newConfigDir.c_str());
7769 }
7770 while (0);
7771
7772 if (FAILED(rc))
7773 {
7774 /* silently try to rename everything back */
7775 if (fileRenamed)
7776 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
7777 if (dirRenamed)
7778 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
7779 }
7780
7781 if (FAILED(rc)) return rc;
7782 }
7783
7784 if (fSettingsFileIsNew)
7785 {
7786 /* create a virgin config file */
7787 int vrc = VINF_SUCCESS;
7788
7789 /* ensure the settings directory exists */
7790 Utf8Str path(mData->m_strConfigFileFull);
7791 path.stripFilename();
7792 if (!RTDirExists(path.c_str()))
7793 {
7794 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7795 if (RT_FAILURE(vrc))
7796 {
7797 return setError(E_FAIL,
7798 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7799 path.c_str(),
7800 vrc);
7801 }
7802 }
7803
7804 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7805 path = Utf8Str(mData->m_strConfigFileFull);
7806 RTFILE f = NIL_RTFILE;
7807 vrc = RTFileOpen(&f, path.c_str(),
7808 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7809 if (RT_FAILURE(vrc))
7810 return setError(E_FAIL,
7811 tr("Could not create the settings file '%s' (%Rrc)"),
7812 path.c_str(),
7813 vrc);
7814 RTFileClose(f);
7815 }
7816
7817 return rc;
7818}
7819
7820/**
7821 * Saves and commits machine data, user data and hardware data.
7822 *
7823 * Note that on failure, the data remains uncommitted.
7824 *
7825 * @a aFlags may combine the following flags:
7826 *
7827 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7828 * Used when saving settings after an operation that makes them 100%
7829 * correspond to the settings from the current snapshot.
7830 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7831 * #isReallyModified() returns false. This is necessary for cases when we
7832 * change machine data directly, not through the backup()/commit() mechanism.
7833 * - SaveS_Force: settings will be saved without doing a deep compare of the
7834 * settings structures. This is used when this is called because snapshots
7835 * have changed to avoid the overhead of the deep compare.
7836 *
7837 * @note Must be called from under this object's write lock. Locks children for
7838 * writing.
7839 *
7840 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7841 * initialized to false and that will be set to true by this function if
7842 * the caller must invoke VirtualBox::saveSettings() because the global
7843 * settings have changed. This will happen if a machine rename has been
7844 * saved and the global machine and media registries will therefore need
7845 * updating.
7846 */
7847HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7848 int aFlags /*= 0*/)
7849{
7850 LogFlowThisFuncEnter();
7851
7852 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7853
7854 /* make sure child objects are unable to modify the settings while we are
7855 * saving them */
7856 ensureNoStateDependencies();
7857
7858 AssertReturn(!isSnapshotMachine(),
7859 E_FAIL);
7860
7861 HRESULT rc = S_OK;
7862 bool fNeedsWrite = false;
7863
7864 /* First, prepare to save settings. It will care about renaming the
7865 * settings directory and file if the machine name was changed and about
7866 * creating a new settings file if this is a new machine. */
7867 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7868 if (FAILED(rc)) return rc;
7869
7870 // keep a pointer to the current settings structures
7871 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7872 settings::MachineConfigFile *pNewConfig = NULL;
7873
7874 try
7875 {
7876 // make a fresh one to have everyone write stuff into
7877 pNewConfig = new settings::MachineConfigFile(NULL);
7878 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7879
7880 // now go and copy all the settings data from COM to the settings structures
7881 // (this calles saveSettings() on all the COM objects in the machine)
7882 copyMachineDataToSettings(*pNewConfig);
7883
7884 if (aFlags & SaveS_ResetCurStateModified)
7885 {
7886 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7887 mData->mCurrentStateModified = FALSE;
7888 fNeedsWrite = true; // always, no need to compare
7889 }
7890 else if (aFlags & SaveS_Force)
7891 {
7892 fNeedsWrite = true; // always, no need to compare
7893 }
7894 else
7895 {
7896 if (!mData->mCurrentStateModified)
7897 {
7898 // do a deep compare of the settings that we just saved with the settings
7899 // previously stored in the config file; this invokes MachineConfigFile::operator==
7900 // which does a deep compare of all the settings, which is expensive but less expensive
7901 // than writing out XML in vain
7902 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7903
7904 // could still be modified if any settings changed
7905 mData->mCurrentStateModified = fAnySettingsChanged;
7906
7907 fNeedsWrite = fAnySettingsChanged;
7908 }
7909 else
7910 fNeedsWrite = true;
7911 }
7912
7913 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7914
7915 if (fNeedsWrite)
7916 // now spit it all out!
7917 pNewConfig->write(mData->m_strConfigFileFull);
7918
7919 mData->pMachineConfigFile = pNewConfig;
7920 delete pOldConfig;
7921 commit();
7922
7923 // after saving settings, we are no longer different from the XML on disk
7924 mData->flModifications = 0;
7925 }
7926 catch (HRESULT err)
7927 {
7928 // we assume that error info is set by the thrower
7929 rc = err;
7930
7931 // restore old config
7932 delete pNewConfig;
7933 mData->pMachineConfigFile = pOldConfig;
7934 }
7935 catch (...)
7936 {
7937 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7938 }
7939
7940 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7941 {
7942 /* Fire the data change event, even on failure (since we've already
7943 * committed all data). This is done only for SessionMachines because
7944 * mutable Machine instances are always not registered (i.e. private
7945 * to the client process that creates them) and thus don't need to
7946 * inform callbacks. */
7947 if (isSessionMachine())
7948 mParent->onMachineDataChange(mData->mUuid);
7949 }
7950
7951 LogFlowThisFunc(("rc=%08X\n", rc));
7952 LogFlowThisFuncLeave();
7953 return rc;
7954}
7955
7956/**
7957 * Implementation for saving the machine settings into the given
7958 * settings::MachineConfigFile instance. This copies machine extradata
7959 * from the previous machine config file in the instance data, if any.
7960 *
7961 * This gets called from two locations:
7962 *
7963 * -- Machine::saveSettings(), during the regular XML writing;
7964 *
7965 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7966 * exported to OVF and we write the VirtualBox proprietary XML
7967 * into a <vbox:Machine> tag.
7968 *
7969 * This routine fills all the fields in there, including snapshots, *except*
7970 * for the following:
7971 *
7972 * -- fCurrentStateModified. There is some special logic associated with that.
7973 *
7974 * The caller can then call MachineConfigFile::write() or do something else
7975 * with it.
7976 *
7977 * Caller must hold the machine lock!
7978 *
7979 * This throws XML errors and HRESULT, so the caller must have a catch block!
7980 */
7981void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7982{
7983 // deep copy extradata
7984 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7985
7986 config.uuid = mData->mUuid;
7987
7988 // copy name, description, OS type, teleport, UTC etc.
7989 config.machineUserData = mUserData->s;
7990
7991 if ( mData->mMachineState == MachineState_Saved
7992 || mData->mMachineState == MachineState_Restoring
7993 // when deleting a snapshot we may or may not have a saved state in the current state,
7994 // so let's not assert here please
7995 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7996 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7997 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7998 && (!mSSData->mStateFilePath.isEmpty())
7999 )
8000 )
8001 {
8002 Assert(!mSSData->mStateFilePath.isEmpty());
8003 /* try to make the file name relative to the settings file dir */
8004 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
8005 }
8006 else
8007 {
8008 Assert(mSSData->mStateFilePath.isEmpty());
8009 config.strStateFile.setNull();
8010 }
8011
8012 if (mData->mCurrentSnapshot)
8013 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8014 else
8015 config.uuidCurrentSnapshot.clear();
8016
8017 config.timeLastStateChange = mData->mLastStateChange;
8018 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8019 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8020
8021 HRESULT rc = saveHardware(config.hardwareMachine);
8022 if (FAILED(rc)) throw rc;
8023
8024 rc = saveStorageControllers(config.storageMachine);
8025 if (FAILED(rc)) throw rc;
8026
8027 // save machine's media registry if this is VirtualBox 4.0 or later
8028 if (config.canHaveOwnMediaRegistry())
8029 {
8030 // determine machine folder
8031 Utf8Str strMachineFolder = getSettingsFileFull();
8032 strMachineFolder.stripFilename();
8033 mParent->saveMediaRegistry(config.mediaRegistry,
8034 getId(), // only media with registry ID == machine UUID
8035 strMachineFolder);
8036 // this throws HRESULT
8037 }
8038
8039 // save snapshots
8040 rc = saveAllSnapshots(config);
8041 if (FAILED(rc)) throw rc;
8042}
8043
8044/**
8045 * Saves all snapshots of the machine into the given machine config file. Called
8046 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8047 * @param config
8048 * @return
8049 */
8050HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8051{
8052 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8053
8054 HRESULT rc = S_OK;
8055
8056 try
8057 {
8058 config.llFirstSnapshot.clear();
8059
8060 if (mData->mFirstSnapshot)
8061 {
8062 settings::Snapshot snapNew;
8063 config.llFirstSnapshot.push_back(snapNew);
8064
8065 // get reference to the fresh copy of the snapshot on the list and
8066 // work on that copy directly to avoid excessive copying later
8067 settings::Snapshot &snap = config.llFirstSnapshot.front();
8068
8069 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8070 if (FAILED(rc)) throw rc;
8071 }
8072
8073// if (mType == IsSessionMachine)
8074// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8075
8076 }
8077 catch (HRESULT err)
8078 {
8079 /* we assume that error info is set by the thrower */
8080 rc = err;
8081 }
8082 catch (...)
8083 {
8084 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8085 }
8086
8087 return rc;
8088}
8089
8090/**
8091 * Saves the VM hardware configuration. It is assumed that the
8092 * given node is empty.
8093 *
8094 * @param aNode <Hardware> node to save the VM hardware configuration to.
8095 */
8096HRESULT Machine::saveHardware(settings::Hardware &data)
8097{
8098 HRESULT rc = S_OK;
8099
8100 try
8101 {
8102 /* The hardware version attribute (optional).
8103 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8104 if ( mHWData->mHWVersion == "1"
8105 && mSSData->mStateFilePath.isEmpty()
8106 )
8107 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. */
8108
8109 data.strVersion = mHWData->mHWVersion;
8110 data.uuid = mHWData->mHardwareUUID;
8111
8112 // CPU
8113 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8114 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8115 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8116 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8117 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8118 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8119 data.fPAE = !!mHWData->mPAEEnabled;
8120 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8121
8122 /* Standard and Extended CPUID leafs. */
8123 data.llCpuIdLeafs.clear();
8124 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8125 {
8126 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8127 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8128 }
8129 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8130 {
8131 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8132 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8133 }
8134
8135 data.cCPUs = mHWData->mCPUCount;
8136 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8137 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8138
8139 data.llCpus.clear();
8140 if (data.fCpuHotPlug)
8141 {
8142 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8143 {
8144 if (mHWData->mCPUAttached[idx])
8145 {
8146 settings::Cpu cpu;
8147 cpu.ulId = idx;
8148 data.llCpus.push_back(cpu);
8149 }
8150 }
8151 }
8152
8153 // memory
8154 data.ulMemorySizeMB = mHWData->mMemorySize;
8155 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8156
8157 // firmware
8158 data.firmwareType = mHWData->mFirmwareType;
8159
8160 // HID
8161 data.pointingHidType = mHWData->mPointingHidType;
8162 data.keyboardHidType = mHWData->mKeyboardHidType;
8163
8164 // chipset
8165 data.chipsetType = mHWData->mChipsetType;
8166
8167 // HPET
8168 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8169
8170 // boot order
8171 data.mapBootOrder.clear();
8172 for (size_t i = 0;
8173 i < RT_ELEMENTS(mHWData->mBootOrder);
8174 ++i)
8175 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8176
8177 // display
8178 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8179 data.cMonitors = mHWData->mMonitorCount;
8180 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8181 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8182
8183 /* VRDEServer settings (optional) */
8184 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8185 if (FAILED(rc)) throw rc;
8186
8187 /* BIOS (required) */
8188 rc = mBIOSSettings->saveSettings(data.biosSettings);
8189 if (FAILED(rc)) throw rc;
8190
8191 /* USB Controller (required) */
8192 rc = mUSBController->saveSettings(data.usbController);
8193 if (FAILED(rc)) throw rc;
8194
8195 /* Network adapters (required) */
8196 data.llNetworkAdapters.clear();
8197 for (ULONG slot = 0;
8198 slot < RT_ELEMENTS(mNetworkAdapters);
8199 ++slot)
8200 {
8201 settings::NetworkAdapter nic;
8202 nic.ulSlot = slot;
8203 rc = mNetworkAdapters[slot]->saveSettings(nic);
8204 if (FAILED(rc)) throw rc;
8205
8206 data.llNetworkAdapters.push_back(nic);
8207 }
8208
8209 /* Serial ports */
8210 data.llSerialPorts.clear();
8211 for (ULONG slot = 0;
8212 slot < RT_ELEMENTS(mSerialPorts);
8213 ++slot)
8214 {
8215 settings::SerialPort s;
8216 s.ulSlot = slot;
8217 rc = mSerialPorts[slot]->saveSettings(s);
8218 if (FAILED(rc)) return rc;
8219
8220 data.llSerialPorts.push_back(s);
8221 }
8222
8223 /* Parallel ports */
8224 data.llParallelPorts.clear();
8225 for (ULONG slot = 0;
8226 slot < RT_ELEMENTS(mParallelPorts);
8227 ++slot)
8228 {
8229 settings::ParallelPort p;
8230 p.ulSlot = slot;
8231 rc = mParallelPorts[slot]->saveSettings(p);
8232 if (FAILED(rc)) return rc;
8233
8234 data.llParallelPorts.push_back(p);
8235 }
8236
8237 /* Audio adapter */
8238 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8239 if (FAILED(rc)) return rc;
8240
8241 /* Shared folders */
8242 data.llSharedFolders.clear();
8243 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8244 it != mHWData->mSharedFolders.end();
8245 ++it)
8246 {
8247 ComObjPtr<SharedFolder> pFolder = *it;
8248 settings::SharedFolder sf;
8249 sf.strName = pFolder->getName();
8250 sf.strHostPath = pFolder->getHostPath();
8251 sf.fWritable = !!pFolder->isWritable();
8252 sf.fAutoMount = !!pFolder->isAutoMounted();
8253
8254 data.llSharedFolders.push_back(sf);
8255 }
8256
8257 // clipboard
8258 data.clipboardMode = mHWData->mClipboardMode;
8259
8260 /* Guest */
8261 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8262
8263 // IO settings
8264 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8265 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8266
8267 // guest properties
8268 data.llGuestProperties.clear();
8269#ifdef VBOX_WITH_GUEST_PROPS
8270 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8271 it != mHWData->mGuestProperties.end();
8272 ++it)
8273 {
8274 HWData::GuestProperty property = *it;
8275
8276 /* Remove transient guest properties at shutdown unless we
8277 * are saving state */
8278 if ( ( mData->mMachineState == MachineState_PoweredOff
8279 || mData->mMachineState == MachineState_Aborted
8280 || mData->mMachineState == MachineState_Teleported)
8281 && property.mFlags & guestProp::TRANSIENT)
8282 continue;
8283 settings::GuestProperty prop;
8284 prop.strName = property.strName;
8285 prop.strValue = property.strValue;
8286 prop.timestamp = property.mTimestamp;
8287 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8288 guestProp::writeFlags(property.mFlags, szFlags);
8289 prop.strFlags = szFlags;
8290
8291 data.llGuestProperties.push_back(prop);
8292 }
8293
8294 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8295 /* I presume this doesn't require a backup(). */
8296 mData->mGuestPropertiesModified = FALSE;
8297#endif /* VBOX_WITH_GUEST_PROPS defined */
8298 }
8299 catch(std::bad_alloc &)
8300 {
8301 return E_OUTOFMEMORY;
8302 }
8303
8304 AssertComRC(rc);
8305 return rc;
8306}
8307
8308/**
8309 * Saves the storage controller configuration.
8310 *
8311 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8312 */
8313HRESULT Machine::saveStorageControllers(settings::Storage &data)
8314{
8315 data.llStorageControllers.clear();
8316
8317 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8318 it != mStorageControllers->end();
8319 ++it)
8320 {
8321 HRESULT rc;
8322 ComObjPtr<StorageController> pCtl = *it;
8323
8324 settings::StorageController ctl;
8325 ctl.strName = pCtl->getName();
8326 ctl.controllerType = pCtl->getControllerType();
8327 ctl.storageBus = pCtl->getStorageBus();
8328 ctl.ulInstance = pCtl->getInstance();
8329 ctl.fBootable = pCtl->getBootable();
8330
8331 /* Save the port count. */
8332 ULONG portCount;
8333 rc = pCtl->COMGETTER(PortCount)(&portCount);
8334 ComAssertComRCRet(rc, rc);
8335 ctl.ulPortCount = portCount;
8336
8337 /* Save fUseHostIOCache */
8338 BOOL fUseHostIOCache;
8339 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8340 ComAssertComRCRet(rc, rc);
8341 ctl.fUseHostIOCache = !!fUseHostIOCache;
8342
8343 /* Save IDE emulation settings. */
8344 if (ctl.controllerType == StorageControllerType_IntelAhci)
8345 {
8346 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8347 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8348 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8349 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8350 )
8351 ComAssertComRCRet(rc, rc);
8352 }
8353
8354 /* save the devices now. */
8355 rc = saveStorageDevices(pCtl, ctl);
8356 ComAssertComRCRet(rc, rc);
8357
8358 data.llStorageControllers.push_back(ctl);
8359 }
8360
8361 return S_OK;
8362}
8363
8364/**
8365 * Saves the hard disk configuration.
8366 */
8367HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8368 settings::StorageController &data)
8369{
8370 MediaData::AttachmentList atts;
8371
8372 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8373 if (FAILED(rc)) return rc;
8374
8375 data.llAttachedDevices.clear();
8376 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8377 it != atts.end();
8378 ++it)
8379 {
8380 settings::AttachedDevice dev;
8381
8382 MediumAttachment *pAttach = *it;
8383 Medium *pMedium = pAttach->getMedium();
8384
8385 dev.deviceType = pAttach->getType();
8386 dev.lPort = pAttach->getPort();
8387 dev.lDevice = pAttach->getDevice();
8388 if (pMedium)
8389 {
8390 if (pMedium->isHostDrive())
8391 dev.strHostDriveSrc = pMedium->getLocationFull();
8392 else
8393 dev.uuid = pMedium->getId();
8394 dev.fPassThrough = pAttach->getPassthrough();
8395 }
8396
8397 data.llAttachedDevices.push_back(dev);
8398 }
8399
8400 return S_OK;
8401}
8402
8403/**
8404 * Saves machine state settings as defined by aFlags
8405 * (SaveSTS_* values).
8406 *
8407 * @param aFlags Combination of SaveSTS_* flags.
8408 *
8409 * @note Locks objects for writing.
8410 */
8411HRESULT Machine::saveStateSettings(int aFlags)
8412{
8413 if (aFlags == 0)
8414 return S_OK;
8415
8416 AutoCaller autoCaller(this);
8417 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8418
8419 /* This object's write lock is also necessary to serialize file access
8420 * (prevent concurrent reads and writes) */
8421 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8422
8423 HRESULT rc = S_OK;
8424
8425 Assert(mData->pMachineConfigFile);
8426
8427 try
8428 {
8429 if (aFlags & SaveSTS_CurStateModified)
8430 mData->pMachineConfigFile->fCurrentStateModified = true;
8431
8432 if (aFlags & SaveSTS_StateFilePath)
8433 {
8434 if (!mSSData->mStateFilePath.isEmpty())
8435 /* try to make the file name relative to the settings file dir */
8436 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8437 else
8438 mData->pMachineConfigFile->strStateFile.setNull();
8439 }
8440
8441 if (aFlags & SaveSTS_StateTimeStamp)
8442 {
8443 Assert( mData->mMachineState != MachineState_Aborted
8444 || mSSData->mStateFilePath.isEmpty());
8445
8446 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8447
8448 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8449//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8450 }
8451
8452 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8453 }
8454 catch (...)
8455 {
8456 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8457 }
8458
8459 return rc;
8460}
8461
8462/**
8463 * Creates differencing hard disks for all normal hard disks attached to this
8464 * machine and a new set of attachments to refer to created disks.
8465 *
8466 * Used when taking a snapshot or when deleting the current state. Gets called
8467 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8468 *
8469 * This method assumes that mMediaData contains the original hard disk attachments
8470 * it needs to create diffs for. On success, these attachments will be replaced
8471 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8472 * called to delete created diffs which will also rollback mMediaData and restore
8473 * whatever was backed up before calling this method.
8474 *
8475 * Attachments with non-normal hard disks are left as is.
8476 *
8477 * If @a aOnline is @c false then the original hard disks that require implicit
8478 * diffs will be locked for reading. Otherwise it is assumed that they are
8479 * already locked for writing (when the VM was started). Note that in the latter
8480 * case it is responsibility of the caller to lock the newly created diffs for
8481 * writing if this method succeeds.
8482 *
8483 * @param aProgress Progress object to run (must contain at least as
8484 * many operations left as the number of hard disks
8485 * attached).
8486 * @param aOnline Whether the VM was online prior to this operation.
8487 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
8488 *
8489 * @note The progress object is not marked as completed, neither on success nor
8490 * on failure. This is a responsibility of the caller.
8491 *
8492 * @note Locks this object for writing.
8493 */
8494HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8495 ULONG aWeight,
8496 bool aOnline,
8497 GuidList *pllRegistriesThatNeedSaving)
8498{
8499 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8500
8501 AutoCaller autoCaller(this);
8502 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8503
8504 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8505
8506 /* must be in a protective state because we leave the lock below */
8507 AssertReturn( mData->mMachineState == MachineState_Saving
8508 || mData->mMachineState == MachineState_LiveSnapshotting
8509 || mData->mMachineState == MachineState_RestoringSnapshot
8510 || mData->mMachineState == MachineState_DeletingSnapshot
8511 , E_FAIL);
8512
8513 HRESULT rc = S_OK;
8514
8515 MediumLockListMap lockedMediaOffline;
8516 MediumLockListMap *lockedMediaMap;
8517 if (aOnline)
8518 lockedMediaMap = &mData->mSession.mLockedMedia;
8519 else
8520 lockedMediaMap = &lockedMediaOffline;
8521
8522 try
8523 {
8524 if (!aOnline)
8525 {
8526 /* lock all attached hard disks early to detect "in use"
8527 * situations before creating actual diffs */
8528 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8529 it != mMediaData->mAttachments.end();
8530 ++it)
8531 {
8532 MediumAttachment* pAtt = *it;
8533 if (pAtt->getType() == DeviceType_HardDisk)
8534 {
8535 Medium* pMedium = pAtt->getMedium();
8536 Assert(pMedium);
8537
8538 MediumLockList *pMediumLockList(new MediumLockList());
8539 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8540 false /* fMediumLockWrite */,
8541 NULL,
8542 *pMediumLockList);
8543 if (FAILED(rc))
8544 {
8545 delete pMediumLockList;
8546 throw rc;
8547 }
8548 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8549 if (FAILED(rc))
8550 {
8551 throw setError(rc,
8552 tr("Collecting locking information for all attached media failed"));
8553 }
8554 }
8555 }
8556
8557 /* Now lock all media. If this fails, nothing is locked. */
8558 rc = lockedMediaMap->Lock();
8559 if (FAILED(rc))
8560 {
8561 throw setError(rc,
8562 tr("Locking of attached media failed"));
8563 }
8564 }
8565
8566 /* remember the current list (note that we don't use backup() since
8567 * mMediaData may be already backed up) */
8568 MediaData::AttachmentList atts = mMediaData->mAttachments;
8569
8570 /* start from scratch */
8571 mMediaData->mAttachments.clear();
8572
8573 /* go through remembered attachments and create diffs for normal hard
8574 * disks and attach them */
8575 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8576 it != atts.end();
8577 ++it)
8578 {
8579 MediumAttachment* pAtt = *it;
8580
8581 DeviceType_T devType = pAtt->getType();
8582 Medium* pMedium = pAtt->getMedium();
8583
8584 if ( devType != DeviceType_HardDisk
8585 || pMedium == NULL
8586 || pMedium->getType() != MediumType_Normal)
8587 {
8588 /* copy the attachment as is */
8589
8590 /** @todo the progress object created in Console::TakeSnaphot
8591 * only expects operations for hard disks. Later other
8592 * device types need to show up in the progress as well. */
8593 if (devType == DeviceType_HardDisk)
8594 {
8595 if (pMedium == NULL)
8596 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
8597 aWeight); // weight
8598 else
8599 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8600 pMedium->getBase()->getName().c_str()).raw(),
8601 aWeight); // weight
8602 }
8603
8604 mMediaData->mAttachments.push_back(pAtt);
8605 continue;
8606 }
8607
8608 /* need a diff */
8609 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8610 pMedium->getBase()->getName().c_str()).raw(),
8611 aWeight); // weight
8612
8613 Utf8Str strFullSnapshotFolder;
8614 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
8615
8616 ComObjPtr<Medium> diff;
8617 diff.createObject();
8618 rc = diff->init(mParent,
8619 pMedium->getPreferredDiffFormat(),
8620 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
8621 pMedium->getFirstRegistryMachineId(), // store the diff in the same registry as the parent
8622 pllRegistriesThatNeedSaving);
8623 if (FAILED(rc)) throw rc;
8624
8625 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8626 * the push_back? Looks like we're going to leave medium with the
8627 * wrong kind of lock (general issue with if we fail anywhere at all)
8628 * and an orphaned VDI in the snapshots folder. */
8629
8630 /* update the appropriate lock list */
8631 MediumLockList *pMediumLockList;
8632 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8633 AssertComRCThrowRC(rc);
8634 if (aOnline)
8635 {
8636 rc = pMediumLockList->Update(pMedium, false);
8637 AssertComRCThrowRC(rc);
8638 }
8639
8640 /* leave the lock before the potentially lengthy operation */
8641 alock.leave();
8642 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8643 pMediumLockList,
8644 NULL /* aProgress */,
8645 true /* aWait */,
8646 pllRegistriesThatNeedSaving);
8647 alock.enter();
8648 if (FAILED(rc)) throw rc;
8649
8650 rc = lockedMediaMap->Unlock();
8651 AssertComRCThrowRC(rc);
8652 rc = pMediumLockList->Append(diff, true);
8653 AssertComRCThrowRC(rc);
8654 rc = lockedMediaMap->Lock();
8655 AssertComRCThrowRC(rc);
8656
8657 rc = diff->addBackReference(mData->mUuid);
8658 AssertComRCThrowRC(rc);
8659
8660 /* add a new attachment */
8661 ComObjPtr<MediumAttachment> attachment;
8662 attachment.createObject();
8663 rc = attachment->init(this,
8664 diff,
8665 pAtt->getControllerName(),
8666 pAtt->getPort(),
8667 pAtt->getDevice(),
8668 DeviceType_HardDisk,
8669 true /* aImplicit */,
8670 0 /* No bandwidth limit */);
8671 if (FAILED(rc)) throw rc;
8672
8673 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8674 AssertComRCThrowRC(rc);
8675 mMediaData->mAttachments.push_back(attachment);
8676 }
8677 }
8678 catch (HRESULT aRC) { rc = aRC; }
8679
8680 /* unlock all hard disks we locked */
8681 if (!aOnline)
8682 {
8683 ErrorInfoKeeper eik;
8684
8685 rc = lockedMediaMap->Clear();
8686 AssertComRC(rc);
8687 }
8688
8689 if (FAILED(rc))
8690 {
8691 MultiResult mrc = rc;
8692
8693 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
8694 }
8695
8696 return rc;
8697}
8698
8699/**
8700 * Deletes implicit differencing hard disks created either by
8701 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8702 *
8703 * Note that to delete hard disks created by #AttachMedium() this method is
8704 * called from #fixupMedia() when the changes are rolled back.
8705 *
8706 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8707 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8708 *
8709 * @note Locks this object for writing.
8710 */
8711HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
8712{
8713 AutoCaller autoCaller(this);
8714 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8715
8716 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8717 LogFlowThisFuncEnter();
8718
8719 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8720
8721 HRESULT rc = S_OK;
8722
8723 MediaData::AttachmentList implicitAtts;
8724
8725 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8726
8727 /* enumerate new attachments */
8728 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8729 it != mMediaData->mAttachments.end();
8730 ++it)
8731 {
8732 ComObjPtr<Medium> hd = (*it)->getMedium();
8733 if (hd.isNull())
8734 continue;
8735
8736 if ((*it)->isImplicit())
8737 {
8738 /* deassociate and mark for deletion */
8739 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8740 rc = hd->removeBackReference(mData->mUuid);
8741 AssertComRC(rc);
8742 implicitAtts.push_back(*it);
8743 continue;
8744 }
8745
8746 /* was this hard disk attached before? */
8747 if (!findAttachment(oldAtts, hd))
8748 {
8749 /* no: de-associate */
8750 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8751 rc = hd->removeBackReference(mData->mUuid);
8752 AssertComRC(rc);
8753 continue;
8754 }
8755 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8756 }
8757
8758 /* rollback hard disk changes */
8759 mMediaData.rollback();
8760
8761 MultiResult mrc(S_OK);
8762
8763 /* delete unused implicit diffs */
8764 if (implicitAtts.size() != 0)
8765 {
8766 /* will leave the lock before the potentially lengthy
8767 * operation, so protect with the special state (unless already
8768 * protected) */
8769 MachineState_T oldState = mData->mMachineState;
8770 if ( oldState != MachineState_Saving
8771 && oldState != MachineState_LiveSnapshotting
8772 && oldState != MachineState_RestoringSnapshot
8773 && oldState != MachineState_DeletingSnapshot
8774 && oldState != MachineState_DeletingSnapshotOnline
8775 && oldState != MachineState_DeletingSnapshotPaused
8776 )
8777 setMachineState(MachineState_SettingUp);
8778
8779 alock.leave();
8780
8781 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8782 it != implicitAtts.end();
8783 ++it)
8784 {
8785 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8786 ComObjPtr<Medium> hd = (*it)->getMedium();
8787
8788 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8789 pllRegistriesThatNeedSaving);
8790 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8791 mrc = rc;
8792 }
8793
8794 alock.enter();
8795
8796 if (mData->mMachineState == MachineState_SettingUp)
8797 setMachineState(oldState);
8798 }
8799
8800 return mrc;
8801}
8802
8803/**
8804 * Looks through the given list of media attachments for one with the given parameters
8805 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8806 * can be searched as well if needed.
8807 *
8808 * @param list
8809 * @param aControllerName
8810 * @param aControllerPort
8811 * @param aDevice
8812 * @return
8813 */
8814MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8815 IN_BSTR aControllerName,
8816 LONG aControllerPort,
8817 LONG aDevice)
8818{
8819 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8820 it != ll.end();
8821 ++it)
8822 {
8823 MediumAttachment *pAttach = *it;
8824 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8825 return pAttach;
8826 }
8827
8828 return NULL;
8829}
8830
8831/**
8832 * Looks through the given list of media attachments for one with the given parameters
8833 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8834 * can be searched as well if needed.
8835 *
8836 * @param list
8837 * @param aControllerName
8838 * @param aControllerPort
8839 * @param aDevice
8840 * @return
8841 */
8842MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8843 ComObjPtr<Medium> pMedium)
8844{
8845 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8846 it != ll.end();
8847 ++it)
8848 {
8849 MediumAttachment *pAttach = *it;
8850 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8851 if (pMediumThis == pMedium)
8852 return pAttach;
8853 }
8854
8855 return NULL;
8856}
8857
8858/**
8859 * Looks through the given list of media attachments for one with the given parameters
8860 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8861 * can be searched as well if needed.
8862 *
8863 * @param list
8864 * @param aControllerName
8865 * @param aControllerPort
8866 * @param aDevice
8867 * @return
8868 */
8869MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8870 Guid &id)
8871{
8872 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8873 it != ll.end();
8874 ++it)
8875 {
8876 MediumAttachment *pAttach = *it;
8877 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8878 if (pMediumThis->getId() == id)
8879 return pAttach;
8880 }
8881
8882 return NULL;
8883}
8884
8885/**
8886 * Main implementation for Machine::DetachDevice. This also gets called
8887 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8888 *
8889 * @param pAttach Medium attachment to detach.
8890 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8891 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8892 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8893 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8894 * @return
8895 */
8896HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8897 AutoWriteLock &writeLock,
8898 Snapshot *pSnapshot,
8899 GuidList *pllRegistriesThatNeedSaving)
8900{
8901 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8902 DeviceType_T mediumType = pAttach->getType();
8903
8904 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8905
8906 if (pAttach->isImplicit())
8907 {
8908 /* attempt to implicitly delete the implicitly created diff */
8909
8910 /// @todo move the implicit flag from MediumAttachment to Medium
8911 /// and forbid any hard disk operation when it is implicit. Or maybe
8912 /// a special media state for it to make it even more simple.
8913
8914 Assert(mMediaData.isBackedUp());
8915
8916 /* will leave the lock before the potentially lengthy operation, so
8917 * protect with the special state */
8918 MachineState_T oldState = mData->mMachineState;
8919 setMachineState(MachineState_SettingUp);
8920
8921 writeLock.release();
8922
8923 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8924 pllRegistriesThatNeedSaving);
8925
8926 writeLock.acquire();
8927
8928 setMachineState(oldState);
8929
8930 if (FAILED(rc)) return rc;
8931 }
8932
8933 setModified(IsModified_Storage);
8934 mMediaData.backup();
8935
8936 // we cannot use erase (it) below because backup() above will create
8937 // a copy of the list and make this copy active, but the iterator
8938 // still refers to the original and is not valid for the copy
8939 mMediaData->mAttachments.remove(pAttach);
8940
8941 if (!oldmedium.isNull())
8942 {
8943 // if this is from a snapshot, do not defer detachment to commitMedia()
8944 if (pSnapshot)
8945 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8946 // else if non-hard disk media, do not defer detachment to commitMedia() either
8947 else if (mediumType != DeviceType_HardDisk)
8948 oldmedium->removeBackReference(mData->mUuid);
8949 }
8950
8951 return S_OK;
8952}
8953
8954/**
8955 * Goes thru all medium attachments of the list and calls detachDevice() on each
8956 * of them and attaches all Medium objects found in the process to the given list,
8957 * depending on cleanupMode.
8958 *
8959 * This gets called from Machine::Unregister, both for the actual Machine and
8960 * the SnapshotMachine objects that might be found in the snapshots.
8961 *
8962 * Requires caller and locking.
8963 *
8964 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8965 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8966 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
8967 * otherwise no media get added.
8968 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
8969 * @return
8970 */
8971HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8972 Snapshot *pSnapshot,
8973 CleanupMode_T cleanupMode,
8974 MediaList &llMedia)
8975{
8976 Assert(isWriteLockOnCurrentThread());
8977
8978 HRESULT rc;
8979
8980 // make a temporary list because detachDevice invalidates iterators into
8981 // mMediaData->mAttachments
8982 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8983
8984 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8985 it != llAttachments2.end();
8986 ++it)
8987 {
8988 ComObjPtr<MediumAttachment> pAttach = *it;
8989 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8990
8991 if (!pMedium.isNull())
8992 {
8993 DeviceType_T devType = pMedium->getDeviceType();
8994 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
8995 && devType == DeviceType_HardDisk)
8996 || (cleanupMode == CleanupMode_Full)
8997 )
8998 llMedia.push_back(pMedium);
8999 }
9000
9001 // real machine: then we need to use the proper method
9002 rc = detachDevice(pAttach,
9003 writeLock,
9004 pSnapshot,
9005 NULL /* pfNeedsSaveSettings */);
9006
9007 if (FAILED(rc))
9008 return rc;
9009 }
9010
9011 return S_OK;
9012}
9013
9014/**
9015 * Perform deferred hard disk detachments.
9016 *
9017 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9018 * backed up).
9019 *
9020 * If @a aOnline is @c true then this method will also unlock the old hard disks
9021 * for which the new implicit diffs were created and will lock these new diffs for
9022 * writing.
9023 *
9024 * @param aOnline Whether the VM was online prior to this operation.
9025 *
9026 * @note Locks this object for writing!
9027 */
9028void Machine::commitMedia(bool aOnline /*= false*/)
9029{
9030 AutoCaller autoCaller(this);
9031 AssertComRCReturnVoid(autoCaller.rc());
9032
9033 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9034
9035 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9036
9037 HRESULT rc = S_OK;
9038
9039 /* no attach/detach operations -- nothing to do */
9040 if (!mMediaData.isBackedUp())
9041 return;
9042
9043 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9044 bool fMediaNeedsLocking = false;
9045
9046 /* enumerate new attachments */
9047 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9048 it != mMediaData->mAttachments.end();
9049 ++it)
9050 {
9051 MediumAttachment *pAttach = *it;
9052
9053 pAttach->commit();
9054
9055 Medium* pMedium = pAttach->getMedium();
9056 bool fImplicit = pAttach->isImplicit();
9057
9058 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9059 (pMedium) ? pMedium->getName().c_str() : "NULL",
9060 fImplicit));
9061
9062 /** @todo convert all this Machine-based voodoo to MediumAttachment
9063 * based commit logic. */
9064 if (fImplicit)
9065 {
9066 /* convert implicit attachment to normal */
9067 pAttach->setImplicit(false);
9068
9069 if ( aOnline
9070 && pMedium
9071 && pAttach->getType() == DeviceType_HardDisk
9072 )
9073 {
9074 ComObjPtr<Medium> parent = pMedium->getParent();
9075 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9076
9077 /* update the appropriate lock list */
9078 MediumLockList *pMediumLockList;
9079 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9080 AssertComRC(rc);
9081 if (pMediumLockList)
9082 {
9083 /* unlock if there's a need to change the locking */
9084 if (!fMediaNeedsLocking)
9085 {
9086 rc = mData->mSession.mLockedMedia.Unlock();
9087 AssertComRC(rc);
9088 fMediaNeedsLocking = true;
9089 }
9090 rc = pMediumLockList->Update(parent, false);
9091 AssertComRC(rc);
9092 rc = pMediumLockList->Append(pMedium, true);
9093 AssertComRC(rc);
9094 }
9095 }
9096
9097 continue;
9098 }
9099
9100 if (pMedium)
9101 {
9102 /* was this medium attached before? */
9103 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9104 oldIt != oldAtts.end();
9105 ++oldIt)
9106 {
9107 MediumAttachment *pOldAttach = *oldIt;
9108 if (pOldAttach->getMedium() == pMedium)
9109 {
9110 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9111
9112 /* yes: remove from old to avoid de-association */
9113 oldAtts.erase(oldIt);
9114 break;
9115 }
9116 }
9117 }
9118 }
9119
9120 /* enumerate remaining old attachments and de-associate from the
9121 * current machine state */
9122 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9123 it != oldAtts.end();
9124 ++it)
9125 {
9126 MediumAttachment *pAttach = *it;
9127 Medium* pMedium = pAttach->getMedium();
9128
9129 /* Detach only hard disks, since DVD/floppy media is detached
9130 * instantly in MountMedium. */
9131 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9132 {
9133 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9134
9135 /* now de-associate from the current machine state */
9136 rc = pMedium->removeBackReference(mData->mUuid);
9137 AssertComRC(rc);
9138
9139 if (aOnline)
9140 {
9141 /* unlock since medium is not used anymore */
9142 MediumLockList *pMediumLockList;
9143 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9144 AssertComRC(rc);
9145 if (pMediumLockList)
9146 {
9147 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9148 AssertComRC(rc);
9149 }
9150 }
9151 }
9152 }
9153
9154 /* take media locks again so that the locking state is consistent */
9155 if (fMediaNeedsLocking)
9156 {
9157 Assert(aOnline);
9158 rc = mData->mSession.mLockedMedia.Lock();
9159 AssertComRC(rc);
9160 }
9161
9162 /* commit the hard disk changes */
9163 mMediaData.commit();
9164
9165 if (isSessionMachine())
9166 {
9167 /* attach new data to the primary machine and reshare it */
9168 mPeer->mMediaData.attach(mMediaData);
9169 }
9170
9171 return;
9172}
9173
9174/**
9175 * Perform deferred deletion of implicitly created diffs.
9176 *
9177 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9178 * backed up).
9179 *
9180 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9181 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9182 *
9183 * @note Locks this object for writing!
9184 */
9185void Machine::rollbackMedia()
9186{
9187 AutoCaller autoCaller(this);
9188 AssertComRCReturnVoid (autoCaller.rc());
9189
9190 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9191
9192 LogFlowThisFunc(("Entering\n"));
9193
9194 HRESULT rc = S_OK;
9195
9196 /* no attach/detach operations -- nothing to do */
9197 if (!mMediaData.isBackedUp())
9198 return;
9199
9200 /* enumerate new attachments */
9201 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9202 it != mMediaData->mAttachments.end();
9203 ++it)
9204 {
9205 MediumAttachment *pAttach = *it;
9206 /* Fix up the backrefs for DVD/floppy media. */
9207 if (pAttach->getType() != DeviceType_HardDisk)
9208 {
9209 Medium* pMedium = pAttach->getMedium();
9210 if (pMedium)
9211 {
9212 rc = pMedium->removeBackReference(mData->mUuid);
9213 AssertComRC(rc);
9214 }
9215 }
9216
9217 (*it)->rollback();
9218
9219 pAttach = *it;
9220 /* Fix up the backrefs for DVD/floppy media. */
9221 if (pAttach->getType() != DeviceType_HardDisk)
9222 {
9223 Medium* pMedium = pAttach->getMedium();
9224 if (pMedium)
9225 {
9226 rc = pMedium->addBackReference(mData->mUuid);
9227 AssertComRC(rc);
9228 }
9229 }
9230 }
9231
9232 /** @todo convert all this Machine-based voodoo to MediumAttachment
9233 * based rollback logic. */
9234 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9235 // which gets called if Machine::registeredInit() fails...
9236 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9237
9238 return;
9239}
9240
9241/**
9242 * Returns true if the settings file is located in the directory named exactly
9243 * as the machine; this means, among other things, that the machine directory
9244 * should be auto-renamed.
9245 *
9246 * @param aSettingsDir if not NULL, the full machine settings file directory
9247 * name will be assigned there.
9248 *
9249 * @note Doesn't lock anything.
9250 * @note Not thread safe (must be called from this object's lock).
9251 */
9252bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9253{
9254 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9255 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9256 if (aSettingsDir)
9257 *aSettingsDir = strMachineDirName;
9258 strMachineDirName.stripPath(); // vmname
9259 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9260 strConfigFileOnly.stripPath() // vmname.vbox
9261 .stripExt(); // vmname
9262
9263 AssertReturn(!strMachineDirName.isEmpty(), false);
9264 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9265
9266 return strMachineDirName == strConfigFileOnly;
9267}
9268
9269/**
9270 * Discards all changes to machine settings.
9271 *
9272 * @param aNotify Whether to notify the direct session about changes or not.
9273 *
9274 * @note Locks objects for writing!
9275 */
9276void Machine::rollback(bool aNotify)
9277{
9278 AutoCaller autoCaller(this);
9279 AssertComRCReturn(autoCaller.rc(), (void)0);
9280
9281 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9282
9283 if (!mStorageControllers.isNull())
9284 {
9285 if (mStorageControllers.isBackedUp())
9286 {
9287 /* unitialize all new devices (absent in the backed up list). */
9288 StorageControllerList::const_iterator it = mStorageControllers->begin();
9289 StorageControllerList *backedList = mStorageControllers.backedUpData();
9290 while (it != mStorageControllers->end())
9291 {
9292 if ( std::find(backedList->begin(), backedList->end(), *it)
9293 == backedList->end()
9294 )
9295 {
9296 (*it)->uninit();
9297 }
9298 ++it;
9299 }
9300
9301 /* restore the list */
9302 mStorageControllers.rollback();
9303 }
9304
9305 /* rollback any changes to devices after restoring the list */
9306 if (mData->flModifications & IsModified_Storage)
9307 {
9308 StorageControllerList::const_iterator it = mStorageControllers->begin();
9309 while (it != mStorageControllers->end())
9310 {
9311 (*it)->rollback();
9312 ++it;
9313 }
9314 }
9315 }
9316
9317 mUserData.rollback();
9318
9319 mHWData.rollback();
9320
9321 if (mData->flModifications & IsModified_Storage)
9322 rollbackMedia();
9323
9324 if (mBIOSSettings)
9325 mBIOSSettings->rollback();
9326
9327 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9328 mVRDEServer->rollback();
9329
9330 if (mAudioAdapter)
9331 mAudioAdapter->rollback();
9332
9333 if (mUSBController && (mData->flModifications & IsModified_USB))
9334 mUSBController->rollback();
9335
9336 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9337 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9338 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9339
9340 if (mData->flModifications & IsModified_NetworkAdapters)
9341 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9342 if ( mNetworkAdapters[slot]
9343 && mNetworkAdapters[slot]->isModified())
9344 {
9345 mNetworkAdapters[slot]->rollback();
9346 networkAdapters[slot] = mNetworkAdapters[slot];
9347 }
9348
9349 if (mData->flModifications & IsModified_SerialPorts)
9350 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9351 if ( mSerialPorts[slot]
9352 && mSerialPorts[slot]->isModified())
9353 {
9354 mSerialPorts[slot]->rollback();
9355 serialPorts[slot] = mSerialPorts[slot];
9356 }
9357
9358 if (mData->flModifications & IsModified_ParallelPorts)
9359 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9360 if ( mParallelPorts[slot]
9361 && mParallelPorts[slot]->isModified())
9362 {
9363 mParallelPorts[slot]->rollback();
9364 parallelPorts[slot] = mParallelPorts[slot];
9365 }
9366
9367 if (aNotify)
9368 {
9369 /* inform the direct session about changes */
9370
9371 ComObjPtr<Machine> that = this;
9372 uint32_t flModifications = mData->flModifications;
9373 alock.leave();
9374
9375 if (flModifications & IsModified_SharedFolders)
9376 that->onSharedFolderChange();
9377
9378 if (flModifications & IsModified_VRDEServer)
9379 that->onVRDEServerChange(/* aRestart */ TRUE);
9380 if (flModifications & IsModified_USB)
9381 that->onUSBControllerChange();
9382
9383 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9384 if (networkAdapters[slot])
9385 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9386 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9387 if (serialPorts[slot])
9388 that->onSerialPortChange(serialPorts[slot]);
9389 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9390 if (parallelPorts[slot])
9391 that->onParallelPortChange(parallelPorts[slot]);
9392
9393 if (flModifications & IsModified_Storage)
9394 that->onStorageControllerChange();
9395 }
9396}
9397
9398/**
9399 * Commits all the changes to machine settings.
9400 *
9401 * Note that this operation is supposed to never fail.
9402 *
9403 * @note Locks this object and children for writing.
9404 */
9405void Machine::commit()
9406{
9407 AutoCaller autoCaller(this);
9408 AssertComRCReturnVoid(autoCaller.rc());
9409
9410 AutoCaller peerCaller(mPeer);
9411 AssertComRCReturnVoid(peerCaller.rc());
9412
9413 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9414
9415 /*
9416 * use safe commit to ensure Snapshot machines (that share mUserData)
9417 * will still refer to a valid memory location
9418 */
9419 mUserData.commitCopy();
9420
9421 mHWData.commit();
9422
9423 if (mMediaData.isBackedUp())
9424 commitMedia();
9425
9426 mBIOSSettings->commit();
9427 mVRDEServer->commit();
9428 mAudioAdapter->commit();
9429 mUSBController->commit();
9430
9431 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9432 mNetworkAdapters[slot]->commit();
9433 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9434 mSerialPorts[slot]->commit();
9435 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9436 mParallelPorts[slot]->commit();
9437
9438 bool commitStorageControllers = false;
9439
9440 if (mStorageControllers.isBackedUp())
9441 {
9442 mStorageControllers.commit();
9443
9444 if (mPeer)
9445 {
9446 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9447
9448 /* Commit all changes to new controllers (this will reshare data with
9449 * peers for those who have peers) */
9450 StorageControllerList *newList = new StorageControllerList();
9451 StorageControllerList::const_iterator it = mStorageControllers->begin();
9452 while (it != mStorageControllers->end())
9453 {
9454 (*it)->commit();
9455
9456 /* look if this controller has a peer device */
9457 ComObjPtr<StorageController> peer = (*it)->getPeer();
9458 if (!peer)
9459 {
9460 /* no peer means the device is a newly created one;
9461 * create a peer owning data this device share it with */
9462 peer.createObject();
9463 peer->init(mPeer, *it, true /* aReshare */);
9464 }
9465 else
9466 {
9467 /* remove peer from the old list */
9468 mPeer->mStorageControllers->remove(peer);
9469 }
9470 /* and add it to the new list */
9471 newList->push_back(peer);
9472
9473 ++it;
9474 }
9475
9476 /* uninit old peer's controllers that are left */
9477 it = mPeer->mStorageControllers->begin();
9478 while (it != mPeer->mStorageControllers->end())
9479 {
9480 (*it)->uninit();
9481 ++it;
9482 }
9483
9484 /* attach new list of controllers to our peer */
9485 mPeer->mStorageControllers.attach(newList);
9486 }
9487 else
9488 {
9489 /* we have no peer (our parent is the newly created machine);
9490 * just commit changes to devices */
9491 commitStorageControllers = true;
9492 }
9493 }
9494 else
9495 {
9496 /* the list of controllers itself is not changed,
9497 * just commit changes to controllers themselves */
9498 commitStorageControllers = true;
9499 }
9500
9501 if (commitStorageControllers)
9502 {
9503 StorageControllerList::const_iterator it = mStorageControllers->begin();
9504 while (it != mStorageControllers->end())
9505 {
9506 (*it)->commit();
9507 ++it;
9508 }
9509 }
9510
9511 if (isSessionMachine())
9512 {
9513 /* attach new data to the primary machine and reshare it */
9514 mPeer->mUserData.attach(mUserData);
9515 mPeer->mHWData.attach(mHWData);
9516 /* mMediaData is reshared by fixupMedia */
9517 // mPeer->mMediaData.attach(mMediaData);
9518 Assert(mPeer->mMediaData.data() == mMediaData.data());
9519 }
9520}
9521
9522/**
9523 * Copies all the hardware data from the given machine.
9524 *
9525 * Currently, only called when the VM is being restored from a snapshot. In
9526 * particular, this implies that the VM is not running during this method's
9527 * call.
9528 *
9529 * @note This method must be called from under this object's lock.
9530 *
9531 * @note This method doesn't call #commit(), so all data remains backed up and
9532 * unsaved.
9533 */
9534void Machine::copyFrom(Machine *aThat)
9535{
9536 AssertReturnVoid(!isSnapshotMachine());
9537 AssertReturnVoid(aThat->isSnapshotMachine());
9538
9539 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9540
9541 mHWData.assignCopy(aThat->mHWData);
9542
9543 // create copies of all shared folders (mHWData after attaching a copy
9544 // contains just references to original objects)
9545 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9546 it != mHWData->mSharedFolders.end();
9547 ++it)
9548 {
9549 ComObjPtr<SharedFolder> folder;
9550 folder.createObject();
9551 HRESULT rc = folder->initCopy(getMachine(), *it);
9552 AssertComRC(rc);
9553 *it = folder;
9554 }
9555
9556 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9557 mVRDEServer->copyFrom(aThat->mVRDEServer);
9558 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9559 mUSBController->copyFrom(aThat->mUSBController);
9560
9561 /* create private copies of all controllers */
9562 mStorageControllers.backup();
9563 mStorageControllers->clear();
9564 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9565 it != aThat->mStorageControllers->end();
9566 ++it)
9567 {
9568 ComObjPtr<StorageController> ctrl;
9569 ctrl.createObject();
9570 ctrl->initCopy(this, *it);
9571 mStorageControllers->push_back(ctrl);
9572 }
9573
9574 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9575 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9576 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9577 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9578 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9579 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9580}
9581
9582#ifdef VBOX_WITH_RESOURCE_USAGE_API
9583
9584void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9585{
9586 AssertReturnVoid(isWriteLockOnCurrentThread());
9587 AssertPtrReturnVoid(aCollector);
9588
9589 pm::CollectorHAL *hal = aCollector->getHAL();
9590 /* Create sub metrics */
9591 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9592 "Percentage of processor time spent in user mode by the VM process.");
9593 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9594 "Percentage of processor time spent in kernel mode by the VM process.");
9595 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9596 "Size of resident portion of VM process in memory.");
9597 /* Create and register base metrics */
9598 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9599 cpuLoadUser, cpuLoadKernel);
9600 aCollector->registerBaseMetric(cpuLoad);
9601 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9602 ramUsageUsed);
9603 aCollector->registerBaseMetric(ramUsage);
9604
9605 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9606 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9607 new pm::AggregateAvg()));
9608 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9609 new pm::AggregateMin()));
9610 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9611 new pm::AggregateMax()));
9612 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9613 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9614 new pm::AggregateAvg()));
9615 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9616 new pm::AggregateMin()));
9617 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9618 new pm::AggregateMax()));
9619
9620 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9621 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9622 new pm::AggregateAvg()));
9623 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9624 new pm::AggregateMin()));
9625 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9626 new pm::AggregateMax()));
9627
9628
9629 /* Guest metrics */
9630 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9631
9632 /* Create sub metrics */
9633 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9634 "Percentage of processor time spent in user mode as seen by the guest.");
9635 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9636 "Percentage of processor time spent in kernel mode as seen by the guest.");
9637 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9638 "Percentage of processor time spent idling as seen by the guest.");
9639
9640 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9641 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9642 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9643 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9644 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9645 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9646
9647 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9648
9649 /* Create and register base metrics */
9650 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9651 aCollector->registerBaseMetric(guestCpuLoad);
9652
9653 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9654 guestMemCache, guestPagedTotal);
9655 aCollector->registerBaseMetric(guestCpuMem);
9656
9657 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9658 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9659 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9660 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9661
9662 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9663 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9664 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9665 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9666
9667 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9668 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9669 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9670 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9671
9672 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9673 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9674 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9675 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9676
9677 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9678 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9679 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9680 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9681
9682 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9683 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9684 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9685 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9686
9687 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9688 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9689 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9690 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9691
9692 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9693 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9694 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9695 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9696
9697 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9698 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9699 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9700 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9701}
9702
9703void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9704{
9705 AssertReturnVoid(isWriteLockOnCurrentThread());
9706
9707 if (aCollector)
9708 {
9709 aCollector->unregisterMetricsFor(aMachine);
9710 aCollector->unregisterBaseMetricsFor(aMachine);
9711 }
9712
9713 if (mGuestHAL)
9714 {
9715 delete mGuestHAL;
9716 mGuestHAL = NULL;
9717 }
9718}
9719
9720#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9721
9722
9723////////////////////////////////////////////////////////////////////////////////
9724
9725DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9726
9727HRESULT SessionMachine::FinalConstruct()
9728{
9729 LogFlowThisFunc(("\n"));
9730
9731#if defined(RT_OS_WINDOWS)
9732 mIPCSem = NULL;
9733#elif defined(RT_OS_OS2)
9734 mIPCSem = NULLHANDLE;
9735#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9736 mIPCSem = -1;
9737#else
9738# error "Port me!"
9739#endif
9740
9741 return S_OK;
9742}
9743
9744void SessionMachine::FinalRelease()
9745{
9746 LogFlowThisFunc(("\n"));
9747
9748 uninit(Uninit::Unexpected);
9749}
9750
9751/**
9752 * @note Must be called only by Machine::openSession() from its own write lock.
9753 */
9754HRESULT SessionMachine::init(Machine *aMachine)
9755{
9756 LogFlowThisFuncEnter();
9757 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9758
9759 AssertReturn(aMachine, E_INVALIDARG);
9760
9761 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9762
9763 /* Enclose the state transition NotReady->InInit->Ready */
9764 AutoInitSpan autoInitSpan(this);
9765 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9766
9767 /* create the interprocess semaphore */
9768#if defined(RT_OS_WINDOWS)
9769 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9770 for (size_t i = 0; i < mIPCSemName.length(); i++)
9771 if (mIPCSemName.raw()[i] == '\\')
9772 mIPCSemName.raw()[i] = '/';
9773 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
9774 ComAssertMsgRet(mIPCSem,
9775 ("Cannot create IPC mutex '%ls', err=%d",
9776 mIPCSemName.raw(), ::GetLastError()),
9777 E_FAIL);
9778#elif defined(RT_OS_OS2)
9779 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9780 aMachine->mData->mUuid.raw());
9781 mIPCSemName = ipcSem;
9782 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
9783 ComAssertMsgRet(arc == NO_ERROR,
9784 ("Cannot create IPC mutex '%s', arc=%ld",
9785 ipcSem.c_str(), arc),
9786 E_FAIL);
9787#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9788# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9789# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9790 /** @todo Check that this still works correctly. */
9791 AssertCompileSize(key_t, 8);
9792# else
9793 AssertCompileSize(key_t, 4);
9794# endif
9795 key_t key;
9796 mIPCSem = -1;
9797 mIPCKey = "0";
9798 for (uint32_t i = 0; i < 1 << 24; i++)
9799 {
9800 key = ((uint32_t)'V' << 24) | i;
9801 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9802 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9803 {
9804 mIPCSem = sem;
9805 if (sem >= 0)
9806 mIPCKey = BstrFmt("%u", key);
9807 break;
9808 }
9809 }
9810# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9811 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9812 char *pszSemName = NULL;
9813 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9814 key_t key = ::ftok(pszSemName, 'V');
9815 RTStrFree(pszSemName);
9816
9817 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9818# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9819
9820 int errnoSave = errno;
9821 if (mIPCSem < 0 && errnoSave == ENOSYS)
9822 {
9823 setError(E_FAIL,
9824 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9825 "support for SysV IPC. Check the host kernel configuration for "
9826 "CONFIG_SYSVIPC=y"));
9827 return E_FAIL;
9828 }
9829 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9830 * the IPC semaphores */
9831 if (mIPCSem < 0 && errnoSave == ENOSPC)
9832 {
9833#ifdef RT_OS_LINUX
9834 setError(E_FAIL,
9835 tr("Cannot create IPC semaphore because the system limit for the "
9836 "maximum number of semaphore sets (SEMMNI), or the system wide "
9837 "maximum number of semaphores (SEMMNS) would be exceeded. The "
9838 "current set of SysV IPC semaphores can be determined from "
9839 "the file /proc/sysvipc/sem"));
9840#else
9841 setError(E_FAIL,
9842 tr("Cannot create IPC semaphore because the system-imposed limit "
9843 "on the maximum number of allowed semaphores or semaphore "
9844 "identifiers system-wide would be exceeded"));
9845#endif
9846 return E_FAIL;
9847 }
9848 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9849 E_FAIL);
9850 /* set the initial value to 1 */
9851 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9852 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9853 E_FAIL);
9854#else
9855# error "Port me!"
9856#endif
9857
9858 /* memorize the peer Machine */
9859 unconst(mPeer) = aMachine;
9860 /* share the parent pointer */
9861 unconst(mParent) = aMachine->mParent;
9862
9863 /* take the pointers to data to share */
9864 mData.share(aMachine->mData);
9865 mSSData.share(aMachine->mSSData);
9866
9867 mUserData.share(aMachine->mUserData);
9868 mHWData.share(aMachine->mHWData);
9869 mMediaData.share(aMachine->mMediaData);
9870
9871 mStorageControllers.allocate();
9872 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9873 it != aMachine->mStorageControllers->end();
9874 ++it)
9875 {
9876 ComObjPtr<StorageController> ctl;
9877 ctl.createObject();
9878 ctl->init(this, *it);
9879 mStorageControllers->push_back(ctl);
9880 }
9881
9882 unconst(mBIOSSettings).createObject();
9883 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9884 /* create another VRDEServer object that will be mutable */
9885 unconst(mVRDEServer).createObject();
9886 mVRDEServer->init(this, aMachine->mVRDEServer);
9887 /* create another audio adapter object that will be mutable */
9888 unconst(mAudioAdapter).createObject();
9889 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9890 /* create a list of serial ports that will be mutable */
9891 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9892 {
9893 unconst(mSerialPorts[slot]).createObject();
9894 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9895 }
9896 /* create a list of parallel ports that will be mutable */
9897 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9898 {
9899 unconst(mParallelPorts[slot]).createObject();
9900 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9901 }
9902 /* create another USB controller object that will be mutable */
9903 unconst(mUSBController).createObject();
9904 mUSBController->init(this, aMachine->mUSBController);
9905
9906 /* create a list of network adapters that will be mutable */
9907 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9908 {
9909 unconst(mNetworkAdapters[slot]).createObject();
9910 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9911 }
9912
9913 /* default is to delete saved state on Saved -> PoweredOff transition */
9914 mRemoveSavedState = true;
9915
9916 /* Confirm a successful initialization when it's the case */
9917 autoInitSpan.setSucceeded();
9918
9919 LogFlowThisFuncLeave();
9920 return S_OK;
9921}
9922
9923/**
9924 * Uninitializes this session object. If the reason is other than
9925 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9926 *
9927 * @param aReason uninitialization reason
9928 *
9929 * @note Locks mParent + this object for writing.
9930 */
9931void SessionMachine::uninit(Uninit::Reason aReason)
9932{
9933 LogFlowThisFuncEnter();
9934 LogFlowThisFunc(("reason=%d\n", aReason));
9935
9936 /*
9937 * Strongly reference ourselves to prevent this object deletion after
9938 * mData->mSession.mMachine.setNull() below (which can release the last
9939 * reference and call the destructor). Important: this must be done before
9940 * accessing any members (and before AutoUninitSpan that does it as well).
9941 * This self reference will be released as the very last step on return.
9942 */
9943 ComObjPtr<SessionMachine> selfRef = this;
9944
9945 /* Enclose the state transition Ready->InUninit->NotReady */
9946 AutoUninitSpan autoUninitSpan(this);
9947 if (autoUninitSpan.uninitDone())
9948 {
9949 LogFlowThisFunc(("Already uninitialized\n"));
9950 LogFlowThisFuncLeave();
9951 return;
9952 }
9953
9954 if (autoUninitSpan.initFailed())
9955 {
9956 /* We've been called by init() because it's failed. It's not really
9957 * necessary (nor it's safe) to perform the regular uninit sequence
9958 * below, the following is enough.
9959 */
9960 LogFlowThisFunc(("Initialization failed.\n"));
9961#if defined(RT_OS_WINDOWS)
9962 if (mIPCSem)
9963 ::CloseHandle(mIPCSem);
9964 mIPCSem = NULL;
9965#elif defined(RT_OS_OS2)
9966 if (mIPCSem != NULLHANDLE)
9967 ::DosCloseMutexSem(mIPCSem);
9968 mIPCSem = NULLHANDLE;
9969#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9970 if (mIPCSem >= 0)
9971 ::semctl(mIPCSem, 0, IPC_RMID);
9972 mIPCSem = -1;
9973# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9974 mIPCKey = "0";
9975# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9976#else
9977# error "Port me!"
9978#endif
9979 uninitDataAndChildObjects();
9980 mData.free();
9981 unconst(mParent) = NULL;
9982 unconst(mPeer) = NULL;
9983 LogFlowThisFuncLeave();
9984 return;
9985 }
9986
9987 MachineState_T lastState;
9988 {
9989 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9990 lastState = mData->mMachineState;
9991 }
9992 NOREF(lastState);
9993
9994#ifdef VBOX_WITH_USB
9995 // release all captured USB devices, but do this before requesting the locks below
9996 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9997 {
9998 /* Console::captureUSBDevices() is called in the VM process only after
9999 * setting the machine state to Starting or Restoring.
10000 * Console::detachAllUSBDevices() will be called upon successful
10001 * termination. So, we need to release USB devices only if there was
10002 * an abnormal termination of a running VM.
10003 *
10004 * This is identical to SessionMachine::DetachAllUSBDevices except
10005 * for the aAbnormal argument. */
10006 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10007 AssertComRC(rc);
10008 NOREF(rc);
10009
10010 USBProxyService *service = mParent->host()->usbProxyService();
10011 if (service)
10012 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10013 }
10014#endif /* VBOX_WITH_USB */
10015
10016 // we need to lock this object in uninit() because the lock is shared
10017 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10018 // and others need mParent lock, and USB needs host lock.
10019 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10020
10021 // Trigger async cleanup tasks, avoid doing things here which are not
10022 // vital to be done immediately and maybe need more locks. This calls
10023 // Machine::unregisterMetrics().
10024 mParent->onMachineUninit(mPeer);
10025
10026 if (aReason == Uninit::Abnormal)
10027 {
10028 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10029 Global::IsOnlineOrTransient(lastState)));
10030
10031 /* reset the state to Aborted */
10032 if (mData->mMachineState != MachineState_Aborted)
10033 setMachineState(MachineState_Aborted);
10034 }
10035
10036 // any machine settings modified?
10037 if (mData->flModifications)
10038 {
10039 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10040 rollback(false /* aNotify */);
10041 }
10042
10043 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
10044 if (!mSnapshotData.mStateFilePath.isEmpty())
10045 {
10046 LogWarningThisFunc(("canceling failed save state request!\n"));
10047 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10048 }
10049 else if (!mSnapshotData.mSnapshot.isNull())
10050 {
10051 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10052
10053 /* delete all differencing hard disks created (this will also attach
10054 * their parents back by rolling back mMediaData) */
10055 rollbackMedia();
10056 /* delete the saved state file (it might have been already created) */
10057 if (mSnapshotData.mSnapshot->stateFilePath().length())
10058 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
10059
10060 mSnapshotData.mSnapshot->uninit();
10061 }
10062
10063 if (!mData->mSession.mType.isEmpty())
10064 {
10065 /* mType is not null when this machine's process has been started by
10066 * Machine::launchVMProcess(), therefore it is our child. We
10067 * need to queue the PID to reap the process (and avoid zombies on
10068 * Linux). */
10069 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10070 mParent->addProcessToReap(mData->mSession.mPid);
10071 }
10072
10073 mData->mSession.mPid = NIL_RTPROCESS;
10074
10075 if (aReason == Uninit::Unexpected)
10076 {
10077 /* Uninitialization didn't come from #checkForDeath(), so tell the
10078 * client watcher thread to update the set of machines that have open
10079 * sessions. */
10080 mParent->updateClientWatcher();
10081 }
10082
10083 /* uninitialize all remote controls */
10084 if (mData->mSession.mRemoteControls.size())
10085 {
10086 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10087 mData->mSession.mRemoteControls.size()));
10088
10089 Data::Session::RemoteControlList::iterator it =
10090 mData->mSession.mRemoteControls.begin();
10091 while (it != mData->mSession.mRemoteControls.end())
10092 {
10093 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10094 HRESULT rc = (*it)->Uninitialize();
10095 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10096 if (FAILED(rc))
10097 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10098 ++it;
10099 }
10100 mData->mSession.mRemoteControls.clear();
10101 }
10102
10103 /*
10104 * An expected uninitialization can come only from #checkForDeath().
10105 * Otherwise it means that something's gone really wrong (for example,
10106 * the Session implementation has released the VirtualBox reference
10107 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10108 * etc). However, it's also possible, that the client releases the IPC
10109 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10110 * but the VirtualBox release event comes first to the server process.
10111 * This case is practically possible, so we should not assert on an
10112 * unexpected uninit, just log a warning.
10113 */
10114
10115 if ((aReason == Uninit::Unexpected))
10116 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10117
10118 if (aReason != Uninit::Normal)
10119 {
10120 mData->mSession.mDirectControl.setNull();
10121 }
10122 else
10123 {
10124 /* this must be null here (see #OnSessionEnd()) */
10125 Assert(mData->mSession.mDirectControl.isNull());
10126 Assert(mData->mSession.mState == SessionState_Unlocking);
10127 Assert(!mData->mSession.mProgress.isNull());
10128 }
10129 if (mData->mSession.mProgress)
10130 {
10131 if (aReason == Uninit::Normal)
10132 mData->mSession.mProgress->notifyComplete(S_OK);
10133 else
10134 mData->mSession.mProgress->notifyComplete(E_FAIL,
10135 COM_IIDOF(ISession),
10136 getComponentName(),
10137 tr("The VM session was aborted"));
10138 mData->mSession.mProgress.setNull();
10139 }
10140
10141 /* remove the association between the peer machine and this session machine */
10142 Assert( (SessionMachine*)mData->mSession.mMachine == this
10143 || aReason == Uninit::Unexpected);
10144
10145 /* reset the rest of session data */
10146 mData->mSession.mMachine.setNull();
10147 mData->mSession.mState = SessionState_Unlocked;
10148 mData->mSession.mType.setNull();
10149
10150 /* close the interprocess semaphore before leaving the exclusive lock */
10151#if defined(RT_OS_WINDOWS)
10152 if (mIPCSem)
10153 ::CloseHandle(mIPCSem);
10154 mIPCSem = NULL;
10155#elif defined(RT_OS_OS2)
10156 if (mIPCSem != NULLHANDLE)
10157 ::DosCloseMutexSem(mIPCSem);
10158 mIPCSem = NULLHANDLE;
10159#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10160 if (mIPCSem >= 0)
10161 ::semctl(mIPCSem, 0, IPC_RMID);
10162 mIPCSem = -1;
10163# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10164 mIPCKey = "0";
10165# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10166#else
10167# error "Port me!"
10168#endif
10169
10170 /* fire an event */
10171 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10172
10173 uninitDataAndChildObjects();
10174
10175 /* free the essential data structure last */
10176 mData.free();
10177
10178#if 1 /** @todo Please review this change! (bird) */
10179 /* drop the exclusive lock before setting the below two to NULL */
10180 multilock.release();
10181#else
10182 /* leave the exclusive lock before setting the below two to NULL */
10183 multilock.leave();
10184#endif
10185
10186 unconst(mParent) = NULL;
10187 unconst(mPeer) = NULL;
10188
10189 LogFlowThisFuncLeave();
10190}
10191
10192// util::Lockable interface
10193////////////////////////////////////////////////////////////////////////////////
10194
10195/**
10196 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10197 * with the primary Machine instance (mPeer).
10198 */
10199RWLockHandle *SessionMachine::lockHandle() const
10200{
10201 AssertReturn(mPeer != NULL, NULL);
10202 return mPeer->lockHandle();
10203}
10204
10205// IInternalMachineControl methods
10206////////////////////////////////////////////////////////////////////////////////
10207
10208/**
10209 * @note Locks this object for writing.
10210 */
10211STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10212{
10213 AutoCaller autoCaller(this);
10214 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10215
10216 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10217
10218 mRemoveSavedState = aRemove;
10219
10220 return S_OK;
10221}
10222
10223/**
10224 * @note Locks the same as #setMachineState() does.
10225 */
10226STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10227{
10228 return setMachineState(aMachineState);
10229}
10230
10231/**
10232 * @note Locks this object for reading.
10233 */
10234STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10235{
10236 AutoCaller autoCaller(this);
10237 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10238
10239 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10240
10241#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10242 mIPCSemName.cloneTo(aId);
10243 return S_OK;
10244#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10245# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10246 mIPCKey.cloneTo(aId);
10247# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10248 mData->m_strConfigFileFull.cloneTo(aId);
10249# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10250 return S_OK;
10251#else
10252# error "Port me!"
10253#endif
10254}
10255
10256/**
10257 * @note Locks this object for writing.
10258 */
10259STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10260{
10261 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10262 AutoCaller autoCaller(this);
10263 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10264
10265 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10266
10267 if (mData->mSession.mState != SessionState_Locked)
10268 return VBOX_E_INVALID_OBJECT_STATE;
10269
10270 if (!mData->mSession.mProgress.isNull())
10271 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10272
10273 LogFlowThisFunc(("returns S_OK.\n"));
10274 return S_OK;
10275}
10276
10277
10278/**
10279 * @note Locks this object for writing.
10280 */
10281STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10282{
10283 AutoCaller autoCaller(this);
10284 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10285
10286 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10287
10288 if (mData->mSession.mState != SessionState_Locked)
10289 return VBOX_E_INVALID_OBJECT_STATE;
10290
10291 /* Finalize the openRemoteSession progress object. */
10292 if (mData->mSession.mProgress)
10293 {
10294 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10295 mData->mSession.mProgress.setNull();
10296 }
10297
10298 if (SUCCEEDED((HRESULT)iResult))
10299 {
10300#ifdef VBOX_WITH_RESOURCE_USAGE_API
10301 /* The VM has been powered up successfully, so it makes sense
10302 * now to offer the performance metrics for a running machine
10303 * object. Doing it earlier wouldn't be safe. */
10304 registerMetrics(mParent->performanceCollector(), mPeer,
10305 mData->mSession.mPid);
10306#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10307 }
10308
10309 return S_OK;
10310}
10311
10312/**
10313 * Goes through the USB filters of the given machine to see if the given
10314 * device matches any filter or not.
10315 *
10316 * @note Locks the same as USBController::hasMatchingFilter() does.
10317 */
10318STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10319 BOOL *aMatched,
10320 ULONG *aMaskedIfs)
10321{
10322 LogFlowThisFunc(("\n"));
10323
10324 CheckComArgNotNull(aUSBDevice);
10325 CheckComArgOutPointerValid(aMatched);
10326
10327 AutoCaller autoCaller(this);
10328 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10329
10330#ifdef VBOX_WITH_USB
10331 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10332#else
10333 NOREF(aUSBDevice);
10334 NOREF(aMaskedIfs);
10335 *aMatched = FALSE;
10336#endif
10337
10338 return S_OK;
10339}
10340
10341/**
10342 * @note Locks the same as Host::captureUSBDevice() does.
10343 */
10344STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10345{
10346 LogFlowThisFunc(("\n"));
10347
10348 AutoCaller autoCaller(this);
10349 AssertComRCReturnRC(autoCaller.rc());
10350
10351#ifdef VBOX_WITH_USB
10352 /* if captureDeviceForVM() fails, it must have set extended error info */
10353 MultiResult rc = mParent->host()->checkUSBProxyService();
10354 if (FAILED(rc)) return rc;
10355
10356 USBProxyService *service = mParent->host()->usbProxyService();
10357 AssertReturn(service, E_FAIL);
10358 return service->captureDeviceForVM(this, Guid(aId).ref());
10359#else
10360 NOREF(aId);
10361 return E_NOTIMPL;
10362#endif
10363}
10364
10365/**
10366 * @note Locks the same as Host::detachUSBDevice() does.
10367 */
10368STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10369{
10370 LogFlowThisFunc(("\n"));
10371
10372 AutoCaller autoCaller(this);
10373 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10374
10375#ifdef VBOX_WITH_USB
10376 USBProxyService *service = mParent->host()->usbProxyService();
10377 AssertReturn(service, E_FAIL);
10378 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10379#else
10380 NOREF(aId);
10381 NOREF(aDone);
10382 return E_NOTIMPL;
10383#endif
10384}
10385
10386/**
10387 * Inserts all machine filters to the USB proxy service and then calls
10388 * Host::autoCaptureUSBDevices().
10389 *
10390 * Called by Console from the VM process upon VM startup.
10391 *
10392 * @note Locks what called methods lock.
10393 */
10394STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10395{
10396 LogFlowThisFunc(("\n"));
10397
10398 AutoCaller autoCaller(this);
10399 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10400
10401#ifdef VBOX_WITH_USB
10402 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10403 AssertComRC(rc);
10404 NOREF(rc);
10405
10406 USBProxyService *service = mParent->host()->usbProxyService();
10407 AssertReturn(service, E_FAIL);
10408 return service->autoCaptureDevicesForVM(this);
10409#else
10410 return S_OK;
10411#endif
10412}
10413
10414/**
10415 * Removes all machine filters from the USB proxy service and then calls
10416 * Host::detachAllUSBDevices().
10417 *
10418 * Called by Console from the VM process upon normal VM termination or by
10419 * SessionMachine::uninit() upon abnormal VM termination (from under the
10420 * Machine/SessionMachine lock).
10421 *
10422 * @note Locks what called methods lock.
10423 */
10424STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10425{
10426 LogFlowThisFunc(("\n"));
10427
10428 AutoCaller autoCaller(this);
10429 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10430
10431#ifdef VBOX_WITH_USB
10432 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10433 AssertComRC(rc);
10434 NOREF(rc);
10435
10436 USBProxyService *service = mParent->host()->usbProxyService();
10437 AssertReturn(service, E_FAIL);
10438 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10439#else
10440 NOREF(aDone);
10441 return S_OK;
10442#endif
10443}
10444
10445/**
10446 * @note Locks this object for writing.
10447 */
10448STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10449 IProgress **aProgress)
10450{
10451 LogFlowThisFuncEnter();
10452
10453 AssertReturn(aSession, E_INVALIDARG);
10454 AssertReturn(aProgress, E_INVALIDARG);
10455
10456 AutoCaller autoCaller(this);
10457
10458 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10459 /*
10460 * We don't assert below because it might happen that a non-direct session
10461 * informs us it is closed right after we've been uninitialized -- it's ok.
10462 */
10463 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10464
10465 /* get IInternalSessionControl interface */
10466 ComPtr<IInternalSessionControl> control(aSession);
10467
10468 ComAssertRet(!control.isNull(), E_INVALIDARG);
10469
10470 /* Creating a Progress object requires the VirtualBox lock, and
10471 * thus locking it here is required by the lock order rules. */
10472 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10473
10474 if (control == mData->mSession.mDirectControl)
10475 {
10476 ComAssertRet(aProgress, E_POINTER);
10477
10478 /* The direct session is being normally closed by the client process
10479 * ----------------------------------------------------------------- */
10480
10481 /* go to the closing state (essential for all open*Session() calls and
10482 * for #checkForDeath()) */
10483 Assert(mData->mSession.mState == SessionState_Locked);
10484 mData->mSession.mState = SessionState_Unlocking;
10485
10486 /* set direct control to NULL to release the remote instance */
10487 mData->mSession.mDirectControl.setNull();
10488 LogFlowThisFunc(("Direct control is set to NULL\n"));
10489
10490 if (mData->mSession.mProgress)
10491 {
10492 /* finalize the progress, someone might wait if a frontend
10493 * closes the session before powering on the VM. */
10494 mData->mSession.mProgress->notifyComplete(E_FAIL,
10495 COM_IIDOF(ISession),
10496 getComponentName(),
10497 tr("The VM session was closed before any attempt to power it on"));
10498 mData->mSession.mProgress.setNull();
10499 }
10500
10501 /* Create the progress object the client will use to wait until
10502 * #checkForDeath() is called to uninitialize this session object after
10503 * it releases the IPC semaphore.
10504 * Note! Because we're "reusing" mProgress here, this must be a proxy
10505 * object just like for openRemoteSession. */
10506 Assert(mData->mSession.mProgress.isNull());
10507 ComObjPtr<ProgressProxy> progress;
10508 progress.createObject();
10509 ComPtr<IUnknown> pPeer(mPeer);
10510 progress->init(mParent, pPeer,
10511 Bstr(tr("Closing session")).raw(),
10512 FALSE /* aCancelable */);
10513 progress.queryInterfaceTo(aProgress);
10514 mData->mSession.mProgress = progress;
10515 }
10516 else
10517 {
10518 /* the remote session is being normally closed */
10519 Data::Session::RemoteControlList::iterator it =
10520 mData->mSession.mRemoteControls.begin();
10521 while (it != mData->mSession.mRemoteControls.end())
10522 {
10523 if (control == *it)
10524 break;
10525 ++it;
10526 }
10527 BOOL found = it != mData->mSession.mRemoteControls.end();
10528 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10529 E_INVALIDARG);
10530 mData->mSession.mRemoteControls.remove(*it);
10531 }
10532
10533 LogFlowThisFuncLeave();
10534 return S_OK;
10535}
10536
10537/**
10538 * @note Locks this object for writing.
10539 */
10540STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
10541{
10542 LogFlowThisFuncEnter();
10543
10544 CheckComArgOutPointerValid(aProgress);
10545 CheckComArgOutPointerValid(aStateFilePath);
10546
10547 AutoCaller autoCaller(this);
10548 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10549
10550 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10551
10552 AssertReturn( mData->mMachineState == MachineState_Paused
10553 && mSnapshotData.mLastState == MachineState_Null
10554 && mSnapshotData.mStateFilePath.isEmpty(),
10555 E_FAIL);
10556
10557 /* create a progress object to track operation completion */
10558 ComObjPtr<Progress> pProgress;
10559 pProgress.createObject();
10560 pProgress->init(getVirtualBox(),
10561 static_cast<IMachine *>(this) /* aInitiator */,
10562 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
10563 FALSE /* aCancelable */);
10564
10565 Bstr stateFilePath;
10566 /* stateFilePath is null when the machine is not running */
10567 if (mData->mMachineState == MachineState_Paused)
10568 {
10569 Utf8Str strFullSnapshotFolder;
10570 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
10571 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10572 strFullSnapshotFolder.c_str(),
10573 RTPATH_DELIMITER,
10574 mData->mUuid.raw());
10575 }
10576
10577 /* fill in the snapshot data */
10578 mSnapshotData.mLastState = mData->mMachineState;
10579 mSnapshotData.mStateFilePath = stateFilePath;
10580 mSnapshotData.mProgress = pProgress;
10581
10582 /* set the state to Saving (this is expected by Console::SaveState()) */
10583 setMachineState(MachineState_Saving);
10584
10585 stateFilePath.cloneTo(aStateFilePath);
10586 pProgress.queryInterfaceTo(aProgress);
10587
10588 return S_OK;
10589}
10590
10591/**
10592 * @note Locks mParent + this object for writing.
10593 */
10594STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
10595{
10596 LogFlowThisFunc(("\n"));
10597
10598 AutoCaller autoCaller(this);
10599 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10600
10601 /* endSavingState() need mParent lock */
10602 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10603
10604 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
10605 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
10606 && mSnapshotData.mLastState != MachineState_Null
10607 && !mSnapshotData.mStateFilePath.isEmpty(),
10608 E_FAIL);
10609
10610 /*
10611 * On failure, set the state to the state we had when BeginSavingState()
10612 * was called (this is expected by Console::SaveState() and the associated
10613 * task). On success the VM process already changed the state to
10614 * MachineState_Saved, so no need to do anything.
10615 */
10616 if (FAILED(iResult))
10617 setMachineState(mSnapshotData.mLastState);
10618
10619 return endSavingState(iResult, aErrMsg);
10620}
10621
10622/**
10623 * @note Locks this object for writing.
10624 */
10625STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10626{
10627 LogFlowThisFunc(("\n"));
10628
10629 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10630
10631 AutoCaller autoCaller(this);
10632 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10633
10634 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10635
10636 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10637 || mData->mMachineState == MachineState_Teleported
10638 || mData->mMachineState == MachineState_Aborted
10639 , E_FAIL); /** @todo setError. */
10640
10641 Utf8Str stateFilePathFull = aSavedStateFile;
10642 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10643 if (RT_FAILURE(vrc))
10644 return setError(VBOX_E_FILE_ERROR,
10645 tr("Invalid saved state file path '%ls' (%Rrc)"),
10646 aSavedStateFile,
10647 vrc);
10648
10649 mSSData->mStateFilePath = stateFilePathFull;
10650
10651 /* The below setMachineState() will detect the state transition and will
10652 * update the settings file */
10653
10654 return setMachineState(MachineState_Saved);
10655}
10656
10657STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10658 ComSafeArrayOut(BSTR, aValues),
10659 ComSafeArrayOut(LONG64, aTimestamps),
10660 ComSafeArrayOut(BSTR, aFlags))
10661{
10662 LogFlowThisFunc(("\n"));
10663
10664#ifdef VBOX_WITH_GUEST_PROPS
10665 using namespace guestProp;
10666
10667 AutoCaller autoCaller(this);
10668 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10669
10670 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10671
10672 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10673 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10674 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10675 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10676
10677 size_t cEntries = mHWData->mGuestProperties.size();
10678 com::SafeArray<BSTR> names(cEntries);
10679 com::SafeArray<BSTR> values(cEntries);
10680 com::SafeArray<LONG64> timestamps(cEntries);
10681 com::SafeArray<BSTR> flags(cEntries);
10682 unsigned i = 0;
10683 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10684 it != mHWData->mGuestProperties.end();
10685 ++it)
10686 {
10687 char szFlags[MAX_FLAGS_LEN + 1];
10688 it->strName.cloneTo(&names[i]);
10689 it->strValue.cloneTo(&values[i]);
10690 timestamps[i] = it->mTimestamp;
10691 /* If it is NULL, keep it NULL. */
10692 if (it->mFlags)
10693 {
10694 writeFlags(it->mFlags, szFlags);
10695 Bstr(szFlags).cloneTo(&flags[i]);
10696 }
10697 else
10698 flags[i] = NULL;
10699 ++i;
10700 }
10701 names.detachTo(ComSafeArrayOutArg(aNames));
10702 values.detachTo(ComSafeArrayOutArg(aValues));
10703 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10704 flags.detachTo(ComSafeArrayOutArg(aFlags));
10705 return S_OK;
10706#else
10707 ReturnComNotImplemented();
10708#endif
10709}
10710
10711STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10712 IN_BSTR aValue,
10713 LONG64 aTimestamp,
10714 IN_BSTR aFlags)
10715{
10716 LogFlowThisFunc(("\n"));
10717
10718#ifdef VBOX_WITH_GUEST_PROPS
10719 using namespace guestProp;
10720
10721 CheckComArgStrNotEmptyOrNull(aName);
10722 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10723 return E_POINTER; /* aValue can be NULL to indicate deletion */
10724
10725 try
10726 {
10727 /*
10728 * Convert input up front.
10729 */
10730 Utf8Str utf8Name(aName);
10731 uint32_t fFlags = NILFLAG;
10732 if (aFlags)
10733 {
10734 Utf8Str utf8Flags(aFlags);
10735 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
10736 AssertRCReturn(vrc, E_INVALIDARG);
10737 }
10738
10739 /*
10740 * Now grab the object lock, validate the state and do the update.
10741 */
10742 AutoCaller autoCaller(this);
10743 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10744
10745 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10746
10747 switch (mData->mMachineState)
10748 {
10749 case MachineState_Paused:
10750 case MachineState_Running:
10751 case MachineState_Teleporting:
10752 case MachineState_TeleportingPausedVM:
10753 case MachineState_LiveSnapshotting:
10754 case MachineState_DeletingSnapshotOnline:
10755 case MachineState_DeletingSnapshotPaused:
10756 case MachineState_Saving:
10757 break;
10758
10759 default:
10760#ifndef DEBUG_sunlover
10761 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10762 VBOX_E_INVALID_VM_STATE);
10763#else
10764 return VBOX_E_INVALID_VM_STATE;
10765#endif
10766 }
10767
10768 setModified(IsModified_MachineData);
10769 mHWData.backup();
10770
10771 /** @todo r=bird: The careful memory handling doesn't work out here because
10772 * the catch block won't undo any damage we've done. So, if push_back throws
10773 * bad_alloc then you've lost the value.
10774 *
10775 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10776 * since values that changes actually bubbles to the end of the list. Using
10777 * something that has an efficient lookup and can tolerate a bit of updates
10778 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10779 * combination of RTStrCache (for sharing names and getting uniqueness into
10780 * the bargain) and hash/tree is another. */
10781 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10782 iter != mHWData->mGuestProperties.end();
10783 ++iter)
10784 if (utf8Name == iter->strName)
10785 {
10786 mHWData->mGuestProperties.erase(iter);
10787 mData->mGuestPropertiesModified = TRUE;
10788 break;
10789 }
10790 if (aValue != NULL)
10791 {
10792 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10793 mHWData->mGuestProperties.push_back(property);
10794 mData->mGuestPropertiesModified = TRUE;
10795 }
10796
10797 /*
10798 * Send a callback notification if appropriate
10799 */
10800 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10801 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
10802 RTSTR_MAX,
10803 utf8Name.c_str(),
10804 RTSTR_MAX, NULL)
10805 )
10806 {
10807 alock.leave();
10808
10809 mParent->onGuestPropertyChange(mData->mUuid,
10810 aName,
10811 aValue,
10812 aFlags);
10813 }
10814 }
10815 catch (...)
10816 {
10817 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10818 }
10819 return S_OK;
10820#else
10821 ReturnComNotImplemented();
10822#endif
10823}
10824
10825// public methods only for internal purposes
10826/////////////////////////////////////////////////////////////////////////////
10827
10828/**
10829 * Called from the client watcher thread to check for expected or unexpected
10830 * death of the client process that has a direct session to this machine.
10831 *
10832 * On Win32 and on OS/2, this method is called only when we've got the
10833 * mutex (i.e. the client has either died or terminated normally) so it always
10834 * returns @c true (the client is terminated, the session machine is
10835 * uninitialized).
10836 *
10837 * On other platforms, the method returns @c true if the client process has
10838 * terminated normally or abnormally and the session machine was uninitialized,
10839 * and @c false if the client process is still alive.
10840 *
10841 * @note Locks this object for writing.
10842 */
10843bool SessionMachine::checkForDeath()
10844{
10845 Uninit::Reason reason;
10846 bool terminated = false;
10847
10848 /* Enclose autoCaller with a block because calling uninit() from under it
10849 * will deadlock. */
10850 {
10851 AutoCaller autoCaller(this);
10852 if (!autoCaller.isOk())
10853 {
10854 /* return true if not ready, to cause the client watcher to exclude
10855 * the corresponding session from watching */
10856 LogFlowThisFunc(("Already uninitialized!\n"));
10857 return true;
10858 }
10859
10860 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10861
10862 /* Determine the reason of death: if the session state is Closing here,
10863 * everything is fine. Otherwise it means that the client did not call
10864 * OnSessionEnd() before it released the IPC semaphore. This may happen
10865 * either because the client process has abnormally terminated, or
10866 * because it simply forgot to call ISession::Close() before exiting. We
10867 * threat the latter also as an abnormal termination (see
10868 * Session::uninit() for details). */
10869 reason = mData->mSession.mState == SessionState_Unlocking ?
10870 Uninit::Normal :
10871 Uninit::Abnormal;
10872
10873#if defined(RT_OS_WINDOWS)
10874
10875 AssertMsg(mIPCSem, ("semaphore must be created"));
10876
10877 /* release the IPC mutex */
10878 ::ReleaseMutex(mIPCSem);
10879
10880 terminated = true;
10881
10882#elif defined(RT_OS_OS2)
10883
10884 AssertMsg(mIPCSem, ("semaphore must be created"));
10885
10886 /* release the IPC mutex */
10887 ::DosReleaseMutexSem(mIPCSem);
10888
10889 terminated = true;
10890
10891#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10892
10893 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10894
10895 int val = ::semctl(mIPCSem, 0, GETVAL);
10896 if (val > 0)
10897 {
10898 /* the semaphore is signaled, meaning the session is terminated */
10899 terminated = true;
10900 }
10901
10902#else
10903# error "Port me!"
10904#endif
10905
10906 } /* AutoCaller block */
10907
10908 if (terminated)
10909 uninit(reason);
10910
10911 return terminated;
10912}
10913
10914/**
10915 * @note Locks this object for reading.
10916 */
10917HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10918{
10919 LogFlowThisFunc(("\n"));
10920
10921 AutoCaller autoCaller(this);
10922 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10923
10924 ComPtr<IInternalSessionControl> directControl;
10925 {
10926 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10927 directControl = mData->mSession.mDirectControl;
10928 }
10929
10930 /* ignore notifications sent after #OnSessionEnd() is called */
10931 if (!directControl)
10932 return S_OK;
10933
10934 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10935}
10936
10937/**
10938 * @note Locks this object for reading.
10939 */
10940HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
10941 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
10942{
10943 LogFlowThisFunc(("\n"));
10944
10945 AutoCaller autoCaller(this);
10946 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10947
10948 ComPtr<IInternalSessionControl> directControl;
10949 {
10950 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10951 directControl = mData->mSession.mDirectControl;
10952 }
10953
10954 /* ignore notifications sent after #OnSessionEnd() is called */
10955 if (!directControl)
10956 return S_OK;
10957 /*
10958 * instead acting like callback we ask IVirtualBox deliver corresponding event
10959 */
10960
10961 mParent->onNatRedirectChange(getId(), ulSlot, aNatRuleRemove, aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
10962 return S_OK;
10963}
10964
10965/**
10966 * @note Locks this object for reading.
10967 */
10968HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10969{
10970 LogFlowThisFunc(("\n"));
10971
10972 AutoCaller autoCaller(this);
10973 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10974
10975 ComPtr<IInternalSessionControl> directControl;
10976 {
10977 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10978 directControl = mData->mSession.mDirectControl;
10979 }
10980
10981 /* ignore notifications sent after #OnSessionEnd() is called */
10982 if (!directControl)
10983 return S_OK;
10984
10985 return directControl->OnSerialPortChange(serialPort);
10986}
10987
10988/**
10989 * @note Locks this object for reading.
10990 */
10991HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10992{
10993 LogFlowThisFunc(("\n"));
10994
10995 AutoCaller autoCaller(this);
10996 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10997
10998 ComPtr<IInternalSessionControl> directControl;
10999 {
11000 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11001 directControl = mData->mSession.mDirectControl;
11002 }
11003
11004 /* ignore notifications sent after #OnSessionEnd() is called */
11005 if (!directControl)
11006 return S_OK;
11007
11008 return directControl->OnParallelPortChange(parallelPort);
11009}
11010
11011/**
11012 * @note Locks this object for reading.
11013 */
11014HRESULT SessionMachine::onStorageControllerChange()
11015{
11016 LogFlowThisFunc(("\n"));
11017
11018 AutoCaller autoCaller(this);
11019 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11020
11021 ComPtr<IInternalSessionControl> directControl;
11022 {
11023 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11024 directControl = mData->mSession.mDirectControl;
11025 }
11026
11027 /* ignore notifications sent after #OnSessionEnd() is called */
11028 if (!directControl)
11029 return S_OK;
11030
11031 return directControl->OnStorageControllerChange();
11032}
11033
11034/**
11035 * @note Locks this object for reading.
11036 */
11037HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11038{
11039 LogFlowThisFunc(("\n"));
11040
11041 AutoCaller autoCaller(this);
11042 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11043
11044 ComPtr<IInternalSessionControl> directControl;
11045 {
11046 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11047 directControl = mData->mSession.mDirectControl;
11048 }
11049
11050 /* ignore notifications sent after #OnSessionEnd() is called */
11051 if (!directControl)
11052 return S_OK;
11053
11054 return directControl->OnMediumChange(aAttachment, aForce);
11055}
11056
11057/**
11058 * @note Locks this object for reading.
11059 */
11060HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11061{
11062 LogFlowThisFunc(("\n"));
11063
11064 AutoCaller autoCaller(this);
11065 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11066
11067 ComPtr<IInternalSessionControl> directControl;
11068 {
11069 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11070 directControl = mData->mSession.mDirectControl;
11071 }
11072
11073 /* ignore notifications sent after #OnSessionEnd() is called */
11074 if (!directControl)
11075 return S_OK;
11076
11077 return directControl->OnCPUChange(aCPU, aRemove);
11078}
11079
11080HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11081{
11082 LogFlowThisFunc(("\n"));
11083
11084 AutoCaller autoCaller(this);
11085 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11086
11087 ComPtr<IInternalSessionControl> directControl;
11088 {
11089 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11090 directControl = mData->mSession.mDirectControl;
11091 }
11092
11093 /* ignore notifications sent after #OnSessionEnd() is called */
11094 if (!directControl)
11095 return S_OK;
11096
11097 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11098}
11099
11100/**
11101 * @note Locks this object for reading.
11102 */
11103HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11104{
11105 LogFlowThisFunc(("\n"));
11106
11107 AutoCaller autoCaller(this);
11108 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11109
11110 ComPtr<IInternalSessionControl> directControl;
11111 {
11112 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11113 directControl = mData->mSession.mDirectControl;
11114 }
11115
11116 /* ignore notifications sent after #OnSessionEnd() is called */
11117 if (!directControl)
11118 return S_OK;
11119
11120 return directControl->OnVRDEServerChange(aRestart);
11121}
11122
11123/**
11124 * @note Locks this object for reading.
11125 */
11126HRESULT SessionMachine::onUSBControllerChange()
11127{
11128 LogFlowThisFunc(("\n"));
11129
11130 AutoCaller autoCaller(this);
11131 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11132
11133 ComPtr<IInternalSessionControl> directControl;
11134 {
11135 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11136 directControl = mData->mSession.mDirectControl;
11137 }
11138
11139 /* ignore notifications sent after #OnSessionEnd() is called */
11140 if (!directControl)
11141 return S_OK;
11142
11143 return directControl->OnUSBControllerChange();
11144}
11145
11146/**
11147 * @note Locks this object for reading.
11148 */
11149HRESULT SessionMachine::onSharedFolderChange()
11150{
11151 LogFlowThisFunc(("\n"));
11152
11153 AutoCaller autoCaller(this);
11154 AssertComRCReturnRC(autoCaller.rc());
11155
11156 ComPtr<IInternalSessionControl> directControl;
11157 {
11158 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11159 directControl = mData->mSession.mDirectControl;
11160 }
11161
11162 /* ignore notifications sent after #OnSessionEnd() is called */
11163 if (!directControl)
11164 return S_OK;
11165
11166 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11167}
11168
11169/**
11170 * Returns @c true if this machine's USB controller reports it has a matching
11171 * filter for the given USB device and @c false otherwise.
11172 *
11173 * @note Caller must have requested machine read lock.
11174 */
11175bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11176{
11177 AutoCaller autoCaller(this);
11178 /* silently return if not ready -- this method may be called after the
11179 * direct machine session has been called */
11180 if (!autoCaller.isOk())
11181 return false;
11182
11183
11184#ifdef VBOX_WITH_USB
11185 switch (mData->mMachineState)
11186 {
11187 case MachineState_Starting:
11188 case MachineState_Restoring:
11189 case MachineState_TeleportingIn:
11190 case MachineState_Paused:
11191 case MachineState_Running:
11192 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11193 * elsewhere... */
11194 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11195 default: break;
11196 }
11197#else
11198 NOREF(aDevice);
11199 NOREF(aMaskedIfs);
11200#endif
11201 return false;
11202}
11203
11204/**
11205 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11206 */
11207HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11208 IVirtualBoxErrorInfo *aError,
11209 ULONG aMaskedIfs)
11210{
11211 LogFlowThisFunc(("\n"));
11212
11213 AutoCaller autoCaller(this);
11214
11215 /* This notification may happen after the machine object has been
11216 * uninitialized (the session was closed), so don't assert. */
11217 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11218
11219 ComPtr<IInternalSessionControl> directControl;
11220 {
11221 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11222 directControl = mData->mSession.mDirectControl;
11223 }
11224
11225 /* fail on notifications sent after #OnSessionEnd() is called, it is
11226 * expected by the caller */
11227 if (!directControl)
11228 return E_FAIL;
11229
11230 /* No locks should be held at this point. */
11231 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11232 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11233
11234 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11235}
11236
11237/**
11238 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11239 */
11240HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11241 IVirtualBoxErrorInfo *aError)
11242{
11243 LogFlowThisFunc(("\n"));
11244
11245 AutoCaller autoCaller(this);
11246
11247 /* This notification may happen after the machine object has been
11248 * uninitialized (the session was closed), so don't assert. */
11249 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11250
11251 ComPtr<IInternalSessionControl> directControl;
11252 {
11253 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11254 directControl = mData->mSession.mDirectControl;
11255 }
11256
11257 /* fail on notifications sent after #OnSessionEnd() is called, it is
11258 * expected by the caller */
11259 if (!directControl)
11260 return E_FAIL;
11261
11262 /* No locks should be held at this point. */
11263 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11264 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11265
11266 return directControl->OnUSBDeviceDetach(aId, aError);
11267}
11268
11269// protected methods
11270/////////////////////////////////////////////////////////////////////////////
11271
11272/**
11273 * Helper method to finalize saving the state.
11274 *
11275 * @note Must be called from under this object's lock.
11276 *
11277 * @param aRc S_OK if the snapshot has been taken successfully
11278 * @param aErrMsg human readable error message for failure
11279 *
11280 * @note Locks mParent + this objects for writing.
11281 */
11282HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
11283{
11284 LogFlowThisFuncEnter();
11285
11286 AutoCaller autoCaller(this);
11287 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11288
11289 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11290
11291 HRESULT rc = S_OK;
11292
11293 if (SUCCEEDED(aRc))
11294 {
11295 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11296
11297 /* save all VM settings */
11298 rc = saveSettings(NULL);
11299 // no need to check whether VirtualBox.xml needs saving also since
11300 // we can't have a name change pending at this point
11301 }
11302 else
11303 {
11304 /* delete the saved state file (it might have been already created) */
11305 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11306 }
11307
11308 /* notify the progress object about operation completion */
11309 Assert(mSnapshotData.mProgress);
11310 if (SUCCEEDED(aRc))
11311 mSnapshotData.mProgress->notifyComplete(S_OK);
11312 else
11313 {
11314 if (aErrMsg.length())
11315 mSnapshotData.mProgress->notifyComplete(aRc,
11316 COM_IIDOF(ISession),
11317 getComponentName(),
11318 aErrMsg.c_str());
11319 else
11320 mSnapshotData.mProgress->notifyComplete(aRc);
11321 }
11322
11323 /* clear out the temporary saved state data */
11324 mSnapshotData.mLastState = MachineState_Null;
11325 mSnapshotData.mStateFilePath.setNull();
11326 mSnapshotData.mProgress.setNull();
11327
11328 LogFlowThisFuncLeave();
11329 return rc;
11330}
11331
11332/**
11333 * Locks the attached media.
11334 *
11335 * All attached hard disks are locked for writing and DVD/floppy are locked for
11336 * reading. Parents of attached hard disks (if any) are locked for reading.
11337 *
11338 * This method also performs accessibility check of all media it locks: if some
11339 * media is inaccessible, the method will return a failure and a bunch of
11340 * extended error info objects per each inaccessible medium.
11341 *
11342 * Note that this method is atomic: if it returns a success, all media are
11343 * locked as described above; on failure no media is locked at all (all
11344 * succeeded individual locks will be undone).
11345 *
11346 * This method is intended to be called when the machine is in Starting or
11347 * Restoring state and asserts otherwise.
11348 *
11349 * The locks made by this method must be undone by calling #unlockMedia() when
11350 * no more needed.
11351 */
11352HRESULT SessionMachine::lockMedia()
11353{
11354 AutoCaller autoCaller(this);
11355 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11356
11357 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11358
11359 AssertReturn( mData->mMachineState == MachineState_Starting
11360 || mData->mMachineState == MachineState_Restoring
11361 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11362 /* bail out if trying to lock things with already set up locking */
11363 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11364
11365 MultiResult mrc(S_OK);
11366
11367 /* Collect locking information for all medium objects attached to the VM. */
11368 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11369 it != mMediaData->mAttachments.end();
11370 ++it)
11371 {
11372 MediumAttachment* pAtt = *it;
11373 DeviceType_T devType = pAtt->getType();
11374 Medium *pMedium = pAtt->getMedium();
11375
11376 MediumLockList *pMediumLockList(new MediumLockList());
11377 // There can be attachments without a medium (floppy/dvd), and thus
11378 // it's impossible to create a medium lock list. It still makes sense
11379 // to have the empty medium lock list in the map in case a medium is
11380 // attached later.
11381 if (pMedium != NULL)
11382 {
11383 MediumType_T mediumType = pMedium->getType();
11384 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
11385 || mediumType == MediumType_Shareable;
11386 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11387
11388 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11389 !fIsReadOnlyLock /* fMediumLockWrite */,
11390 NULL,
11391 *pMediumLockList);
11392 if (FAILED(mrc))
11393 {
11394 delete pMediumLockList;
11395 mData->mSession.mLockedMedia.Clear();
11396 break;
11397 }
11398 }
11399
11400 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11401 if (FAILED(rc))
11402 {
11403 mData->mSession.mLockedMedia.Clear();
11404 mrc = setError(rc,
11405 tr("Collecting locking information for all attached media failed"));
11406 break;
11407 }
11408 }
11409
11410 if (SUCCEEDED(mrc))
11411 {
11412 /* Now lock all media. If this fails, nothing is locked. */
11413 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11414 if (FAILED(rc))
11415 {
11416 mrc = setError(rc,
11417 tr("Locking of attached media failed"));
11418 }
11419 }
11420
11421 return mrc;
11422}
11423
11424/**
11425 * Undoes the locks made by by #lockMedia().
11426 */
11427void SessionMachine::unlockMedia()
11428{
11429 AutoCaller autoCaller(this);
11430 AssertComRCReturnVoid(autoCaller.rc());
11431
11432 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11433
11434 /* we may be holding important error info on the current thread;
11435 * preserve it */
11436 ErrorInfoKeeper eik;
11437
11438 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11439 AssertComRC(rc);
11440}
11441
11442/**
11443 * Helper to change the machine state (reimplementation).
11444 *
11445 * @note Locks this object for writing.
11446 */
11447HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11448{
11449 LogFlowThisFuncEnter();
11450 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11451
11452 AutoCaller autoCaller(this);
11453 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11454
11455 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11456
11457 MachineState_T oldMachineState = mData->mMachineState;
11458
11459 AssertMsgReturn(oldMachineState != aMachineState,
11460 ("oldMachineState=%s, aMachineState=%s\n",
11461 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11462 E_FAIL);
11463
11464 HRESULT rc = S_OK;
11465
11466 int stsFlags = 0;
11467 bool deleteSavedState = false;
11468
11469 /* detect some state transitions */
11470
11471 if ( ( oldMachineState == MachineState_Saved
11472 && aMachineState == MachineState_Restoring)
11473 || ( ( oldMachineState == MachineState_PoweredOff
11474 || oldMachineState == MachineState_Teleported
11475 || oldMachineState == MachineState_Aborted
11476 )
11477 && ( aMachineState == MachineState_TeleportingIn
11478 || aMachineState == MachineState_Starting
11479 )
11480 )
11481 )
11482 {
11483 /* The EMT thread is about to start */
11484
11485 /* Nothing to do here for now... */
11486
11487 /// @todo NEWMEDIA don't let mDVDDrive and other children
11488 /// change anything when in the Starting/Restoring state
11489 }
11490 else if ( ( oldMachineState == MachineState_Running
11491 || oldMachineState == MachineState_Paused
11492 || oldMachineState == MachineState_Teleporting
11493 || oldMachineState == MachineState_LiveSnapshotting
11494 || oldMachineState == MachineState_Stuck
11495 || oldMachineState == MachineState_Starting
11496 || oldMachineState == MachineState_Stopping
11497 || oldMachineState == MachineState_Saving
11498 || oldMachineState == MachineState_Restoring
11499 || oldMachineState == MachineState_TeleportingPausedVM
11500 || oldMachineState == MachineState_TeleportingIn
11501 )
11502 && ( aMachineState == MachineState_PoweredOff
11503 || aMachineState == MachineState_Saved
11504 || aMachineState == MachineState_Teleported
11505 || aMachineState == MachineState_Aborted
11506 )
11507 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11508 * snapshot */
11509 && ( mSnapshotData.mSnapshot.isNull()
11510 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11511 )
11512 )
11513 {
11514 /* The EMT thread has just stopped, unlock attached media. Note that as
11515 * opposed to locking that is done from Console, we do unlocking here
11516 * because the VM process may have aborted before having a chance to
11517 * properly unlock all media it locked. */
11518
11519 unlockMedia();
11520 }
11521
11522 if (oldMachineState == MachineState_Restoring)
11523 {
11524 if (aMachineState != MachineState_Saved)
11525 {
11526 /*
11527 * delete the saved state file once the machine has finished
11528 * restoring from it (note that Console sets the state from
11529 * Restoring to Saved if the VM couldn't restore successfully,
11530 * to give the user an ability to fix an error and retry --
11531 * we keep the saved state file in this case)
11532 */
11533 deleteSavedState = true;
11534 }
11535 }
11536 else if ( oldMachineState == MachineState_Saved
11537 && ( aMachineState == MachineState_PoweredOff
11538 || aMachineState == MachineState_Aborted
11539 || aMachineState == MachineState_Teleported
11540 )
11541 )
11542 {
11543 /*
11544 * delete the saved state after Console::ForgetSavedState() is called
11545 * or if the VM process (owning a direct VM session) crashed while the
11546 * VM was Saved
11547 */
11548
11549 /// @todo (dmik)
11550 // Not sure that deleting the saved state file just because of the
11551 // client death before it attempted to restore the VM is a good
11552 // thing. But when it crashes we need to go to the Aborted state
11553 // which cannot have the saved state file associated... The only
11554 // way to fix this is to make the Aborted condition not a VM state
11555 // but a bool flag: i.e., when a crash occurs, set it to true and
11556 // change the state to PoweredOff or Saved depending on the
11557 // saved state presence.
11558
11559 deleteSavedState = true;
11560 mData->mCurrentStateModified = TRUE;
11561 stsFlags |= SaveSTS_CurStateModified;
11562 }
11563
11564 if ( aMachineState == MachineState_Starting
11565 || aMachineState == MachineState_Restoring
11566 || aMachineState == MachineState_TeleportingIn
11567 )
11568 {
11569 /* set the current state modified flag to indicate that the current
11570 * state is no more identical to the state in the
11571 * current snapshot */
11572 if (!mData->mCurrentSnapshot.isNull())
11573 {
11574 mData->mCurrentStateModified = TRUE;
11575 stsFlags |= SaveSTS_CurStateModified;
11576 }
11577 }
11578
11579 if (deleteSavedState)
11580 {
11581 if (mRemoveSavedState)
11582 {
11583 Assert(!mSSData->mStateFilePath.isEmpty());
11584 RTFileDelete(mSSData->mStateFilePath.c_str());
11585 }
11586 mSSData->mStateFilePath.setNull();
11587 stsFlags |= SaveSTS_StateFilePath;
11588 }
11589
11590 /* redirect to the underlying peer machine */
11591 mPeer->setMachineState(aMachineState);
11592
11593 if ( aMachineState == MachineState_PoweredOff
11594 || aMachineState == MachineState_Teleported
11595 || aMachineState == MachineState_Aborted
11596 || aMachineState == MachineState_Saved)
11597 {
11598 /* the machine has stopped execution
11599 * (or the saved state file was adopted) */
11600 stsFlags |= SaveSTS_StateTimeStamp;
11601 }
11602
11603 if ( ( oldMachineState == MachineState_PoweredOff
11604 || oldMachineState == MachineState_Aborted
11605 || oldMachineState == MachineState_Teleported
11606 )
11607 && aMachineState == MachineState_Saved)
11608 {
11609 /* the saved state file was adopted */
11610 Assert(!mSSData->mStateFilePath.isEmpty());
11611 stsFlags |= SaveSTS_StateFilePath;
11612 }
11613
11614#ifdef VBOX_WITH_GUEST_PROPS
11615 if ( aMachineState == MachineState_PoweredOff
11616 || aMachineState == MachineState_Aborted
11617 || aMachineState == MachineState_Teleported)
11618 {
11619 /* Make sure any transient guest properties get removed from the
11620 * property store on shutdown. */
11621
11622 HWData::GuestPropertyList::iterator it;
11623 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11624 if (!fNeedsSaving)
11625 for (it = mHWData->mGuestProperties.begin();
11626 it != mHWData->mGuestProperties.end(); ++it)
11627 if (it->mFlags & guestProp::TRANSIENT)
11628 {
11629 fNeedsSaving = true;
11630 break;
11631 }
11632 if (fNeedsSaving)
11633 {
11634 mData->mCurrentStateModified = TRUE;
11635 stsFlags |= SaveSTS_CurStateModified;
11636 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11637 }
11638 }
11639#endif
11640
11641 rc = saveStateSettings(stsFlags);
11642
11643 if ( ( oldMachineState != MachineState_PoweredOff
11644 && oldMachineState != MachineState_Aborted
11645 && oldMachineState != MachineState_Teleported
11646 )
11647 && ( aMachineState == MachineState_PoweredOff
11648 || aMachineState == MachineState_Aborted
11649 || aMachineState == MachineState_Teleported
11650 )
11651 )
11652 {
11653 /* we've been shut down for any reason */
11654 /* no special action so far */
11655 }
11656
11657 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11658 LogFlowThisFuncLeave();
11659 return rc;
11660}
11661
11662/**
11663 * Sends the current machine state value to the VM process.
11664 *
11665 * @note Locks this object for reading, then calls a client process.
11666 */
11667HRESULT SessionMachine::updateMachineStateOnClient()
11668{
11669 AutoCaller autoCaller(this);
11670 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11671
11672 ComPtr<IInternalSessionControl> directControl;
11673 {
11674 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11675 AssertReturn(!!mData, E_FAIL);
11676 directControl = mData->mSession.mDirectControl;
11677
11678 /* directControl may be already set to NULL here in #OnSessionEnd()
11679 * called too early by the direct session process while there is still
11680 * some operation (like deleting the snapshot) in progress. The client
11681 * process in this case is waiting inside Session::close() for the
11682 * "end session" process object to complete, while #uninit() called by
11683 * #checkForDeath() on the Watcher thread is waiting for the pending
11684 * operation to complete. For now, we accept this inconsistent behavior
11685 * and simply do nothing here. */
11686
11687 if (mData->mSession.mState == SessionState_Unlocking)
11688 return S_OK;
11689
11690 AssertReturn(!directControl.isNull(), E_FAIL);
11691 }
11692
11693 return directControl->UpdateMachineState(mData->mMachineState);
11694}
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