VirtualBox

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

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

Main/Machine: yet another %ls/%s mixup

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

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