VirtualBox

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

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

Main: merge IVirtualBox::FindHardDisk, GetHardDisk, FindDVDImage, GetDVDImage, FindFloppyImage and GetFloppyImage into one IVirtualBox::findMedium method

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