VirtualBox

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

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

Main: fix crash taking/restoring snapshot (regression from last week's media changes)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 374.6 KB
Line 
1/* $Id: MachineImpl.cpp 31683 2010-08-16 09:39:00Z 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 IMedium *aMedium)
3100{
3101 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aType=%d aId=\"%ls\"\n",
3102 aControllerName, aControllerPort, aDevice, aType, aMedium));
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 fNeedsGlobalSaveSettings = 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 ComObjPtr<Medium> medium = static_cast<Medium*>(aMedium);
3168 if (aMedium && medium.isNull())
3169 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3170
3171 AutoCaller mediumCaller(medium);
3172 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3173
3174 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3175
3176 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
3177 && !medium.isNull()
3178 )
3179 return setError(VBOX_E_OBJECT_IN_USE,
3180 tr("Medium '%s' is already attached to this virtual machine"),
3181 medium->getLocationFull().c_str());
3182
3183 bool fIndirect = false;
3184 if (!medium.isNull())
3185 fIndirect = medium->isReadOnly();
3186 bool associate = true;
3187
3188 do
3189 {
3190 if ( aType == DeviceType_HardDisk
3191 && mMediaData.isBackedUp())
3192 {
3193 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3194
3195 /* check if the medium was attached to the VM before we started
3196 * changing attachments in which case the attachment just needs to
3197 * be restored */
3198 if ((pAttachTemp = findAttachment(oldAtts, medium)))
3199 {
3200 AssertReturn(!fIndirect, E_FAIL);
3201
3202 /* see if it's the same bus/channel/device */
3203 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
3204 {
3205 /* the simplest case: restore the whole attachment
3206 * and return, nothing else to do */
3207 mMediaData->mAttachments.push_back(pAttachTemp);
3208 return S_OK;
3209 }
3210
3211 /* bus/channel/device differ; we need a new attachment object,
3212 * but don't try to associate it again */
3213 associate = false;
3214 break;
3215 }
3216 }
3217
3218 /* go further only if the attachment is to be indirect */
3219 if (!fIndirect)
3220 break;
3221
3222 /* perform the so called smart attachment logic for indirect
3223 * attachments. Note that smart attachment is only applicable to base
3224 * hard disks. */
3225
3226 if (medium->getParent().isNull())
3227 {
3228 /* first, investigate the backup copy of the current hard disk
3229 * attachments to make it possible to re-attach existing diffs to
3230 * another device slot w/o losing their contents */
3231 if (mMediaData.isBackedUp())
3232 {
3233 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3234
3235 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
3236 uint32_t foundLevel = 0;
3237
3238 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
3239 it != oldAtts.end();
3240 ++it)
3241 {
3242 uint32_t level = 0;
3243 MediumAttachment *pAttach = *it;
3244 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3245 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3246 if (pMedium.isNull())
3247 continue;
3248
3249 if (pMedium->getBase(&level) == medium)
3250 {
3251 /* skip the hard disk if its currently attached (we
3252 * cannot attach the same hard disk twice) */
3253 if (findAttachment(mMediaData->mAttachments,
3254 pMedium))
3255 continue;
3256
3257 /* matched device, channel and bus (i.e. attached to the
3258 * same place) will win and immediately stop the search;
3259 * otherwise the attachment that has the youngest
3260 * descendant of medium will be used
3261 */
3262 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
3263 {
3264 /* the simplest case: restore the whole attachment
3265 * and return, nothing else to do */
3266 mMediaData->mAttachments.push_back(*it);
3267 return S_OK;
3268 }
3269 else if ( foundIt == oldAtts.end()
3270 || level > foundLevel /* prefer younger */
3271 )
3272 {
3273 foundIt = it;
3274 foundLevel = level;
3275 }
3276 }
3277 }
3278
3279 if (foundIt != oldAtts.end())
3280 {
3281 /* use the previously attached hard disk */
3282 medium = (*foundIt)->getMedium();
3283 mediumCaller.attach(medium);
3284 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3285 mediumLock.attach(medium);
3286 /* not implicit, doesn't require association with this VM */
3287 fIndirect = false;
3288 associate = false;
3289 /* go right to the MediumAttachment creation */
3290 break;
3291 }
3292 }
3293
3294 /* must give up the medium lock and medium tree lock as below we
3295 * go over snapshots, which needs a lock with higher lock order. */
3296 mediumLock.release();
3297 treeLock.release();
3298
3299 /* then, search through snapshots for the best diff in the given
3300 * hard disk's chain to base the new diff on */
3301
3302 ComObjPtr<Medium> base;
3303 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
3304 while (snap)
3305 {
3306 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
3307
3308 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
3309
3310 MediumAttachment *pAttachFound = NULL;
3311 uint32_t foundLevel = 0;
3312
3313 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
3314 it != snapAtts.end();
3315 ++it)
3316 {
3317 MediumAttachment *pAttach = *it;
3318 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3319 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3320 if (pMedium.isNull())
3321 continue;
3322
3323 uint32_t level = 0;
3324 if (pMedium->getBase(&level) == medium)
3325 {
3326 /* matched device, channel and bus (i.e. attached to the
3327 * same place) will win and immediately stop the search;
3328 * otherwise the attachment that has the youngest
3329 * descendant of medium will be used
3330 */
3331 if ( pAttach->getDevice() == aDevice
3332 && pAttach->getPort() == aControllerPort
3333 && pAttach->getControllerName() == aControllerName
3334 )
3335 {
3336 pAttachFound = pAttach;
3337 break;
3338 }
3339 else if ( !pAttachFound
3340 || level > foundLevel /* prefer younger */
3341 )
3342 {
3343 pAttachFound = pAttach;
3344 foundLevel = level;
3345 }
3346 }
3347 }
3348
3349 if (pAttachFound)
3350 {
3351 base = pAttachFound->getMedium();
3352 break;
3353 }
3354
3355 snap = snap->getParent();
3356 }
3357
3358 /* re-lock medium tree and the medium, as we need it below */
3359 treeLock.acquire();
3360 mediumLock.acquire();
3361
3362 /* found a suitable diff, use it as a base */
3363 if (!base.isNull())
3364 {
3365 medium = base;
3366 mediumCaller.attach(medium);
3367 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3368 mediumLock.attach(medium);
3369 }
3370 }
3371
3372 ComObjPtr<Medium> diff;
3373 diff.createObject();
3374 rc = diff->init(mParent,
3375 medium->getPreferredDiffFormat(),
3376 Utf8Str(mUserData->m_strSnapshotFolderFull).append(RTPATH_SLASH_STR),
3377 medium->getRegistryMachineId(), // store this diff in the same registry as the parent
3378 &fNeedsGlobalSaveSettings);
3379 if (FAILED(rc)) return rc;
3380
3381 /* Apply the normal locking logic to the entire chain. */
3382 MediumLockList *pMediumLockList(new MediumLockList());
3383 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
3384 true /* fMediumLockWrite */,
3385 medium,
3386 *pMediumLockList);
3387 if (SUCCEEDED(rc))
3388 {
3389 rc = pMediumLockList->Lock();
3390 if (FAILED(rc))
3391 setError(rc,
3392 tr("Could not lock medium when creating diff '%s'"),
3393 diff->getLocationFull().c_str());
3394 else
3395 {
3396 /* will leave the lock before the potentially lengthy operation, so
3397 * protect with the special state */
3398 MachineState_T oldState = mData->mMachineState;
3399 setMachineState(MachineState_SettingUp);
3400
3401 mediumLock.leave();
3402 treeLock.leave();
3403 alock.leave();
3404
3405 rc = medium->createDiffStorage(diff,
3406 MediumVariant_Standard,
3407 pMediumLockList,
3408 NULL /* aProgress */,
3409 true /* aWait */,
3410 &fNeedsGlobalSaveSettings);
3411
3412 alock.enter();
3413 treeLock.enter();
3414 mediumLock.enter();
3415
3416 setMachineState(oldState);
3417 }
3418 }
3419
3420 /* Unlock the media and free the associated memory. */
3421 delete pMediumLockList;
3422
3423 if (FAILED(rc)) return rc;
3424
3425 /* use the created diff for the actual attachment */
3426 medium = diff;
3427 mediumCaller.attach(medium);
3428 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3429 mediumLock.attach(medium);
3430 }
3431 while (0);
3432
3433 ComObjPtr<MediumAttachment> attachment;
3434 attachment.createObject();
3435 rc = attachment->init(this,
3436 medium,
3437 aControllerName,
3438 aControllerPort,
3439 aDevice,
3440 aType,
3441 fIndirect,
3442 0 /* No bandwidth limit */);
3443 if (FAILED(rc)) return rc;
3444
3445 if (associate && !medium.isNull())
3446 {
3447 // as the last step, associate the medium to the VM
3448 rc = medium->addBackReference(mData->mUuid);
3449 // here we can fail because of Deleting, or being in process of creating a Diff
3450 if (FAILED(rc)) return rc;
3451
3452 // and decide which medium registry to use now that the medium is attached:
3453 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
3454 medium->setRegistryIdIfFirst(getId()); // machine UUID
3455 else
3456 medium->setRegistryIdIfFirst(mParent->getGlobalRegistryId()); // VirtualBox global registry UUID
3457 }
3458
3459 /* success: finally remember the attachment */
3460 setModified(IsModified_Storage);
3461 mMediaData.backup();
3462 mMediaData->mAttachments.push_back(attachment);
3463
3464 if (fNeedsGlobalSaveSettings)
3465 {
3466 // save the global settings; for that we should hold only the VirtualBox lock
3467 mediumLock.release();
3468 treeLock.leave();
3469 alock.release();
3470
3471 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
3472 mParent->saveSettings();
3473 }
3474
3475 return rc;
3476}
3477
3478STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
3479 LONG aDevice)
3480{
3481 CheckComArgStrNotEmptyOrNull(aControllerName);
3482
3483 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3484 aControllerName, aControllerPort, aDevice));
3485
3486 AutoCaller autoCaller(this);
3487 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3488
3489 bool fNeedsSaveSettings = false;
3490
3491 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3492
3493 HRESULT rc = checkStateDependency(MutableStateDep);
3494 if (FAILED(rc)) return rc;
3495
3496 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3497
3498 if (Global::IsOnlineOrTransient(mData->mMachineState))
3499 return setError(VBOX_E_INVALID_VM_STATE,
3500 tr("Invalid machine state: %s"),
3501 Global::stringifyMachineState(mData->mMachineState));
3502
3503 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3504 aControllerName,
3505 aControllerPort,
3506 aDevice);
3507 if (!pAttach)
3508 return setError(VBOX_E_OBJECT_NOT_FOUND,
3509 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3510 aDevice, aControllerPort, aControllerName);
3511
3512 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */, &fNeedsSaveSettings);
3513
3514 if (fNeedsSaveSettings)
3515 {
3516 bool fNeedsGlobalSaveSettings = false;
3517 saveSettings(&fNeedsGlobalSaveSettings);
3518
3519 if (fNeedsGlobalSaveSettings)
3520 {
3521 // save the global settings; for that we should hold only the VirtualBox lock
3522 alock.release();
3523 AutoWriteLock vboxlock(this COMMA_LOCKVAL_SRC_POS);
3524 mParent->saveSettings();
3525 }
3526 }
3527
3528 return S_OK;
3529}
3530
3531STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
3532 LONG aDevice, BOOL aPassthrough)
3533{
3534 CheckComArgStrNotEmptyOrNull(aControllerName);
3535
3536 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aPassthrough=%d\n",
3537 aControllerName, aControllerPort, aDevice, aPassthrough));
3538
3539 AutoCaller autoCaller(this);
3540 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3541
3542 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3543
3544 HRESULT rc = checkStateDependency(MutableStateDep);
3545 if (FAILED(rc)) return rc;
3546
3547 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3548
3549 if (Global::IsOnlineOrTransient(mData->mMachineState))
3550 return setError(VBOX_E_INVALID_VM_STATE,
3551 tr("Invalid machine state: %s"),
3552 Global::stringifyMachineState(mData->mMachineState));
3553
3554 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3555 aControllerName,
3556 aControllerPort,
3557 aDevice);
3558 if (!pAttach)
3559 return setError(VBOX_E_OBJECT_NOT_FOUND,
3560 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3561 aDevice, aControllerPort, aControllerName);
3562
3563
3564 setModified(IsModified_Storage);
3565 mMediaData.backup();
3566
3567 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3568
3569 if (pAttach->getType() != DeviceType_DVD)
3570 return setError(E_INVALIDARG,
3571 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3572 aDevice, aControllerPort, aControllerName);
3573 pAttach->updatePassthrough(!!aPassthrough);
3574
3575 return S_OK;
3576}
3577
3578STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
3579 LONG aControllerPort,
3580 LONG aDevice,
3581 IN_BSTR aId,
3582 BOOL aForce)
3583{
3584 int rc = S_OK;
3585 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aForce=%d\n",
3586 aControllerName, aControllerPort, aDevice, aForce));
3587
3588 CheckComArgStrNotEmptyOrNull(aControllerName);
3589
3590 AutoCaller autoCaller(this);
3591 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3592
3593 // we're calling host methods for getting DVD and floppy drives so lock host first
3594 AutoMultiWriteLock2 alock(mParent->host(), this COMMA_LOCKVAL_SRC_POS);
3595
3596 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3597 aControllerName,
3598 aControllerPort,
3599 aDevice);
3600 if (pAttach.isNull())
3601 return setError(VBOX_E_OBJECT_NOT_FOUND,
3602 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
3603 aDevice, aControllerPort, aControllerName);
3604
3605 /* Remember previously mounted medium. The medium before taking the
3606 * backup is not necessarily the same thing. */
3607 ComObjPtr<Medium> oldmedium;
3608 oldmedium = pAttach->getMedium();
3609
3610 Guid uuid(aId);
3611 ComObjPtr<Medium> medium;
3612 DeviceType_T mediumType = pAttach->getType();
3613 switch (mediumType)
3614 {
3615 case DeviceType_DVD:
3616 case DeviceType_Floppy:
3617 rc = mParent->findRemoveableMedium(mediumType, uuid, true /* fRefresh */, medium);
3618 if (FAILED(rc)) return rc;
3619 break;
3620
3621 default:
3622 return setError(VBOX_E_INVALID_OBJECT_STATE,
3623 tr("Cannot change medium attached to device slot %d on port %d of controller '%ls'"),
3624 aDevice, aControllerPort, aControllerName);
3625 }
3626
3627 if (SUCCEEDED(rc))
3628 {
3629 setModified(IsModified_Storage);
3630 mMediaData.backup();
3631
3632 /* The backup operation makes the pAttach reference point to the
3633 * old settings. Re-get the correct reference. */
3634 pAttach = findAttachment(mMediaData->mAttachments,
3635 aControllerName,
3636 aControllerPort,
3637 aDevice);
3638 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3639 /* For non-hard disk media, detach straight away. */
3640 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
3641 oldmedium->removeBackReference(mData->mUuid);
3642 if (!medium.isNull())
3643 medium->addBackReference(mData->mUuid);
3644 pAttach->updateMedium(medium, false /* aImplicit */);
3645 setModified(IsModified_Storage);
3646 }
3647
3648 alock.leave();
3649 rc = onMediumChange(pAttach, aForce);
3650 alock.enter();
3651
3652 /* On error roll back this change only. */
3653 if (FAILED(rc))
3654 {
3655 if (!medium.isNull())
3656 medium->removeBackReference(mData->mUuid);
3657 pAttach = findAttachment(mMediaData->mAttachments,
3658 aControllerName,
3659 aControllerPort,
3660 aDevice);
3661 /* If the attachment is gone in the mean time, bail out. */
3662 if (pAttach.isNull())
3663 return rc;
3664 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3665 /* For non-hard disk media, re-attach straight away. */
3666 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
3667 oldmedium->addBackReference(mData->mUuid);
3668 pAttach->updateMedium(oldmedium, false /* aImplicit */);
3669 }
3670
3671 return rc;
3672}
3673
3674STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
3675 LONG aControllerPort,
3676 LONG aDevice,
3677 IMedium **aMedium)
3678{
3679 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3680 aControllerName, aControllerPort, aDevice));
3681
3682 CheckComArgStrNotEmptyOrNull(aControllerName);
3683 CheckComArgOutPointerValid(aMedium);
3684
3685 AutoCaller autoCaller(this);
3686 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3687
3688 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3689
3690 *aMedium = NULL;
3691
3692 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3693 aControllerName,
3694 aControllerPort,
3695 aDevice);
3696 if (pAttach.isNull())
3697 return setError(VBOX_E_OBJECT_NOT_FOUND,
3698 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3699 aDevice, aControllerPort, aControllerName);
3700
3701 pAttach->getMedium().queryInterfaceTo(aMedium);
3702
3703 return S_OK;
3704}
3705
3706STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
3707{
3708 CheckComArgOutPointerValid(port);
3709 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
3710
3711 AutoCaller autoCaller(this);
3712 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3713
3714 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3715
3716 mSerialPorts[slot].queryInterfaceTo(port);
3717
3718 return S_OK;
3719}
3720
3721STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
3722{
3723 CheckComArgOutPointerValid(port);
3724 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
3725
3726 AutoCaller autoCaller(this);
3727 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3728
3729 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3730
3731 mParallelPorts[slot].queryInterfaceTo(port);
3732
3733 return S_OK;
3734}
3735
3736STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
3737{
3738 CheckComArgOutPointerValid(adapter);
3739 CheckComArgExpr(slot, slot < RT_ELEMENTS(mNetworkAdapters));
3740
3741 AutoCaller autoCaller(this);
3742 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3743
3744 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3745
3746 mNetworkAdapters[slot].queryInterfaceTo(adapter);
3747
3748 return S_OK;
3749}
3750
3751STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
3752{
3753 if (ComSafeArrayOutIsNull(aKeys))
3754 return E_POINTER;
3755
3756 AutoCaller autoCaller(this);
3757 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3758
3759 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3760
3761 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
3762 int i = 0;
3763 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
3764 it != mData->pMachineConfigFile->mapExtraDataItems.end();
3765 ++it, ++i)
3766 {
3767 const Utf8Str &strKey = it->first;
3768 strKey.cloneTo(&saKeys[i]);
3769 }
3770 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
3771
3772 return S_OK;
3773 }
3774
3775 /**
3776 * @note Locks this object for reading.
3777 */
3778STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
3779 BSTR *aValue)
3780{
3781 CheckComArgStrNotEmptyOrNull(aKey);
3782 CheckComArgOutPointerValid(aValue);
3783
3784 AutoCaller autoCaller(this);
3785 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3786
3787 /* start with nothing found */
3788 Bstr bstrResult("");
3789
3790 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3791
3792 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
3793 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
3794 // found:
3795 bstrResult = it->second; // source is a Utf8Str
3796
3797 /* return the result to caller (may be empty) */
3798 bstrResult.cloneTo(aValue);
3799
3800 return S_OK;
3801}
3802
3803 /**
3804 * @note Locks mParent for writing + this object for writing.
3805 */
3806STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
3807{
3808 CheckComArgStrNotEmptyOrNull(aKey);
3809
3810 AutoCaller autoCaller(this);
3811 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3812
3813 Utf8Str strKey(aKey);
3814 Utf8Str strValue(aValue);
3815 Utf8Str strOldValue; // empty
3816
3817 // locking note: we only hold the read lock briefly to look up the old value,
3818 // then release it and call the onExtraCanChange callbacks. There is a small
3819 // chance of a race insofar as the callback might be called twice if two callers
3820 // change the same key at the same time, but that's a much better solution
3821 // than the deadlock we had here before. The actual changing of the extradata
3822 // is then performed under the write lock and race-free.
3823
3824 // look up the old value first; if nothing's changed then we need not do anything
3825 {
3826 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
3827 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
3828 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
3829 strOldValue = it->second;
3830 }
3831
3832 bool fChanged;
3833 if ((fChanged = (strOldValue != strValue)))
3834 {
3835 // ask for permission from all listeners outside the locks;
3836 // onExtraDataCanChange() only briefly requests the VirtualBox
3837 // lock to copy the list of callbacks to invoke
3838 Bstr error;
3839 Bstr bstrValue(aValue);
3840
3841 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue, error))
3842 {
3843 const char *sep = error.isEmpty() ? "" : ": ";
3844 CBSTR err = error.raw();
3845 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
3846 sep, err));
3847 return setError(E_ACCESSDENIED,
3848 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
3849 aKey,
3850 bstrValue.raw(),
3851 sep,
3852 err);
3853 }
3854
3855 // data is changing and change not vetoed: then write it out under the lock
3856 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3857
3858 if (isSnapshotMachine())
3859 {
3860 HRESULT rc = checkStateDependency(MutableStateDep);
3861 if (FAILED(rc)) return rc;
3862 }
3863
3864 if (strValue.isEmpty())
3865 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
3866 else
3867 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
3868 // creates a new key if needed
3869
3870 bool fNeedsGlobalSaveSettings = false;
3871 saveSettings(&fNeedsGlobalSaveSettings);
3872
3873 if (fNeedsGlobalSaveSettings)
3874 {
3875 // save the global settings; for that we should hold only the VirtualBox lock
3876 alock.release();
3877 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
3878 mParent->saveSettings();
3879 }
3880 }
3881
3882 // fire notification outside the lock
3883 if (fChanged)
3884 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
3885
3886 return S_OK;
3887}
3888
3889STDMETHODIMP Machine::SaveSettings()
3890{
3891 AutoCaller autoCaller(this);
3892 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3893
3894 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
3895
3896 /* when there was auto-conversion, we want to save the file even if
3897 * the VM is saved */
3898 HRESULT rc = checkStateDependency(MutableStateDep);
3899 if (FAILED(rc)) return rc;
3900
3901 /* the settings file path may never be null */
3902 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
3903
3904 /* save all VM data excluding snapshots */
3905 bool fNeedsGlobalSaveSettings = false;
3906 rc = saveSettings(&fNeedsGlobalSaveSettings);
3907 mlock.release();
3908
3909 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
3910 {
3911 // save the global settings; for that we should hold only the VirtualBox lock
3912 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
3913 rc = mParent->saveSettings();
3914 }
3915
3916 return rc;
3917}
3918
3919STDMETHODIMP Machine::DiscardSettings()
3920{
3921 AutoCaller autoCaller(this);
3922 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3923
3924 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3925
3926 HRESULT rc = checkStateDependency(MutableStateDep);
3927 if (FAILED(rc)) return rc;
3928
3929 /*
3930 * during this rollback, the session will be notified if data has
3931 * been actually changed
3932 */
3933 rollback(true /* aNotify */);
3934
3935 return S_OK;
3936}
3937
3938/** @note Locks objects! */
3939STDMETHODIMP Machine::Unregister(CleanupMode_T cleanupMode,
3940 ComSafeArrayOut(IMedium*, aMedia))
3941{
3942 // use AutoLimitedCaller because this call is valid on inaccessible machines as well
3943 AutoLimitedCaller autoCaller(this);
3944 AssertComRCReturnRC(autoCaller.rc());
3945
3946 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3947
3948 Guid id(getId());
3949
3950 if (mData->mSession.mState != SessionState_Unlocked)
3951 return setError(VBOX_E_INVALID_OBJECT_STATE,
3952 tr("Cannot unregister the machine '%s' while it is locked"),
3953 mUserData->s.strName.c_str());
3954
3955 // wait for state dependants to drop to zero
3956 ensureNoStateDependencies();
3957
3958 if (!mData->mAccessible)
3959 {
3960 // inaccessible maschines can only be unregistered; uninitialize ourselves
3961 // here because currently there may be no unregistered that are inaccessible
3962 // (this state combination is not supported). Note releasing the caller and
3963 // leaving the lock before alling uninit()
3964 alock.leave();
3965 autoCaller.release();
3966
3967 uninit();
3968
3969 mParent->unregisterMachine(this, id);
3970 // calls VirtualBox::saveSettings()
3971
3972 return S_OK;
3973 }
3974
3975 HRESULT rc = S_OK;
3976
3977 // discard saved state
3978 if (mData->mMachineState == MachineState_Saved)
3979 {
3980 // add the saved state file to the list of files the caller should delete
3981 Assert(!mSSData->mStateFilePath.isEmpty());
3982 mData->llFilesToDelete.push_back(mSSData->mStateFilePath);
3983
3984 mSSData->mStateFilePath.setNull();
3985
3986 // unconditionally set the machine state to powered off, we now
3987 // know no session has locked the machine
3988 mData->mMachineState = MachineState_PoweredOff;
3989 }
3990
3991 size_t cSnapshots = 0;
3992 if (mData->mFirstSnapshot)
3993 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
3994 if (cSnapshots && cleanupMode == CleanupMode_UnregisterOnly)
3995 // fail now before we start detaching media
3996 return setError(VBOX_E_INVALID_OBJECT_STATE,
3997 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
3998 mUserData->s.strName.c_str(), cSnapshots);
3999
4000 // this list collects the medium objects from all medium attachments
4001 // which got detached from the machine and its snapshots, in the following
4002 // order:
4003 // 1) media from machine attachments (these have the "leaf" attachments with snapshots
4004 // and must be closed first, or closing the parents will fail because they will
4005 // children);
4006 // 2) media from the youngest snapshots followed those from the parent snapshots until
4007 // the root ("first") snapshot of the machine
4008 // This order allows for closing the media on this list from the beginning to the end
4009 // without getting "media in use" errors.
4010 MediaList llMedia;
4011
4012 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4013 && mMediaData->mAttachments.size()
4014 )
4015 {
4016 // we have media attachments: detach them all and add the Medium objects to our list
4017 if (cleanupMode != CleanupMode_UnregisterOnly)
4018 detachAllMedia(alock, NULL /* pSnapshot */, cleanupMode, llMedia);
4019 else
4020 return setError(VBOX_E_INVALID_OBJECT_STATE,
4021 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
4022 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
4023 }
4024
4025 if (cSnapshots)
4026 {
4027 // autoCleanup must be true here, or we would have failed above
4028
4029 // add the media from the medium attachments of the snapshots to llMedia
4030 // as well, after the "main" machine media; Snapshot::uninitRecursively()
4031 // calls Machine::detachAllMedia() for the snapshot machine, recursing
4032 // into the children first
4033
4034 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
4035 MachineState_T oldState = mData->mMachineState;
4036 mData->mMachineState = MachineState_DeletingSnapshot;
4037
4038 // make a copy of the first snapshot so the refcount does not drop to 0
4039 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
4040 // because of the AutoCaller voodoo)
4041 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
4042
4043 // GO!
4044 pFirstSnapshot->uninitRecursively(alock, cleanupMode, llMedia, mData->llFilesToDelete);
4045
4046 mData->mMachineState = oldState;
4047 }
4048
4049 if (FAILED(rc))
4050 {
4051 rollbackMedia();
4052 return rc;
4053 }
4054
4055 // commit all the media changes made above
4056 commitMedia();
4057
4058 mData->mRegistered = false;
4059
4060 // machine lock no longer needed
4061 alock.release();
4062
4063 // return media to caller
4064 SafeIfaceArray<IMedium> sfaMedia(llMedia);
4065 sfaMedia.detachTo(ComSafeArrayOutArg(aMedia));
4066
4067 mParent->unregisterMachine(this, id);
4068 // calls VirtualBox::saveSettings()
4069
4070 return S_OK;
4071}
4072
4073struct Machine::DeleteTask
4074{
4075 ComObjPtr<Machine> pMachine;
4076 std::list<Utf8Str> llFilesToDelete;
4077 ComObjPtr<Progress> pProgress;
4078 bool fNeedsGlobalSaveSettings;
4079};
4080
4081STDMETHODIMP Machine::Delete(ComSafeArrayIn(IMedium*, aMedia), IProgress **aProgress)
4082{
4083 LogFlowFuncEnter();
4084
4085 AutoCaller autoCaller(this);
4086 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4087
4088 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4089
4090 HRESULT rc = checkStateDependency(MutableStateDep);
4091 if (FAILED(rc)) return rc;
4092
4093 if (mData->mRegistered)
4094 return setError(VBOX_E_INVALID_VM_STATE,
4095 tr("Cannot delete settings of a registered machine"));
4096
4097 DeleteTask *pTask = new DeleteTask;
4098 pTask->pMachine = this;
4099 com::SafeIfaceArray<IMedium> sfaMedia(ComSafeArrayInArg(aMedia));
4100
4101 // collect files to delete
4102 pTask->llFilesToDelete = mData->llFilesToDelete; // saved states pushed here by Unregister()
4103
4104 pTask->fNeedsGlobalSaveSettings = false;
4105 for (size_t i = 0; i < sfaMedia.size(); ++i)
4106 {
4107 IMedium *pIMedium(sfaMedia[i]);
4108 Medium *pMedium = static_cast<Medium*>(pIMedium);
4109 AutoCaller mediumAutoCaller(pMedium);
4110 if (FAILED(mediumAutoCaller.rc())) return mediumAutoCaller.rc();
4111
4112 Utf8Str bstrLocation = pMedium->getLocationFull();
4113 // close the medium now; if that succeeds, then that means the medium is no longer
4114 // in use and we can add it to the list of files to delete
4115 rc = pMedium->close(&pTask->fNeedsGlobalSaveSettings,
4116 mediumAutoCaller);
4117 if (SUCCEEDED(rc))
4118 pTask->llFilesToDelete.push_back(bstrLocation);
4119 }
4120 if (mData->pMachineConfigFile->fileExists())
4121 pTask->llFilesToDelete.push_back(mData->m_strConfigFileFull);
4122
4123 pTask->pProgress.createObject();
4124 pTask->pProgress->init(getVirtualBox(),
4125 static_cast<IMachine*>(this) /* aInitiator */,
4126 Bstr(tr("Deleting files")),
4127 true /* fCancellable */,
4128 pTask->llFilesToDelete.size() + 1, // cOperations
4129 BstrFmt(tr("Deleting '%s'"), pTask->llFilesToDelete.front().c_str()));
4130
4131 int vrc = RTThreadCreate(NULL,
4132 Machine::deleteThread,
4133 (void*)pTask,
4134 0,
4135 RTTHREADTYPE_MAIN_WORKER,
4136 0,
4137 "MachineDelete");
4138
4139 pTask->pProgress.queryInterfaceTo(aProgress);
4140
4141 if (RT_FAILURE(vrc))
4142 {
4143 delete pTask;
4144 return setError(E_FAIL, "Could not create MachineDelete thread (%Rrc)", vrc);
4145 }
4146
4147 LogFlowFuncLeave();
4148
4149 return S_OK;
4150}
4151
4152/**
4153 * Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
4154 * calls Machine::deleteTaskWorker() on the actual machine object.
4155 * @param Thread
4156 * @param pvUser
4157 * @return
4158 */
4159/*static*/
4160DECLCALLBACK(int) Machine::deleteThread(RTTHREAD Thread, void *pvUser)
4161{
4162 LogFlowFuncEnter();
4163
4164 DeleteTask *pTask = (DeleteTask*)pvUser;
4165 Assert(pTask);
4166 Assert(pTask->pMachine);
4167 Assert(pTask->pProgress);
4168
4169 HRESULT rc = pTask->pMachine->deleteTaskWorker(*pTask);
4170 pTask->pProgress->notifyComplete(rc);
4171
4172 delete pTask;
4173
4174 LogFlowFuncLeave();
4175
4176 NOREF(Thread);
4177
4178 return VINF_SUCCESS;
4179}
4180
4181/**
4182 * Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
4183 * @param task
4184 * @return
4185 */
4186HRESULT Machine::deleteTaskWorker(DeleteTask &task)
4187{
4188 AutoCaller autoCaller(this);
4189 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4190
4191 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4192
4193 ULONG uLogHistoryCount = 3;
4194 ComPtr<ISystemProperties> systemProperties;
4195 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4196 if (!systemProperties.isNull())
4197 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4198
4199 // delete the files pushed on the task list by Machine::Delete()
4200 // (this includes saved states of the machine and snapshots and
4201 // medium storage files from the IMedium list passed in, and the
4202 // machine XML file)
4203 std::list<Utf8Str>::const_iterator it = task.llFilesToDelete.begin();
4204 while (it != task.llFilesToDelete.end())
4205 {
4206 const Utf8Str &strFile = *it;
4207 LogFunc(("Deleting file %s\n", strFile.c_str()));
4208 RTFileDelete(strFile.c_str());
4209
4210 ++it;
4211 if (it == task.llFilesToDelete.end())
4212 {
4213 task.pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")), 1);
4214 break;
4215 }
4216
4217 task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()), 1);
4218 }
4219
4220 /* delete the settings only when the file actually exists */
4221 if (mData->pMachineConfigFile->fileExists())
4222 {
4223 /* Delete any backup or uncommitted XML files. Ignore failures.
4224 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4225 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4226 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4227 RTFileDelete(otherXml.c_str());
4228 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4229 RTFileDelete(otherXml.c_str());
4230
4231 /* delete the Logs folder, nothing important should be left
4232 * there (we don't check for errors because the user might have
4233 * some private files there that we don't want to delete) */
4234 Utf8Str logFolder;
4235 getLogFolder(logFolder);
4236 Assert(logFolder.length());
4237 if (RTDirExists(logFolder.c_str()))
4238 {
4239 /* Delete all VBox.log[.N] files from the Logs folder
4240 * (this must be in sync with the rotation logic in
4241 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4242 * files that may have been created by the GUI. */
4243 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4244 logFolder.c_str(), RTPATH_DELIMITER);
4245 RTFileDelete(log.c_str());
4246 log = Utf8StrFmt("%s%cVBox.png",
4247 logFolder.c_str(), RTPATH_DELIMITER);
4248 RTFileDelete(log.c_str());
4249 for (int i = uLogHistoryCount; i > 0; i--)
4250 {
4251 log = Utf8StrFmt("%s%cVBox.log.%d",
4252 logFolder.c_str(), RTPATH_DELIMITER, i);
4253 RTFileDelete(log.c_str());
4254 log = Utf8StrFmt("%s%cVBox.png.%d",
4255 logFolder.c_str(), RTPATH_DELIMITER, i);
4256 RTFileDelete(log.c_str());
4257 }
4258
4259 RTDirRemove(logFolder.c_str());
4260 }
4261
4262 /* delete the Snapshots folder, nothing important should be left
4263 * there (we don't check for errors because the user might have
4264 * some private files there that we don't want to delete) */
4265 Assert(mUserData->m_strSnapshotFolderFull.length());
4266 if (RTDirExists(mUserData->m_strSnapshotFolderFull.c_str()))
4267 RTDirRemove(mUserData->m_strSnapshotFolderFull.c_str());
4268
4269 /* delete the directory that contains the settings file, but only
4270 * if it matches the VM name (i.e. a structure created by default in
4271 * prepareSaveSettings()) */
4272 {
4273 Utf8Str settingsDir;
4274 if (isInOwnDir(&settingsDir))
4275 RTDirRemove(settingsDir.c_str());
4276 }
4277 }
4278
4279 alock.release();
4280
4281 if (task.fNeedsGlobalSaveSettings)
4282 {
4283 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
4284 mParent->saveSettings();
4285 }
4286
4287 return S_OK;
4288}
4289
4290STDMETHODIMP Machine::GetSnapshot(IN_BSTR aId, ISnapshot **aSnapshot)
4291{
4292 CheckComArgOutPointerValid(aSnapshot);
4293
4294 AutoCaller autoCaller(this);
4295 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4296
4297 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4298
4299 Guid uuid(aId);
4300 /* Todo: fix this properly by perhaps introducing an isValid method for the Guid class */
4301 if ( (aId)
4302 && (*aId != '\0') // an empty Bstr means "get root snapshot", so don't fail on that
4303 && (uuid.isEmpty()))
4304 {
4305 RTUUID uuidTemp;
4306 /* Either it's a null UUID or the conversion failed. (null uuid has a special meaning in findSnapshot) */
4307 if (RT_FAILURE(RTUuidFromUtf16(&uuidTemp, aId)))
4308 return setError(E_FAIL,
4309 tr("Could not find a snapshot with UUID {%ls}"),
4310 aId);
4311 }
4312
4313 ComObjPtr<Snapshot> snapshot;
4314
4315 HRESULT rc = findSnapshot(uuid, snapshot, true /* aSetError */);
4316 snapshot.queryInterfaceTo(aSnapshot);
4317
4318 return rc;
4319}
4320
4321STDMETHODIMP Machine::FindSnapshot(IN_BSTR aName, ISnapshot **aSnapshot)
4322{
4323 CheckComArgStrNotEmptyOrNull(aName);
4324 CheckComArgOutPointerValid(aSnapshot);
4325
4326 AutoCaller autoCaller(this);
4327 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4328
4329 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4330
4331 ComObjPtr<Snapshot> snapshot;
4332
4333 HRESULT rc = findSnapshot(aName, snapshot, true /* aSetError */);
4334 snapshot.queryInterfaceTo(aSnapshot);
4335
4336 return rc;
4337}
4338
4339STDMETHODIMP Machine::SetCurrentSnapshot(IN_BSTR /* aId */)
4340{
4341 /// @todo (dmik) don't forget to set
4342 // mData->mCurrentStateModified to FALSE
4343
4344 return setError(E_NOTIMPL, "Not implemented");
4345}
4346
4347STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4348{
4349 CheckComArgStrNotEmptyOrNull(aName);
4350 CheckComArgStrNotEmptyOrNull(aHostPath);
4351
4352 AutoCaller autoCaller(this);
4353 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4354
4355 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4356
4357 HRESULT rc = checkStateDependency(MutableStateDep);
4358 if (FAILED(rc)) return rc;
4359
4360 ComObjPtr<SharedFolder> sharedFolder;
4361 rc = findSharedFolder(aName, sharedFolder, false /* aSetError */);
4362 if (SUCCEEDED(rc))
4363 return setError(VBOX_E_OBJECT_IN_USE,
4364 tr("Shared folder named '%ls' already exists"),
4365 aName);
4366
4367 sharedFolder.createObject();
4368 rc = sharedFolder->init(getMachine(), aName, aHostPath, aWritable, aAutoMount);
4369 if (FAILED(rc)) return rc;
4370
4371 setModified(IsModified_SharedFolders);
4372 mHWData.backup();
4373 mHWData->mSharedFolders.push_back(sharedFolder);
4374
4375 /* inform the direct session if any */
4376 alock.leave();
4377 onSharedFolderChange();
4378
4379 return S_OK;
4380}
4381
4382STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4383{
4384 CheckComArgStrNotEmptyOrNull(aName);
4385
4386 AutoCaller autoCaller(this);
4387 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4388
4389 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4390
4391 HRESULT rc = checkStateDependency(MutableStateDep);
4392 if (FAILED(rc)) return rc;
4393
4394 ComObjPtr<SharedFolder> sharedFolder;
4395 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4396 if (FAILED(rc)) return rc;
4397
4398 setModified(IsModified_SharedFolders);
4399 mHWData.backup();
4400 mHWData->mSharedFolders.remove(sharedFolder);
4401
4402 /* inform the direct session if any */
4403 alock.leave();
4404 onSharedFolderChange();
4405
4406 return S_OK;
4407}
4408
4409STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4410{
4411 CheckComArgOutPointerValid(aCanShow);
4412
4413 /* start with No */
4414 *aCanShow = FALSE;
4415
4416 AutoCaller autoCaller(this);
4417 AssertComRCReturnRC(autoCaller.rc());
4418
4419 ComPtr<IInternalSessionControl> directControl;
4420 {
4421 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4422
4423 if (mData->mSession.mState != SessionState_Locked)
4424 return setError(VBOX_E_INVALID_VM_STATE,
4425 tr("Machine is not locked for session (session state: %s)"),
4426 Global::stringifySessionState(mData->mSession.mState));
4427
4428 directControl = mData->mSession.mDirectControl;
4429 }
4430
4431 /* ignore calls made after #OnSessionEnd() is called */
4432 if (!directControl)
4433 return S_OK;
4434
4435 ULONG64 dummy;
4436 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
4437}
4438
4439STDMETHODIMP Machine::ShowConsoleWindow(ULONG64 *aWinId)
4440{
4441 CheckComArgOutPointerValid(aWinId);
4442
4443 AutoCaller autoCaller(this);
4444 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4445
4446 ComPtr<IInternalSessionControl> directControl;
4447 {
4448 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4449
4450 if (mData->mSession.mState != SessionState_Locked)
4451 return setError(E_FAIL,
4452 tr("Machine is not locked for session (session state: %s)"),
4453 Global::stringifySessionState(mData->mSession.mState));
4454
4455 directControl = mData->mSession.mDirectControl;
4456 }
4457
4458 /* ignore calls made after #OnSessionEnd() is called */
4459 if (!directControl)
4460 return S_OK;
4461
4462 BOOL dummy;
4463 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
4464}
4465
4466#ifdef VBOX_WITH_GUEST_PROPS
4467/**
4468 * Look up a guest property in VBoxSVC's internal structures.
4469 */
4470HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4471 BSTR *aValue,
4472 ULONG64 *aTimestamp,
4473 BSTR *aFlags) const
4474{
4475 using namespace guestProp;
4476
4477 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4478 Utf8Str strName(aName);
4479 HWData::GuestPropertyList::const_iterator it;
4480
4481 for (it = mHWData->mGuestProperties.begin();
4482 it != mHWData->mGuestProperties.end(); ++it)
4483 {
4484 if (it->strName == strName)
4485 {
4486 char szFlags[MAX_FLAGS_LEN + 1];
4487 it->strValue.cloneTo(aValue);
4488 *aTimestamp = it->mTimestamp;
4489 writeFlags(it->mFlags, szFlags);
4490 Bstr(szFlags).cloneTo(aFlags);
4491 break;
4492 }
4493 }
4494 return S_OK;
4495}
4496
4497/**
4498 * Query the VM that a guest property belongs to for the property.
4499 * @returns E_ACCESSDENIED if the VM process is not available or not
4500 * currently handling queries and the lookup should then be done in
4501 * VBoxSVC.
4502 */
4503HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4504 BSTR *aValue,
4505 ULONG64 *aTimestamp,
4506 BSTR *aFlags) const
4507{
4508 HRESULT rc;
4509 ComPtr<IInternalSessionControl> directControl;
4510 directControl = mData->mSession.mDirectControl;
4511
4512 /* fail if we were called after #OnSessionEnd() is called. This is a
4513 * silly race condition. */
4514
4515 if (!directControl)
4516 rc = E_ACCESSDENIED;
4517 else
4518 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4519 false /* isSetter */,
4520 aValue, aTimestamp, aFlags);
4521 return rc;
4522}
4523#endif // VBOX_WITH_GUEST_PROPS
4524
4525STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4526 BSTR *aValue,
4527 ULONG64 *aTimestamp,
4528 BSTR *aFlags)
4529{
4530#ifndef VBOX_WITH_GUEST_PROPS
4531 ReturnComNotImplemented();
4532#else // VBOX_WITH_GUEST_PROPS
4533 CheckComArgStrNotEmptyOrNull(aName);
4534 CheckComArgOutPointerValid(aValue);
4535 CheckComArgOutPointerValid(aTimestamp);
4536 CheckComArgOutPointerValid(aFlags);
4537
4538 AutoCaller autoCaller(this);
4539 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4540
4541 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4542 if (rc == E_ACCESSDENIED)
4543 /* The VM is not running or the service is not (yet) accessible */
4544 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4545 return rc;
4546#endif // VBOX_WITH_GUEST_PROPS
4547}
4548
4549STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4550{
4551 ULONG64 dummyTimestamp;
4552 Bstr dummyFlags;
4553 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
4554}
4555
4556STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, ULONG64 *aTimestamp)
4557{
4558 Bstr dummyValue;
4559 Bstr dummyFlags;
4560 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
4561}
4562
4563#ifdef VBOX_WITH_GUEST_PROPS
4564/**
4565 * Set a guest property in VBoxSVC's internal structures.
4566 */
4567HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4568 IN_BSTR aFlags)
4569{
4570 using namespace guestProp;
4571
4572 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4573 HRESULT rc = S_OK;
4574 HWData::GuestProperty property;
4575 property.mFlags = NILFLAG;
4576 bool found = false;
4577
4578 rc = checkStateDependency(MutableStateDep);
4579 if (FAILED(rc)) return rc;
4580
4581 try
4582 {
4583 Utf8Str utf8Name(aName);
4584 Utf8Str utf8Flags(aFlags);
4585 uint32_t fFlags = NILFLAG;
4586 if ( (aFlags != NULL)
4587 && RT_FAILURE(validateFlags(utf8Flags.c_str(), &fFlags))
4588 )
4589 return setError(E_INVALIDARG,
4590 tr("Invalid flag values: '%ls'"),
4591 aFlags);
4592
4593 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
4594 * know, this is simple and do an OK job atm.) */
4595 HWData::GuestPropertyList::iterator it;
4596 for (it = mHWData->mGuestProperties.begin();
4597 it != mHWData->mGuestProperties.end(); ++it)
4598 if (it->strName == utf8Name)
4599 {
4600 property = *it;
4601 if (it->mFlags & (RDONLYHOST))
4602 rc = setError(E_ACCESSDENIED,
4603 tr("The property '%ls' cannot be changed by the host"),
4604 aName);
4605 else
4606 {
4607 setModified(IsModified_MachineData);
4608 mHWData.backup(); // @todo r=dj backup in a loop?!?
4609
4610 /* The backup() operation invalidates our iterator, so
4611 * get a new one. */
4612 for (it = mHWData->mGuestProperties.begin();
4613 it->strName != utf8Name;
4614 ++it)
4615 ;
4616 mHWData->mGuestProperties.erase(it);
4617 }
4618 found = true;
4619 break;
4620 }
4621 if (found && SUCCEEDED(rc))
4622 {
4623 if (*aValue)
4624 {
4625 RTTIMESPEC time;
4626 property.strValue = aValue;
4627 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4628 if (aFlags != NULL)
4629 property.mFlags = fFlags;
4630 mHWData->mGuestProperties.push_back(property);
4631 }
4632 }
4633 else if (SUCCEEDED(rc) && *aValue)
4634 {
4635 RTTIMESPEC time;
4636 setModified(IsModified_MachineData);
4637 mHWData.backup();
4638 property.strName = aName;
4639 property.strValue = aValue;
4640 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4641 property.mFlags = fFlags;
4642 mHWData->mGuestProperties.push_back(property);
4643 }
4644 if ( SUCCEEDED(rc)
4645 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
4646 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
4647 RTSTR_MAX,
4648 utf8Name.c_str(),
4649 RTSTR_MAX,
4650 NULL)
4651 )
4652 )
4653 {
4654 /** @todo r=bird: Why aren't we leaving the lock here? The
4655 * same code in PushGuestProperty does... */
4656 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
4657 }
4658 }
4659 catch (std::bad_alloc &)
4660 {
4661 rc = E_OUTOFMEMORY;
4662 }
4663
4664 return rc;
4665}
4666
4667/**
4668 * Set a property on the VM that that property belongs to.
4669 * @returns E_ACCESSDENIED if the VM process is not available or not
4670 * currently handling queries and the setting should then be done in
4671 * VBoxSVC.
4672 */
4673HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
4674 IN_BSTR aFlags)
4675{
4676 HRESULT rc;
4677
4678 try {
4679 ComPtr<IInternalSessionControl> directControl =
4680 mData->mSession.mDirectControl;
4681
4682 BSTR dummy = NULL; /* will not be changed (setter) */
4683 ULONG64 dummy64;
4684 if (!directControl)
4685 rc = E_ACCESSDENIED;
4686 else
4687 rc = directControl->AccessGuestProperty
4688 (aName,
4689 /** @todo Fix when adding DeleteGuestProperty(),
4690 see defect. */
4691 *aValue ? aValue : NULL, aFlags, true /* isSetter */,
4692 &dummy, &dummy64, &dummy);
4693 }
4694 catch (std::bad_alloc &)
4695 {
4696 rc = E_OUTOFMEMORY;
4697 }
4698
4699 return rc;
4700}
4701#endif // VBOX_WITH_GUEST_PROPS
4702
4703STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
4704 IN_BSTR aFlags)
4705{
4706#ifndef VBOX_WITH_GUEST_PROPS
4707 ReturnComNotImplemented();
4708#else // VBOX_WITH_GUEST_PROPS
4709 CheckComArgStrNotEmptyOrNull(aName);
4710 if ((aFlags != NULL) && !VALID_PTR(aFlags))
4711 return E_INVALIDARG;
4712 AutoCaller autoCaller(this);
4713 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4714
4715 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
4716 if (rc == E_ACCESSDENIED)
4717 /* The VM is not running or the service is not (yet) accessible */
4718 rc = setGuestPropertyToService(aName, aValue, aFlags);
4719 return rc;
4720#endif // VBOX_WITH_GUEST_PROPS
4721}
4722
4723STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
4724{
4725 return SetGuestProperty(aName, aValue, NULL);
4726}
4727
4728#ifdef VBOX_WITH_GUEST_PROPS
4729/**
4730 * Enumerate the guest properties in VBoxSVC's internal structures.
4731 */
4732HRESULT Machine::enumerateGuestPropertiesInService
4733 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4734 ComSafeArrayOut(BSTR, aValues),
4735 ComSafeArrayOut(ULONG64, aTimestamps),
4736 ComSafeArrayOut(BSTR, aFlags))
4737{
4738 using namespace guestProp;
4739
4740 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4741 Utf8Str strPatterns(aPatterns);
4742
4743 /*
4744 * Look for matching patterns and build up a list.
4745 */
4746 HWData::GuestPropertyList propList;
4747 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
4748 it != mHWData->mGuestProperties.end();
4749 ++it)
4750 if ( strPatterns.isEmpty()
4751 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
4752 RTSTR_MAX,
4753 it->strName.c_str(),
4754 RTSTR_MAX,
4755 NULL)
4756 )
4757 propList.push_back(*it);
4758
4759 /*
4760 * And build up the arrays for returning the property information.
4761 */
4762 size_t cEntries = propList.size();
4763 SafeArray<BSTR> names(cEntries);
4764 SafeArray<BSTR> values(cEntries);
4765 SafeArray<ULONG64> timestamps(cEntries);
4766 SafeArray<BSTR> flags(cEntries);
4767 size_t iProp = 0;
4768 for (HWData::GuestPropertyList::iterator it = propList.begin();
4769 it != propList.end();
4770 ++it)
4771 {
4772 char szFlags[MAX_FLAGS_LEN + 1];
4773 it->strName.cloneTo(&names[iProp]);
4774 it->strValue.cloneTo(&values[iProp]);
4775 timestamps[iProp] = it->mTimestamp;
4776 writeFlags(it->mFlags, szFlags);
4777 Bstr(szFlags).cloneTo(&flags[iProp]);
4778 ++iProp;
4779 }
4780 names.detachTo(ComSafeArrayOutArg(aNames));
4781 values.detachTo(ComSafeArrayOutArg(aValues));
4782 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
4783 flags.detachTo(ComSafeArrayOutArg(aFlags));
4784 return S_OK;
4785}
4786
4787/**
4788 * Enumerate the properties managed by a VM.
4789 * @returns E_ACCESSDENIED if the VM process is not available or not
4790 * currently handling queries and the setting should then be done in
4791 * VBoxSVC.
4792 */
4793HRESULT Machine::enumerateGuestPropertiesOnVM
4794 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4795 ComSafeArrayOut(BSTR, aValues),
4796 ComSafeArrayOut(ULONG64, aTimestamps),
4797 ComSafeArrayOut(BSTR, aFlags))
4798{
4799 HRESULT rc;
4800 ComPtr<IInternalSessionControl> directControl;
4801 directControl = mData->mSession.mDirectControl;
4802
4803 if (!directControl)
4804 rc = E_ACCESSDENIED;
4805 else
4806 rc = directControl->EnumerateGuestProperties
4807 (aPatterns, ComSafeArrayOutArg(aNames),
4808 ComSafeArrayOutArg(aValues),
4809 ComSafeArrayOutArg(aTimestamps),
4810 ComSafeArrayOutArg(aFlags));
4811 return rc;
4812}
4813#endif // VBOX_WITH_GUEST_PROPS
4814
4815STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
4816 ComSafeArrayOut(BSTR, aNames),
4817 ComSafeArrayOut(BSTR, aValues),
4818 ComSafeArrayOut(ULONG64, aTimestamps),
4819 ComSafeArrayOut(BSTR, aFlags))
4820{
4821#ifndef VBOX_WITH_GUEST_PROPS
4822 ReturnComNotImplemented();
4823#else // VBOX_WITH_GUEST_PROPS
4824 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
4825 return E_POINTER;
4826
4827 CheckComArgOutSafeArrayPointerValid(aNames);
4828 CheckComArgOutSafeArrayPointerValid(aValues);
4829 CheckComArgOutSafeArrayPointerValid(aTimestamps);
4830 CheckComArgOutSafeArrayPointerValid(aFlags);
4831
4832 AutoCaller autoCaller(this);
4833 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4834
4835 HRESULT rc = enumerateGuestPropertiesOnVM
4836 (aPatterns, ComSafeArrayOutArg(aNames),
4837 ComSafeArrayOutArg(aValues),
4838 ComSafeArrayOutArg(aTimestamps),
4839 ComSafeArrayOutArg(aFlags));
4840 if (rc == E_ACCESSDENIED)
4841 /* The VM is not running or the service is not (yet) accessible */
4842 rc = enumerateGuestPropertiesInService
4843 (aPatterns, ComSafeArrayOutArg(aNames),
4844 ComSafeArrayOutArg(aValues),
4845 ComSafeArrayOutArg(aTimestamps),
4846 ComSafeArrayOutArg(aFlags));
4847 return rc;
4848#endif // VBOX_WITH_GUEST_PROPS
4849}
4850
4851STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
4852 ComSafeArrayOut(IMediumAttachment*, aAttachments))
4853{
4854 MediaData::AttachmentList atts;
4855
4856 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
4857 if (FAILED(rc)) return rc;
4858
4859 SafeIfaceArray<IMediumAttachment> attachments(atts);
4860 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
4861
4862 return S_OK;
4863}
4864
4865STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
4866 LONG aControllerPort,
4867 LONG aDevice,
4868 IMediumAttachment **aAttachment)
4869{
4870 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4871 aControllerName, aControllerPort, aDevice));
4872
4873 CheckComArgStrNotEmptyOrNull(aControllerName);
4874 CheckComArgOutPointerValid(aAttachment);
4875
4876 AutoCaller autoCaller(this);
4877 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4878
4879 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4880
4881 *aAttachment = NULL;
4882
4883 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4884 aControllerName,
4885 aControllerPort,
4886 aDevice);
4887 if (pAttach.isNull())
4888 return setError(VBOX_E_OBJECT_NOT_FOUND,
4889 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4890 aDevice, aControllerPort, aControllerName);
4891
4892 pAttach.queryInterfaceTo(aAttachment);
4893
4894 return S_OK;
4895}
4896
4897STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
4898 StorageBus_T aConnectionType,
4899 IStorageController **controller)
4900{
4901 CheckComArgStrNotEmptyOrNull(aName);
4902
4903 if ( (aConnectionType <= StorageBus_Null)
4904 || (aConnectionType > StorageBus_SAS))
4905 return setError(E_INVALIDARG,
4906 tr("Invalid connection type: %d"),
4907 aConnectionType);
4908
4909 AutoCaller autoCaller(this);
4910 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4911
4912 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4913
4914 HRESULT rc = checkStateDependency(MutableStateDep);
4915 if (FAILED(rc)) return rc;
4916
4917 /* try to find one with the name first. */
4918 ComObjPtr<StorageController> ctrl;
4919
4920 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
4921 if (SUCCEEDED(rc))
4922 return setError(VBOX_E_OBJECT_IN_USE,
4923 tr("Storage controller named '%ls' already exists"),
4924 aName);
4925
4926 ctrl.createObject();
4927
4928 /* get a new instance number for the storage controller */
4929 ULONG ulInstance = 0;
4930 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4931 it != mStorageControllers->end();
4932 ++it)
4933 {
4934 if ((*it)->getStorageBus() == aConnectionType)
4935 {
4936 ULONG ulCurInst = (*it)->getInstance();
4937
4938 if (ulCurInst >= ulInstance)
4939 ulInstance = ulCurInst + 1;
4940 }
4941 }
4942
4943 rc = ctrl->init(this, aName, aConnectionType, ulInstance);
4944 if (FAILED(rc)) return rc;
4945
4946 setModified(IsModified_Storage);
4947 mStorageControllers.backup();
4948 mStorageControllers->push_back(ctrl);
4949
4950 ctrl.queryInterfaceTo(controller);
4951
4952 /* inform the direct session if any */
4953 alock.leave();
4954 onStorageControllerChange();
4955
4956 return S_OK;
4957}
4958
4959STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
4960 IStorageController **aStorageController)
4961{
4962 CheckComArgStrNotEmptyOrNull(aName);
4963
4964 AutoCaller autoCaller(this);
4965 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4966
4967 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4968
4969 ComObjPtr<StorageController> ctrl;
4970
4971 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
4972 if (SUCCEEDED(rc))
4973 ctrl.queryInterfaceTo(aStorageController);
4974
4975 return rc;
4976}
4977
4978STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
4979 IStorageController **aStorageController)
4980{
4981 AutoCaller autoCaller(this);
4982 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4983
4984 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4985
4986 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4987 it != mStorageControllers->end();
4988 ++it)
4989 {
4990 if ((*it)->getInstance() == aInstance)
4991 {
4992 (*it).queryInterfaceTo(aStorageController);
4993 return S_OK;
4994 }
4995 }
4996
4997 return setError(VBOX_E_OBJECT_NOT_FOUND,
4998 tr("Could not find a storage controller with instance number '%lu'"),
4999 aInstance);
5000}
5001
5002STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5003{
5004 CheckComArgStrNotEmptyOrNull(aName);
5005
5006 AutoCaller autoCaller(this);
5007 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5008
5009 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5010
5011 HRESULT rc = checkStateDependency(MutableStateDep);
5012 if (FAILED(rc)) return rc;
5013
5014 ComObjPtr<StorageController> ctrl;
5015 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5016 if (FAILED(rc)) return rc;
5017
5018 /* We can remove the controller only if there is no device attached. */
5019 /* check if the device slot is already busy */
5020 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5021 it != mMediaData->mAttachments.end();
5022 ++it)
5023 {
5024 if ((*it)->getControllerName() == aName)
5025 return setError(VBOX_E_OBJECT_IN_USE,
5026 tr("Storage controller named '%ls' has still devices attached"),
5027 aName);
5028 }
5029
5030 /* We can remove it now. */
5031 setModified(IsModified_Storage);
5032 mStorageControllers.backup();
5033
5034 ctrl->unshare();
5035
5036 mStorageControllers->remove(ctrl);
5037
5038 /* inform the direct session if any */
5039 alock.leave();
5040 onStorageControllerChange();
5041
5042 return S_OK;
5043}
5044
5045/* @todo where is the right place for this? */
5046#define sSSMDisplayScreenshotVer 0x00010001
5047
5048static int readSavedDisplayScreenshot(const Utf8Str &strStateFilePath, uint32_t u32Type, uint8_t **ppu8Data, uint32_t *pcbData, uint32_t *pu32Width, uint32_t *pu32Height)
5049{
5050 LogFlowFunc(("u32Type = %d [%s]\n", u32Type, strStateFilePath.c_str()));
5051
5052 /* @todo cache read data */
5053 if (strStateFilePath.isEmpty())
5054 {
5055 /* No saved state data. */
5056 return VERR_NOT_SUPPORTED;
5057 }
5058
5059 uint8_t *pu8Data = NULL;
5060 uint32_t cbData = 0;
5061 uint32_t u32Width = 0;
5062 uint32_t u32Height = 0;
5063
5064 PSSMHANDLE pSSM;
5065 int vrc = SSMR3Open(strStateFilePath.c_str(), 0 /*fFlags*/, &pSSM);
5066 if (RT_SUCCESS(vrc))
5067 {
5068 uint32_t uVersion;
5069 vrc = SSMR3Seek(pSSM, "DisplayScreenshot", 1100 /*iInstance*/, &uVersion);
5070 if (RT_SUCCESS(vrc))
5071 {
5072 if (uVersion == sSSMDisplayScreenshotVer)
5073 {
5074 uint32_t cBlocks;
5075 vrc = SSMR3GetU32(pSSM, &cBlocks);
5076 AssertRCReturn(vrc, vrc);
5077
5078 for (uint32_t i = 0; i < cBlocks; i++)
5079 {
5080 uint32_t cbBlock;
5081 vrc = SSMR3GetU32(pSSM, &cbBlock);
5082 AssertRCBreak(vrc);
5083
5084 uint32_t typeOfBlock;
5085 vrc = SSMR3GetU32(pSSM, &typeOfBlock);
5086 AssertRCBreak(vrc);
5087
5088 LogFlowFunc(("[%d] type %d, size %d bytes\n", i, typeOfBlock, cbBlock));
5089
5090 if (typeOfBlock == u32Type)
5091 {
5092 if (cbBlock > 2 * sizeof(uint32_t))
5093 {
5094 cbData = cbBlock - 2 * sizeof(uint32_t);
5095 pu8Data = (uint8_t *)RTMemAlloc(cbData);
5096 if (pu8Data == NULL)
5097 {
5098 vrc = VERR_NO_MEMORY;
5099 break;
5100 }
5101
5102 vrc = SSMR3GetU32(pSSM, &u32Width);
5103 AssertRCBreak(vrc);
5104 vrc = SSMR3GetU32(pSSM, &u32Height);
5105 AssertRCBreak(vrc);
5106 vrc = SSMR3GetMem(pSSM, pu8Data, cbData);
5107 AssertRCBreak(vrc);
5108 }
5109 else
5110 {
5111 /* No saved state data. */
5112 vrc = VERR_NOT_SUPPORTED;
5113 }
5114
5115 break;
5116 }
5117 else
5118 {
5119 /* displaySSMSaveScreenshot did not write any data, if
5120 * cbBlock was == 2 * sizeof (uint32_t).
5121 */
5122 if (cbBlock > 2 * sizeof (uint32_t))
5123 {
5124 vrc = SSMR3Skip(pSSM, cbBlock);
5125 AssertRCBreak(vrc);
5126 }
5127 }
5128 }
5129 }
5130 else
5131 {
5132 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
5133 }
5134 }
5135
5136 SSMR3Close(pSSM);
5137 }
5138
5139 if (RT_SUCCESS(vrc))
5140 {
5141 if (u32Type == 0 && cbData % 4 != 0)
5142 {
5143 /* Bitmap is 32bpp, so data is invalid. */
5144 vrc = VERR_SSM_UNEXPECTED_DATA;
5145 }
5146 }
5147
5148 if (RT_SUCCESS(vrc))
5149 {
5150 *ppu8Data = pu8Data;
5151 *pcbData = cbData;
5152 *pu32Width = u32Width;
5153 *pu32Height = u32Height;
5154 LogFlowFunc(("cbData %d, u32Width %d, u32Height %d\n", cbData, u32Width, u32Height));
5155 }
5156
5157 LogFlowFunc(("vrc %Rrc\n", vrc));
5158 return vrc;
5159}
5160
5161static void freeSavedDisplayScreenshot(uint8_t *pu8Data)
5162{
5163 /* @todo not necessary when caching is implemented. */
5164 RTMemFree(pu8Data);
5165}
5166
5167STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5168{
5169 LogFlowThisFunc(("\n"));
5170
5171 CheckComArgNotNull(aSize);
5172 CheckComArgNotNull(aWidth);
5173 CheckComArgNotNull(aHeight);
5174
5175 if (aScreenId != 0)
5176 return E_NOTIMPL;
5177
5178 AutoCaller autoCaller(this);
5179 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5180
5181 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5182
5183 uint8_t *pu8Data = NULL;
5184 uint32_t cbData = 0;
5185 uint32_t u32Width = 0;
5186 uint32_t u32Height = 0;
5187
5188 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5189
5190 if (RT_FAILURE(vrc))
5191 return setError(VBOX_E_IPRT_ERROR,
5192 tr("Saved screenshot data is not available (%Rrc)"),
5193 vrc);
5194
5195 *aSize = cbData;
5196 *aWidth = u32Width;
5197 *aHeight = u32Height;
5198
5199 freeSavedDisplayScreenshot(pu8Data);
5200
5201 return S_OK;
5202}
5203
5204STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5205{
5206 LogFlowThisFunc(("\n"));
5207
5208 CheckComArgNotNull(aWidth);
5209 CheckComArgNotNull(aHeight);
5210 CheckComArgOutSafeArrayPointerValid(aData);
5211
5212 if (aScreenId != 0)
5213 return E_NOTIMPL;
5214
5215 AutoCaller autoCaller(this);
5216 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5217
5218 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5219
5220 uint8_t *pu8Data = NULL;
5221 uint32_t cbData = 0;
5222 uint32_t u32Width = 0;
5223 uint32_t u32Height = 0;
5224
5225 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5226
5227 if (RT_FAILURE(vrc))
5228 return setError(VBOX_E_IPRT_ERROR,
5229 tr("Saved screenshot data is not available (%Rrc)"),
5230 vrc);
5231
5232 *aWidth = u32Width;
5233 *aHeight = u32Height;
5234
5235 com::SafeArray<BYTE> bitmap(cbData);
5236 /* Convert pixels to format expected by the API caller. */
5237 if (aBGR)
5238 {
5239 /* [0] B, [1] G, [2] R, [3] A. */
5240 for (unsigned i = 0; i < cbData; i += 4)
5241 {
5242 bitmap[i] = pu8Data[i];
5243 bitmap[i + 1] = pu8Data[i + 1];
5244 bitmap[i + 2] = pu8Data[i + 2];
5245 bitmap[i + 3] = 0xff;
5246 }
5247 }
5248 else
5249 {
5250 /* [0] R, [1] G, [2] B, [3] A. */
5251 for (unsigned i = 0; i < cbData; i += 4)
5252 {
5253 bitmap[i] = pu8Data[i + 2];
5254 bitmap[i + 1] = pu8Data[i + 1];
5255 bitmap[i + 2] = pu8Data[i];
5256 bitmap[i + 3] = 0xff;
5257 }
5258 }
5259 bitmap.detachTo(ComSafeArrayOutArg(aData));
5260
5261 freeSavedDisplayScreenshot(pu8Data);
5262
5263 return S_OK;
5264}
5265
5266STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5267{
5268 LogFlowThisFunc(("\n"));
5269
5270 CheckComArgNotNull(aSize);
5271 CheckComArgNotNull(aWidth);
5272 CheckComArgNotNull(aHeight);
5273
5274 if (aScreenId != 0)
5275 return E_NOTIMPL;
5276
5277 AutoCaller autoCaller(this);
5278 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5279
5280 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5281
5282 uint8_t *pu8Data = NULL;
5283 uint32_t cbData = 0;
5284 uint32_t u32Width = 0;
5285 uint32_t u32Height = 0;
5286
5287 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5288
5289 if (RT_FAILURE(vrc))
5290 return setError(VBOX_E_IPRT_ERROR,
5291 tr("Saved screenshot data is not available (%Rrc)"),
5292 vrc);
5293
5294 *aSize = cbData;
5295 *aWidth = u32Width;
5296 *aHeight = u32Height;
5297
5298 freeSavedDisplayScreenshot(pu8Data);
5299
5300 return S_OK;
5301}
5302
5303STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5304{
5305 LogFlowThisFunc(("\n"));
5306
5307 CheckComArgNotNull(aWidth);
5308 CheckComArgNotNull(aHeight);
5309 CheckComArgOutSafeArrayPointerValid(aData);
5310
5311 if (aScreenId != 0)
5312 return E_NOTIMPL;
5313
5314 AutoCaller autoCaller(this);
5315 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5316
5317 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5318
5319 uint8_t *pu8Data = NULL;
5320 uint32_t cbData = 0;
5321 uint32_t u32Width = 0;
5322 uint32_t u32Height = 0;
5323
5324 int vrc = readSavedDisplayScreenshot(mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5325
5326 if (RT_FAILURE(vrc))
5327 return setError(VBOX_E_IPRT_ERROR,
5328 tr("Saved screenshot data is not available (%Rrc)"),
5329 vrc);
5330
5331 *aWidth = u32Width;
5332 *aHeight = u32Height;
5333
5334 com::SafeArray<BYTE> png(cbData);
5335 for (unsigned i = 0; i < cbData; i++)
5336 png[i] = pu8Data[i];
5337 png.detachTo(ComSafeArrayOutArg(aData));
5338
5339 freeSavedDisplayScreenshot(pu8Data);
5340
5341 return S_OK;
5342}
5343
5344STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5345{
5346 HRESULT rc = S_OK;
5347 LogFlowThisFunc(("\n"));
5348
5349 AutoCaller autoCaller(this);
5350 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5351
5352 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5353
5354 if (!mHWData->mCPUHotPlugEnabled)
5355 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5356
5357 if (aCpu >= mHWData->mCPUCount)
5358 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5359
5360 if (mHWData->mCPUAttached[aCpu])
5361 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5362
5363 alock.release();
5364 rc = onCPUChange(aCpu, false);
5365 alock.acquire();
5366 if (FAILED(rc)) return rc;
5367
5368 setModified(IsModified_MachineData);
5369 mHWData.backup();
5370 mHWData->mCPUAttached[aCpu] = true;
5371
5372 /* Save settings if online */
5373 if (Global::IsOnline(mData->mMachineState))
5374 saveSettings(NULL);
5375
5376 return S_OK;
5377}
5378
5379STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5380{
5381 HRESULT rc = S_OK;
5382 LogFlowThisFunc(("\n"));
5383
5384 AutoCaller autoCaller(this);
5385 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5386
5387 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5388
5389 if (!mHWData->mCPUHotPlugEnabled)
5390 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5391
5392 if (aCpu >= SchemaDefs::MaxCPUCount)
5393 return setError(E_INVALIDARG,
5394 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5395 SchemaDefs::MaxCPUCount);
5396
5397 if (!mHWData->mCPUAttached[aCpu])
5398 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5399
5400 /* CPU 0 can't be detached */
5401 if (aCpu == 0)
5402 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5403
5404 alock.release();
5405 rc = onCPUChange(aCpu, true);
5406 alock.acquire();
5407 if (FAILED(rc)) return rc;
5408
5409 setModified(IsModified_MachineData);
5410 mHWData.backup();
5411 mHWData->mCPUAttached[aCpu] = false;
5412
5413 /* Save settings if online */
5414 if (Global::IsOnline(mData->mMachineState))
5415 saveSettings(NULL);
5416
5417 return S_OK;
5418}
5419
5420STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5421{
5422 LogFlowThisFunc(("\n"));
5423
5424 CheckComArgNotNull(aCpuAttached);
5425
5426 *aCpuAttached = false;
5427
5428 AutoCaller autoCaller(this);
5429 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5430
5431 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5432
5433 /* If hotplug is enabled the CPU is always enabled. */
5434 if (!mHWData->mCPUHotPlugEnabled)
5435 {
5436 if (aCpu < mHWData->mCPUCount)
5437 *aCpuAttached = true;
5438 }
5439 else
5440 {
5441 if (aCpu < SchemaDefs::MaxCPUCount)
5442 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5443 }
5444
5445 return S_OK;
5446}
5447
5448STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5449{
5450 CheckComArgOutPointerValid(aName);
5451
5452 AutoCaller autoCaller(this);
5453 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5454
5455 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5456
5457 Utf8Str log = queryLogFilename(aIdx);
5458 if (!RTFileExists(log.c_str()))
5459 log.setNull();
5460 log.cloneTo(aName);
5461
5462 return S_OK;
5463}
5464
5465STDMETHODIMP Machine::ReadLog(ULONG aIdx, ULONG64 aOffset, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
5466{
5467 LogFlowThisFunc(("\n"));
5468 CheckComArgOutSafeArrayPointerValid(aData);
5469
5470 AutoCaller autoCaller(this);
5471 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5472
5473 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5474
5475 HRESULT rc = S_OK;
5476 Utf8Str log = queryLogFilename(aIdx);
5477
5478 /* do not unnecessarily hold the lock while doing something which does
5479 * not need the lock and potentially takes a long time. */
5480 alock.release();
5481
5482 /* Limit the chunk size to 32K for now, as that gives better performance
5483 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5484 * One byte expands to approx. 25 bytes of breathtaking XML. */
5485 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5486 com::SafeArray<BYTE> logData(cbData);
5487
5488 RTFILE LogFile;
5489 int vrc = RTFileOpen(&LogFile, log.c_str(),
5490 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5491 if (RT_SUCCESS(vrc))
5492 {
5493 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5494 if (RT_SUCCESS(vrc))
5495 logData.resize(cbData);
5496 else
5497 rc = setError(VBOX_E_IPRT_ERROR,
5498 tr("Could not read log file '%s' (%Rrc)"),
5499 log.c_str(), vrc);
5500 RTFileClose(LogFile);
5501 }
5502 else
5503 rc = setError(VBOX_E_IPRT_ERROR,
5504 tr("Could not open log file '%s' (%Rrc)"),
5505 log.c_str(), vrc);
5506
5507 if (FAILED(rc))
5508 logData.resize(0);
5509 logData.detachTo(ComSafeArrayOutArg(aData));
5510
5511 return rc;
5512}
5513
5514
5515// public methods for internal purposes
5516/////////////////////////////////////////////////////////////////////////////
5517
5518/**
5519 * Adds the given IsModified_* flag to the dirty flags of the machine.
5520 * This must be called either during loadSettings or under the machine write lock.
5521 * @param fl
5522 */
5523void Machine::setModified(uint32_t fl)
5524{
5525 mData->flModifications |= fl;
5526}
5527
5528/**
5529 * Saves the registry entry of this machine to the given configuration node.
5530 *
5531 * @param aEntryNode Node to save the registry entry to.
5532 *
5533 * @note locks this object for reading.
5534 */
5535HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5536{
5537 AutoLimitedCaller autoCaller(this);
5538 AssertComRCReturnRC(autoCaller.rc());
5539
5540 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5541
5542 data.uuid = mData->mUuid;
5543 data.strSettingsFile = mData->m_strConfigFile;
5544
5545 return S_OK;
5546}
5547
5548/**
5549 * Calculates the absolute path of the given path taking the directory of the
5550 * machine settings file as the current directory.
5551 *
5552 * @param aPath Path to calculate the absolute path for.
5553 * @param aResult Where to put the result (used only on success, can be the
5554 * same Utf8Str instance as passed in @a aPath).
5555 * @return IPRT result.
5556 *
5557 * @note Locks this object for reading.
5558 */
5559int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5560{
5561 AutoCaller autoCaller(this);
5562 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5563
5564 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5565
5566 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5567
5568 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5569
5570 strSettingsDir.stripFilename();
5571 char folder[RTPATH_MAX];
5572 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5573 if (RT_SUCCESS(vrc))
5574 aResult = folder;
5575
5576 return vrc;
5577}
5578
5579/**
5580 * Copies strSource to strTarget, making it relative to the machine folder
5581 * if it is a subdirectory thereof, or simply copying it otherwise.
5582 *
5583 * @param strSource Path to evalue and copy.
5584 * @param strTarget Buffer to receive target path.
5585 *
5586 * @note Locks this object for reading.
5587 */
5588void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5589 Utf8Str &strTarget)
5590{
5591 AutoCaller autoCaller(this);
5592 AssertComRCReturn(autoCaller.rc(), (void)0);
5593
5594 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5595
5596 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5597 // use strTarget as a temporary buffer to hold the machine settings dir
5598 strTarget = mData->m_strConfigFileFull;
5599 strTarget.stripFilename();
5600 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5601 // is relative: then append what's left
5602 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
5603 else
5604 // is not relative: then overwrite
5605 strTarget = strSource;
5606}
5607
5608/**
5609 * Returns the full path to the machine's log folder in the
5610 * \a aLogFolder argument.
5611 */
5612void Machine::getLogFolder(Utf8Str &aLogFolder)
5613{
5614 AutoCaller autoCaller(this);
5615 AssertComRCReturnVoid(autoCaller.rc());
5616
5617 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5618
5619 Utf8Str settingsDir;
5620 if (isInOwnDir(&settingsDir))
5621 /* Log folder is <Machines>/<VM_Name>/Logs */
5622 aLogFolder = settingsDir;
5623 else
5624 {
5625 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5626 Assert(!mUserData->m_strSnapshotFolderFull.isEmpty());
5627 aLogFolder = mUserData->m_strSnapshotFolderFull;
5628 }
5629
5630 aLogFolder.append(RTPATH_DELIMITER);
5631 aLogFolder.append("Logs");
5632}
5633
5634/**
5635 * Returns the full path to the machine's log file for an given index.
5636 */
5637Utf8Str Machine::queryLogFilename(ULONG idx)
5638{
5639 Utf8Str logFolder;
5640 getLogFolder(logFolder);
5641 Assert(logFolder.length());
5642 Utf8Str log;
5643 if (idx == 0)
5644 log = Utf8StrFmt("%s%cVBox.log",
5645 logFolder.c_str(), RTPATH_DELIMITER);
5646 else
5647 log = Utf8StrFmt("%s%cVBox.log.%d",
5648 logFolder.c_str(), RTPATH_DELIMITER, idx);
5649 return log;
5650}
5651
5652/**
5653 * @note Locks this object for writing, calls the client process
5654 * (inside the lock).
5655 */
5656HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5657 IN_BSTR aType,
5658 IN_BSTR aEnvironment,
5659 ProgressProxy *aProgress)
5660{
5661 LogFlowThisFuncEnter();
5662
5663 AssertReturn(aControl, E_FAIL);
5664 AssertReturn(aProgress, E_FAIL);
5665
5666 AutoCaller autoCaller(this);
5667 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5668
5669 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5670
5671 if (!mData->mRegistered)
5672 return setError(E_UNEXPECTED,
5673 tr("The machine '%s' is not registered"),
5674 mUserData->s.strName.c_str());
5675
5676 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5677
5678 if ( mData->mSession.mState == SessionState_Locked
5679 || mData->mSession.mState == SessionState_Spawning
5680 || mData->mSession.mState == SessionState_Unlocking)
5681 return setError(VBOX_E_INVALID_OBJECT_STATE,
5682 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
5683 mUserData->s.strName.c_str());
5684
5685 /* may not be busy */
5686 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5687
5688 /* get the path to the executable */
5689 char szPath[RTPATH_MAX];
5690 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5691 size_t sz = strlen(szPath);
5692 szPath[sz++] = RTPATH_DELIMITER;
5693 szPath[sz] = 0;
5694 char *cmd = szPath + sz;
5695 sz = RTPATH_MAX - sz;
5696
5697 int vrc = VINF_SUCCESS;
5698 RTPROCESS pid = NIL_RTPROCESS;
5699
5700 RTENV env = RTENV_DEFAULT;
5701
5702 if (aEnvironment != NULL && *aEnvironment)
5703 {
5704 char *newEnvStr = NULL;
5705
5706 do
5707 {
5708 /* clone the current environment */
5709 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5710 AssertRCBreakStmt(vrc2, vrc = vrc2);
5711
5712 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5713 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5714
5715 /* put new variables to the environment
5716 * (ignore empty variable names here since RTEnv API
5717 * intentionally doesn't do that) */
5718 char *var = newEnvStr;
5719 for (char *p = newEnvStr; *p; ++p)
5720 {
5721 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5722 {
5723 *p = '\0';
5724 if (*var)
5725 {
5726 char *val = strchr(var, '=');
5727 if (val)
5728 {
5729 *val++ = '\0';
5730 vrc2 = RTEnvSetEx(env, var, val);
5731 }
5732 else
5733 vrc2 = RTEnvUnsetEx(env, var);
5734 if (RT_FAILURE(vrc2))
5735 break;
5736 }
5737 var = p + 1;
5738 }
5739 }
5740 if (RT_SUCCESS(vrc2) && *var)
5741 vrc2 = RTEnvPutEx(env, var);
5742
5743 AssertRCBreakStmt(vrc2, vrc = vrc2);
5744 }
5745 while (0);
5746
5747 if (newEnvStr != NULL)
5748 RTStrFree(newEnvStr);
5749 }
5750
5751 Utf8Str strType(aType);
5752
5753 /* Qt is default */
5754#ifdef VBOX_WITH_QTGUI
5755 if (strType == "gui" || strType == "GUI/Qt")
5756 {
5757# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5758 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5759# else
5760 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5761# endif
5762 Assert(sz >= sizeof(VirtualBox_exe));
5763 strcpy(cmd, VirtualBox_exe);
5764
5765 Utf8Str idStr = mData->mUuid.toString();
5766 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5767 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5768 }
5769#else /* !VBOX_WITH_QTGUI */
5770 if (0)
5771 ;
5772#endif /* VBOX_WITH_QTGUI */
5773
5774 else
5775
5776#ifdef VBOX_WITH_VBOXSDL
5777 if (strType == "sdl" || strType == "GUI/SDL")
5778 {
5779 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5780 Assert(sz >= sizeof(VBoxSDL_exe));
5781 strcpy(cmd, VBoxSDL_exe);
5782
5783 Utf8Str idStr = mData->mUuid.toString();
5784 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
5785 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5786 }
5787#else /* !VBOX_WITH_VBOXSDL */
5788 if (0)
5789 ;
5790#endif /* !VBOX_WITH_VBOXSDL */
5791
5792 else
5793
5794#ifdef VBOX_WITH_HEADLESS
5795 if ( strType == "headless"
5796 || strType == "capture"
5797#ifdef VBOX_WITH_VRDP
5798 || strType == "vrdp"
5799#endif
5800 )
5801 {
5802 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
5803 Assert(sz >= sizeof(VBoxHeadless_exe));
5804 strcpy(cmd, VBoxHeadless_exe);
5805
5806 Utf8Str idStr = mData->mUuid.toString();
5807 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
5808 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
5809#ifdef VBOX_WITH_VRDP
5810 if (strType == "headless")
5811 {
5812 unsigned pos = RT_ELEMENTS(args) - 3;
5813 args[pos++] = "--vrdp";
5814 args[pos] = "off";
5815 }
5816#endif
5817 if (strType == "capture")
5818 {
5819 unsigned pos = RT_ELEMENTS(args) - 3;
5820 args[pos] = "--capture";
5821 }
5822 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5823 }
5824#else /* !VBOX_WITH_HEADLESS */
5825 if (0)
5826 ;
5827#endif /* !VBOX_WITH_HEADLESS */
5828 else
5829 {
5830 RTEnvDestroy(env);
5831 return setError(E_INVALIDARG,
5832 tr("Invalid session type: '%s'"),
5833 strType.c_str());
5834 }
5835
5836 RTEnvDestroy(env);
5837
5838 if (RT_FAILURE(vrc))
5839 return setError(VBOX_E_IPRT_ERROR,
5840 tr("Could not launch a process for the machine '%s' (%Rrc)"),
5841 mUserData->s.strName.c_str(), vrc);
5842
5843 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
5844
5845 /*
5846 * Note that we don't leave the lock here before calling the client,
5847 * because it doesn't need to call us back if called with a NULL argument.
5848 * Leaving the lock herer is dangerous because we didn't prepare the
5849 * launch data yet, but the client we've just started may happen to be
5850 * too fast and call openSession() that will fail (because of PID, etc.),
5851 * so that the Machine will never get out of the Spawning session state.
5852 */
5853
5854 /* inform the session that it will be a remote one */
5855 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
5856 HRESULT rc = aControl->AssignMachine(NULL);
5857 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
5858
5859 if (FAILED(rc))
5860 {
5861 /* restore the session state */
5862 mData->mSession.mState = SessionState_Unlocked;
5863 /* The failure may occur w/o any error info (from RPC), so provide one */
5864 return setError(VBOX_E_VM_ERROR,
5865 tr("Failed to assign the machine to the session (%Rrc)"), rc);
5866 }
5867
5868 /* attach launch data to the machine */
5869 Assert(mData->mSession.mPid == NIL_RTPROCESS);
5870 mData->mSession.mRemoteControls.push_back (aControl);
5871 mData->mSession.mProgress = aProgress;
5872 mData->mSession.mPid = pid;
5873 mData->mSession.mState = SessionState_Spawning;
5874 mData->mSession.mType = strType;
5875
5876 LogFlowThisFuncLeave();
5877 return S_OK;
5878}
5879
5880/**
5881 * Returns @c true if the given machine has an open direct session and returns
5882 * the session machine instance and additional session data (on some platforms)
5883 * if so.
5884 *
5885 * Note that when the method returns @c false, the arguments remain unchanged.
5886 *
5887 * @param aMachine Session machine object.
5888 * @param aControl Direct session control object (optional).
5889 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
5890 *
5891 * @note locks this object for reading.
5892 */
5893#if defined(RT_OS_WINDOWS)
5894bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5895 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5896 HANDLE *aIPCSem /*= NULL*/,
5897 bool aAllowClosing /*= false*/)
5898#elif defined(RT_OS_OS2)
5899bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5900 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5901 HMTX *aIPCSem /*= NULL*/,
5902 bool aAllowClosing /*= false*/)
5903#else
5904bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5905 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5906 bool aAllowClosing /*= false*/)
5907#endif
5908{
5909 AutoLimitedCaller autoCaller(this);
5910 AssertComRCReturn(autoCaller.rc(), false);
5911
5912 /* just return false for inaccessible machines */
5913 if (autoCaller.state() != Ready)
5914 return false;
5915
5916 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5917
5918 if ( mData->mSession.mState == SessionState_Locked
5919 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
5920 )
5921 {
5922 AssertReturn(!mData->mSession.mMachine.isNull(), false);
5923
5924 aMachine = mData->mSession.mMachine;
5925
5926 if (aControl != NULL)
5927 *aControl = mData->mSession.mDirectControl;
5928
5929#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5930 /* Additional session data */
5931 if (aIPCSem != NULL)
5932 *aIPCSem = aMachine->mIPCSem;
5933#endif
5934 return true;
5935 }
5936
5937 return false;
5938}
5939
5940/**
5941 * Returns @c true if the given machine has an spawning direct session and
5942 * returns and additional session data (on some platforms) if so.
5943 *
5944 * Note that when the method returns @c false, the arguments remain unchanged.
5945 *
5946 * @param aPID PID of the spawned direct session process.
5947 *
5948 * @note locks this object for reading.
5949 */
5950#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5951bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
5952#else
5953bool Machine::isSessionSpawning()
5954#endif
5955{
5956 AutoLimitedCaller autoCaller(this);
5957 AssertComRCReturn(autoCaller.rc(), false);
5958
5959 /* just return false for inaccessible machines */
5960 if (autoCaller.state() != Ready)
5961 return false;
5962
5963 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5964
5965 if (mData->mSession.mState == SessionState_Spawning)
5966 {
5967#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5968 /* Additional session data */
5969 if (aPID != NULL)
5970 {
5971 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
5972 *aPID = mData->mSession.mPid;
5973 }
5974#endif
5975 return true;
5976 }
5977
5978 return false;
5979}
5980
5981/**
5982 * Called from the client watcher thread to check for unexpected client process
5983 * death during Session_Spawning state (e.g. before it successfully opened a
5984 * direct session).
5985 *
5986 * On Win32 and on OS/2, this method is called only when we've got the
5987 * direct client's process termination notification, so it always returns @c
5988 * true.
5989 *
5990 * On other platforms, this method returns @c true if the client process is
5991 * terminated and @c false if it's still alive.
5992 *
5993 * @note Locks this object for writing.
5994 */
5995bool Machine::checkForSpawnFailure()
5996{
5997 AutoCaller autoCaller(this);
5998 if (!autoCaller.isOk())
5999 {
6000 /* nothing to do */
6001 LogFlowThisFunc(("Already uninitialized!\n"));
6002 return true;
6003 }
6004
6005 /* VirtualBox::addProcessToReap() needs a write lock */
6006 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6007
6008 if (mData->mSession.mState != SessionState_Spawning)
6009 {
6010 /* nothing to do */
6011 LogFlowThisFunc(("Not spawning any more!\n"));
6012 return true;
6013 }
6014
6015 HRESULT rc = S_OK;
6016
6017#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6018
6019 /* the process was already unexpectedly terminated, we just need to set an
6020 * error and finalize session spawning */
6021 rc = setError(E_FAIL,
6022 tr("The virtual machine '%ls' has terminated unexpectedly during startup"),
6023 getName().c_str());
6024#else
6025
6026 /* PID not yet initialized, skip check. */
6027 if (mData->mSession.mPid == NIL_RTPROCESS)
6028 return false;
6029
6030 RTPROCSTATUS status;
6031 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6032 &status);
6033
6034 if (vrc != VERR_PROCESS_RUNNING)
6035 {
6036 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6037 rc = setError(E_FAIL,
6038 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6039 getName().c_str(), status.iStatus);
6040 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6041 rc = setError(E_FAIL,
6042 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6043 getName().c_str(), status.iStatus);
6044 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6045 rc = setError(E_FAIL,
6046 tr("The virtual machine '%s' has terminated abnormally"),
6047 getName().c_str(), status.iStatus);
6048 else
6049 rc = setError(E_FAIL,
6050 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6051 getName().c_str(), rc);
6052 }
6053
6054#endif
6055
6056 if (FAILED(rc))
6057 {
6058 /* Close the remote session, remove the remote control from the list
6059 * and reset session state to Closed (@note keep the code in sync with
6060 * the relevant part in checkForSpawnFailure()). */
6061
6062 Assert(mData->mSession.mRemoteControls.size() == 1);
6063 if (mData->mSession.mRemoteControls.size() == 1)
6064 {
6065 ErrorInfoKeeper eik;
6066 mData->mSession.mRemoteControls.front()->Uninitialize();
6067 }
6068
6069 mData->mSession.mRemoteControls.clear();
6070 mData->mSession.mState = SessionState_Unlocked;
6071
6072 /* finalize the progress after setting the state */
6073 if (!mData->mSession.mProgress.isNull())
6074 {
6075 mData->mSession.mProgress->notifyComplete(rc);
6076 mData->mSession.mProgress.setNull();
6077 }
6078
6079 mParent->addProcessToReap(mData->mSession.mPid);
6080 mData->mSession.mPid = NIL_RTPROCESS;
6081
6082 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6083 return true;
6084 }
6085
6086 return false;
6087}
6088
6089/**
6090 * Checks whether the machine can be registered. If so, commits and saves
6091 * all settings.
6092 *
6093 * @note Must be called from mParent's write lock. Locks this object and
6094 * children for writing.
6095 */
6096HRESULT Machine::prepareRegister()
6097{
6098 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6099
6100 AutoLimitedCaller autoCaller(this);
6101 AssertComRCReturnRC(autoCaller.rc());
6102
6103 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6104
6105 /* wait for state dependants to drop to zero */
6106 ensureNoStateDependencies();
6107
6108 if (!mData->mAccessible)
6109 return setError(VBOX_E_INVALID_OBJECT_STATE,
6110 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6111 mUserData->s.strName.c_str(),
6112 mData->mUuid.toString().c_str());
6113
6114 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6115
6116 if (mData->mRegistered)
6117 return setError(VBOX_E_INVALID_OBJECT_STATE,
6118 tr("The machine '%s' with UUID {%s} is already registered"),
6119 mUserData->s.strName.c_str(),
6120 mData->mUuid.toString().c_str());
6121
6122 HRESULT rc = S_OK;
6123
6124 // Ensure the settings are saved. If we are going to be registered and
6125 // no config file exists yet, create it by calling saveSettings() too.
6126 if ( (mData->flModifications)
6127 || (!mData->pMachineConfigFile->fileExists())
6128 )
6129 {
6130 rc = saveSettings(NULL);
6131 // no need to check whether VirtualBox.xml needs saving too since
6132 // we can't have a machine XML file rename pending
6133 if (FAILED(rc)) return rc;
6134 }
6135
6136 /* more config checking goes here */
6137
6138 if (SUCCEEDED(rc))
6139 {
6140 /* we may have had implicit modifications we want to fix on success */
6141 commit();
6142
6143 mData->mRegistered = true;
6144 }
6145 else
6146 {
6147 /* we may have had implicit modifications we want to cancel on failure*/
6148 rollback(false /* aNotify */);
6149 }
6150
6151 return rc;
6152}
6153
6154/**
6155 * Increases the number of objects dependent on the machine state or on the
6156 * registered state. Guarantees that these two states will not change at least
6157 * until #releaseStateDependency() is called.
6158 *
6159 * Depending on the @a aDepType value, additional state checks may be made.
6160 * These checks will set extended error info on failure. See
6161 * #checkStateDependency() for more info.
6162 *
6163 * If this method returns a failure, the dependency is not added and the caller
6164 * is not allowed to rely on any particular machine state or registration state
6165 * value and may return the failed result code to the upper level.
6166 *
6167 * @param aDepType Dependency type to add.
6168 * @param aState Current machine state (NULL if not interested).
6169 * @param aRegistered Current registered state (NULL if not interested).
6170 *
6171 * @note Locks this object for writing.
6172 */
6173HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6174 MachineState_T *aState /* = NULL */,
6175 BOOL *aRegistered /* = NULL */)
6176{
6177 AutoCaller autoCaller(this);
6178 AssertComRCReturnRC(autoCaller.rc());
6179
6180 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6181
6182 HRESULT rc = checkStateDependency(aDepType);
6183 if (FAILED(rc)) return rc;
6184
6185 {
6186 if (mData->mMachineStateChangePending != 0)
6187 {
6188 /* ensureNoStateDependencies() is waiting for state dependencies to
6189 * drop to zero so don't add more. It may make sense to wait a bit
6190 * and retry before reporting an error (since the pending state
6191 * transition should be really quick) but let's just assert for
6192 * now to see if it ever happens on practice. */
6193
6194 AssertFailed();
6195
6196 return setError(E_ACCESSDENIED,
6197 tr("Machine state change is in progress. Please retry the operation later."));
6198 }
6199
6200 ++mData->mMachineStateDeps;
6201 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6202 }
6203
6204 if (aState)
6205 *aState = mData->mMachineState;
6206 if (aRegistered)
6207 *aRegistered = mData->mRegistered;
6208
6209 return S_OK;
6210}
6211
6212/**
6213 * Decreases the number of objects dependent on the machine state.
6214 * Must always complete the #addStateDependency() call after the state
6215 * dependency is no more necessary.
6216 */
6217void Machine::releaseStateDependency()
6218{
6219 AutoCaller autoCaller(this);
6220 AssertComRCReturnVoid(autoCaller.rc());
6221
6222 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6223
6224 /* releaseStateDependency() w/o addStateDependency()? */
6225 AssertReturnVoid(mData->mMachineStateDeps != 0);
6226 -- mData->mMachineStateDeps;
6227
6228 if (mData->mMachineStateDeps == 0)
6229 {
6230 /* inform ensureNoStateDependencies() that there are no more deps */
6231 if (mData->mMachineStateChangePending != 0)
6232 {
6233 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6234 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6235 }
6236 }
6237}
6238
6239// protected methods
6240/////////////////////////////////////////////////////////////////////////////
6241
6242/**
6243 * Performs machine state checks based on the @a aDepType value. If a check
6244 * fails, this method will set extended error info, otherwise it will return
6245 * S_OK. It is supposed, that on failure, the caller will immedieately return
6246 * the return value of this method to the upper level.
6247 *
6248 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6249 *
6250 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6251 * current state of this machine object allows to change settings of the
6252 * machine (i.e. the machine is not registered, or registered but not running
6253 * and not saved). It is useful to call this method from Machine setters
6254 * before performing any change.
6255 *
6256 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6257 * as for MutableStateDep except that if the machine is saved, S_OK is also
6258 * returned. This is useful in setters which allow changing machine
6259 * properties when it is in the saved state.
6260 *
6261 * @param aDepType Dependency type to check.
6262 *
6263 * @note Non Machine based classes should use #addStateDependency() and
6264 * #releaseStateDependency() methods or the smart AutoStateDependency
6265 * template.
6266 *
6267 * @note This method must be called from under this object's read or write
6268 * lock.
6269 */
6270HRESULT Machine::checkStateDependency(StateDependency aDepType)
6271{
6272 switch (aDepType)
6273 {
6274 case AnyStateDep:
6275 {
6276 break;
6277 }
6278 case MutableStateDep:
6279 {
6280 if ( mData->mRegistered
6281 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6282 || ( mData->mMachineState != MachineState_Paused
6283 && mData->mMachineState != MachineState_Running
6284 && mData->mMachineState != MachineState_Aborted
6285 && mData->mMachineState != MachineState_Teleported
6286 && mData->mMachineState != MachineState_PoweredOff
6287 )
6288 )
6289 )
6290 return setError(VBOX_E_INVALID_VM_STATE,
6291 tr("The machine is not mutable (state is %s)"),
6292 Global::stringifyMachineState(mData->mMachineState));
6293 break;
6294 }
6295 case MutableOrSavedStateDep:
6296 {
6297 if ( mData->mRegistered
6298 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6299 || ( mData->mMachineState != MachineState_Paused
6300 && mData->mMachineState != MachineState_Running
6301 && mData->mMachineState != MachineState_Aborted
6302 && mData->mMachineState != MachineState_Teleported
6303 && mData->mMachineState != MachineState_Saved
6304 && mData->mMachineState != MachineState_PoweredOff
6305 )
6306 )
6307 )
6308 return setError(VBOX_E_INVALID_VM_STATE,
6309 tr("The machine is not mutable (state is %s)"),
6310 Global::stringifyMachineState(mData->mMachineState));
6311 break;
6312 }
6313 }
6314
6315 return S_OK;
6316}
6317
6318/**
6319 * Helper to initialize all associated child objects and allocate data
6320 * structures.
6321 *
6322 * This method must be called as a part of the object's initialization procedure
6323 * (usually done in the #init() method).
6324 *
6325 * @note Must be called only from #init() or from #registeredInit().
6326 */
6327HRESULT Machine::initDataAndChildObjects()
6328{
6329 AutoCaller autoCaller(this);
6330 AssertComRCReturnRC(autoCaller.rc());
6331 AssertComRCReturn(autoCaller.state() == InInit ||
6332 autoCaller.state() == Limited, E_FAIL);
6333
6334 AssertReturn(!mData->mAccessible, E_FAIL);
6335
6336 /* allocate data structures */
6337 mSSData.allocate();
6338 mUserData.allocate();
6339 mHWData.allocate();
6340 mMediaData.allocate();
6341 mStorageControllers.allocate();
6342
6343 /* initialize mOSTypeId */
6344 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6345
6346 /* create associated BIOS settings object */
6347 unconst(mBIOSSettings).createObject();
6348 mBIOSSettings->init(this);
6349
6350#ifdef VBOX_WITH_VRDP
6351 /* create an associated VRDPServer object (default is disabled) */
6352 unconst(mVRDPServer).createObject();
6353 mVRDPServer->init(this);
6354#endif
6355
6356 /* create associated serial port objects */
6357 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6358 {
6359 unconst(mSerialPorts[slot]).createObject();
6360 mSerialPorts[slot]->init(this, slot);
6361 }
6362
6363 /* create associated parallel port objects */
6364 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6365 {
6366 unconst(mParallelPorts[slot]).createObject();
6367 mParallelPorts[slot]->init(this, slot);
6368 }
6369
6370 /* create the audio adapter object (always present, default is disabled) */
6371 unconst(mAudioAdapter).createObject();
6372 mAudioAdapter->init(this);
6373
6374 /* create the USB controller object (always present, default is disabled) */
6375 unconst(mUSBController).createObject();
6376 mUSBController->init(this);
6377
6378 /* create associated network adapter objects */
6379 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6380 {
6381 unconst(mNetworkAdapters[slot]).createObject();
6382 mNetworkAdapters[slot]->init(this, slot);
6383 }
6384
6385 return S_OK;
6386}
6387
6388/**
6389 * Helper to uninitialize all associated child objects and to free all data
6390 * structures.
6391 *
6392 * This method must be called as a part of the object's uninitialization
6393 * procedure (usually done in the #uninit() method).
6394 *
6395 * @note Must be called only from #uninit() or from #registeredInit().
6396 */
6397void Machine::uninitDataAndChildObjects()
6398{
6399 AutoCaller autoCaller(this);
6400 AssertComRCReturnVoid(autoCaller.rc());
6401 AssertComRCReturnVoid( autoCaller.state() == InUninit
6402 || autoCaller.state() == Limited);
6403
6404 /* uninit all children using addDependentChild()/removeDependentChild()
6405 * in their init()/uninit() methods */
6406 uninitDependentChildren();
6407
6408 /* tell all our other child objects we've been uninitialized */
6409
6410 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6411 {
6412 if (mNetworkAdapters[slot])
6413 {
6414 mNetworkAdapters[slot]->uninit();
6415 unconst(mNetworkAdapters[slot]).setNull();
6416 }
6417 }
6418
6419 if (mUSBController)
6420 {
6421 mUSBController->uninit();
6422 unconst(mUSBController).setNull();
6423 }
6424
6425 if (mAudioAdapter)
6426 {
6427 mAudioAdapter->uninit();
6428 unconst(mAudioAdapter).setNull();
6429 }
6430
6431 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6432 {
6433 if (mParallelPorts[slot])
6434 {
6435 mParallelPorts[slot]->uninit();
6436 unconst(mParallelPorts[slot]).setNull();
6437 }
6438 }
6439
6440 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6441 {
6442 if (mSerialPorts[slot])
6443 {
6444 mSerialPorts[slot]->uninit();
6445 unconst(mSerialPorts[slot]).setNull();
6446 }
6447 }
6448
6449#ifdef VBOX_WITH_VRDP
6450 if (mVRDPServer)
6451 {
6452 mVRDPServer->uninit();
6453 unconst(mVRDPServer).setNull();
6454 }
6455#endif
6456
6457 if (mBIOSSettings)
6458 {
6459 mBIOSSettings->uninit();
6460 unconst(mBIOSSettings).setNull();
6461 }
6462
6463 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6464 * instance is uninitialized; SessionMachine instances refer to real
6465 * Machine hard disks). This is necessary for a clean re-initialization of
6466 * the VM after successfully re-checking the accessibility state. Note
6467 * that in case of normal Machine or SnapshotMachine uninitialization (as
6468 * a result of unregistering or deleting the snapshot), outdated hard
6469 * disk attachments will already be uninitialized and deleted, so this
6470 * code will not affect them. */
6471 if ( !!mMediaData
6472 && (!isSessionMachine())
6473 )
6474 {
6475 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6476 it != mMediaData->mAttachments.end();
6477 ++it)
6478 {
6479 ComObjPtr<Medium> hd = (*it)->getMedium();
6480 if (hd.isNull())
6481 continue;
6482 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6483 AssertComRC(rc);
6484 }
6485 }
6486
6487 if (!isSessionMachine() && !isSnapshotMachine())
6488 {
6489 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6490 if (mData->mFirstSnapshot)
6491 {
6492 // snapshots tree is protected by media write lock; strictly
6493 // this isn't necessary here since we're deleting the entire
6494 // machine, but otherwise we assert in Snapshot::uninit()
6495 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6496 mData->mFirstSnapshot->uninit();
6497 mData->mFirstSnapshot.setNull();
6498 }
6499
6500 mData->mCurrentSnapshot.setNull();
6501 }
6502
6503 /* free data structures (the essential mData structure is not freed here
6504 * since it may be still in use) */
6505 mMediaData.free();
6506 mStorageControllers.free();
6507 mHWData.free();
6508 mUserData.free();
6509 mSSData.free();
6510}
6511
6512/**
6513 * Returns a pointer to the Machine object for this machine that acts like a
6514 * parent for complex machine data objects such as shared folders, etc.
6515 *
6516 * For primary Machine objects and for SnapshotMachine objects, returns this
6517 * object's pointer itself. For SessoinMachine objects, returns the peer
6518 * (primary) machine pointer.
6519 */
6520Machine* Machine::getMachine()
6521{
6522 if (isSessionMachine())
6523 return (Machine*)mPeer;
6524 return this;
6525}
6526
6527/**
6528 * Makes sure that there are no machine state dependants. If necessary, waits
6529 * for the number of dependants to drop to zero.
6530 *
6531 * Make sure this method is called from under this object's write lock to
6532 * guarantee that no new dependants may be added when this method returns
6533 * control to the caller.
6534 *
6535 * @note Locks this object for writing. The lock will be released while waiting
6536 * (if necessary).
6537 *
6538 * @warning To be used only in methods that change the machine state!
6539 */
6540void Machine::ensureNoStateDependencies()
6541{
6542 AssertReturnVoid(isWriteLockOnCurrentThread());
6543
6544 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6545
6546 /* Wait for all state dependants if necessary */
6547 if (mData->mMachineStateDeps != 0)
6548 {
6549 /* lazy semaphore creation */
6550 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6551 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6552
6553 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6554 mData->mMachineStateDeps));
6555
6556 ++mData->mMachineStateChangePending;
6557
6558 /* reset the semaphore before waiting, the last dependant will signal
6559 * it */
6560 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6561
6562 alock.leave();
6563
6564 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6565
6566 alock.enter();
6567
6568 -- mData->mMachineStateChangePending;
6569 }
6570}
6571
6572/**
6573 * Changes the machine state and informs callbacks.
6574 *
6575 * This method is not intended to fail so it either returns S_OK or asserts (and
6576 * returns a failure).
6577 *
6578 * @note Locks this object for writing.
6579 */
6580HRESULT Machine::setMachineState(MachineState_T aMachineState)
6581{
6582 LogFlowThisFuncEnter();
6583 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6584
6585 AutoCaller autoCaller(this);
6586 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6587
6588 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6589
6590 /* wait for state dependants to drop to zero */
6591 ensureNoStateDependencies();
6592
6593 if (mData->mMachineState != aMachineState)
6594 {
6595 mData->mMachineState = aMachineState;
6596
6597 RTTimeNow(&mData->mLastStateChange);
6598
6599 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6600 }
6601
6602 LogFlowThisFuncLeave();
6603 return S_OK;
6604}
6605
6606/**
6607 * Searches for a shared folder with the given logical name
6608 * in the collection of shared folders.
6609 *
6610 * @param aName logical name of the shared folder
6611 * @param aSharedFolder where to return the found object
6612 * @param aSetError whether to set the error info if the folder is
6613 * not found
6614 * @return
6615 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6616 *
6617 * @note
6618 * must be called from under the object's lock!
6619 */
6620HRESULT Machine::findSharedFolder(CBSTR aName,
6621 ComObjPtr<SharedFolder> &aSharedFolder,
6622 bool aSetError /* = false */)
6623{
6624 bool found = false;
6625 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6626 !found && it != mHWData->mSharedFolders.end();
6627 ++it)
6628 {
6629 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6630 found = (*it)->getName() == aName;
6631 if (found)
6632 aSharedFolder = *it;
6633 }
6634
6635 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6636
6637 if (aSetError && !found)
6638 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6639
6640 return rc;
6641}
6642
6643/**
6644 * Initializes all machine instance data from the given settings structures
6645 * from XML. The exception is the machine UUID which needs special handling
6646 * depending on the caller's use case, so the caller needs to set that herself.
6647 *
6648 * @param config
6649 * @param fAllowStorage
6650 */
6651HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config)
6652{
6653 // copy name, description, OS type, teleporter, UTC etc.
6654 mUserData->s = config.machineUserData;
6655
6656 // look up the object by Id to check it is valid
6657 ComPtr<IGuestOSType> guestOSType;
6658 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType),
6659 guestOSType.asOutParam());
6660 if (FAILED(rc)) return rc;
6661
6662 // stateFile (optional)
6663 if (config.strStateFile.isEmpty())
6664 mSSData->mStateFilePath.setNull();
6665 else
6666 {
6667 Utf8Str stateFilePathFull(config.strStateFile);
6668 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6669 if (RT_FAILURE(vrc))
6670 return setError(E_FAIL,
6671 tr("Invalid saved state file path '%s' (%Rrc)"),
6672 config.strStateFile.c_str(),
6673 vrc);
6674 mSSData->mStateFilePath = stateFilePathFull;
6675 }
6676
6677 // snapshot folder needs special processing so set it again
6678 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder));
6679 if (FAILED(rc)) return rc;
6680
6681 /* currentStateModified (optional, default is true) */
6682 mData->mCurrentStateModified = config.fCurrentStateModified;
6683
6684 mData->mLastStateChange = config.timeLastStateChange;
6685
6686 /*
6687 * note: all mUserData members must be assigned prior this point because
6688 * we need to commit changes in order to let mUserData be shared by all
6689 * snapshot machine instances.
6690 */
6691 mUserData.commitCopy();
6692
6693 // machine registry, if present (must be loaded before snapshots)
6694 if (config.canHaveOwnMediaRegistry())
6695 {
6696 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
6697 config.mediaRegistry);
6698 if (FAILED(rc)) return rc;
6699 }
6700
6701 /* Snapshot node (optional) */
6702 size_t cRootSnapshots;
6703 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6704 {
6705 // there must be only one root snapshot
6706 Assert(cRootSnapshots == 1);
6707
6708 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6709
6710 rc = loadSnapshot(snap,
6711 config.uuidCurrentSnapshot,
6712 NULL); // no parent == first snapshot
6713 if (FAILED(rc)) return rc;
6714 }
6715
6716 // hardware data
6717 rc = loadHardware(config.hardwareMachine);
6718 if (FAILED(rc)) return rc;
6719
6720 // load storage controllers
6721 rc = loadStorageControllers(config.storageMachine);
6722 if (FAILED(rc)) return rc;
6723
6724 /*
6725 * NOTE: the assignment below must be the last thing to do,
6726 * otherwise it will be not possible to change the settings
6727 * somewehere in the code above because all setters will be
6728 * blocked by checkStateDependency(MutableStateDep).
6729 */
6730
6731 /* set the machine state to Aborted or Saved when appropriate */
6732 if (config.fAborted)
6733 {
6734 Assert(!mSSData->mStateFilePath.isEmpty());
6735 mSSData->mStateFilePath.setNull();
6736
6737 /* no need to use setMachineState() during init() */
6738 mData->mMachineState = MachineState_Aborted;
6739 }
6740 else if (!mSSData->mStateFilePath.isEmpty())
6741 {
6742 /* no need to use setMachineState() during init() */
6743 mData->mMachineState = MachineState_Saved;
6744 }
6745
6746 // after loading settings, we are no longer different from the XML on disk
6747 mData->flModifications = 0;
6748
6749 return S_OK;
6750}
6751
6752/**
6753 * Recursively loads all snapshots starting from the given.
6754 *
6755 * @param aNode <Snapshot> node.
6756 * @param aCurSnapshotId Current snapshot ID from the settings file.
6757 * @param aParentSnapshot Parent snapshot.
6758 */
6759HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6760 const Guid &aCurSnapshotId,
6761 Snapshot *aParentSnapshot)
6762{
6763 AssertReturn(!isSnapshotMachine(), E_FAIL);
6764 AssertReturn(!isSessionMachine(), E_FAIL);
6765
6766 HRESULT rc = S_OK;
6767
6768 Utf8Str strStateFile;
6769 if (!data.strStateFile.isEmpty())
6770 {
6771 /* optional */
6772 strStateFile = data.strStateFile;
6773 int vrc = calculateFullPath(strStateFile, strStateFile);
6774 if (RT_FAILURE(vrc))
6775 return setError(E_FAIL,
6776 tr("Invalid saved state file path '%s' (%Rrc)"),
6777 strStateFile.c_str(),
6778 vrc);
6779 }
6780
6781 /* create a snapshot machine object */
6782 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6783 pSnapshotMachine.createObject();
6784 rc = pSnapshotMachine->init(this,
6785 data.hardware,
6786 data.storage,
6787 data.uuid,
6788 strStateFile);
6789 if (FAILED(rc)) return rc;
6790
6791 /* create a snapshot object */
6792 ComObjPtr<Snapshot> pSnapshot;
6793 pSnapshot.createObject();
6794 /* initialize the snapshot */
6795 rc = pSnapshot->init(mParent, // VirtualBox object
6796 data.uuid,
6797 data.strName,
6798 data.strDescription,
6799 data.timestamp,
6800 pSnapshotMachine,
6801 aParentSnapshot);
6802 if (FAILED(rc)) return rc;
6803
6804 /* memorize the first snapshot if necessary */
6805 if (!mData->mFirstSnapshot)
6806 mData->mFirstSnapshot = pSnapshot;
6807
6808 /* memorize the current snapshot when appropriate */
6809 if ( !mData->mCurrentSnapshot
6810 && pSnapshot->getId() == aCurSnapshotId
6811 )
6812 mData->mCurrentSnapshot = pSnapshot;
6813
6814 // now create the children
6815 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
6816 it != data.llChildSnapshots.end();
6817 ++it)
6818 {
6819 const settings::Snapshot &childData = *it;
6820 // recurse
6821 rc = loadSnapshot(childData,
6822 aCurSnapshotId,
6823 pSnapshot); // parent = the one we created above
6824 if (FAILED(rc)) return rc;
6825 }
6826
6827 return rc;
6828}
6829
6830/**
6831 * @param aNode <Hardware> node.
6832 */
6833HRESULT Machine::loadHardware(const settings::Hardware &data)
6834{
6835 AssertReturn(!isSessionMachine(), E_FAIL);
6836
6837 HRESULT rc = S_OK;
6838
6839 try
6840 {
6841 /* The hardware version attribute (optional). */
6842 mHWData->mHWVersion = data.strVersion;
6843 mHWData->mHardwareUUID = data.uuid;
6844
6845 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
6846 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
6847 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
6848 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
6849 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
6850 mHWData->mPAEEnabled = data.fPAE;
6851 mHWData->mSyntheticCpu = data.fSyntheticCpu;
6852
6853 mHWData->mCPUCount = data.cCPUs;
6854 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
6855 mHWData->mCpuPriority = data.ulCpuPriority;
6856
6857 // cpu
6858 if (mHWData->mCPUHotPlugEnabled)
6859 {
6860 for (settings::CpuList::const_iterator it = data.llCpus.begin();
6861 it != data.llCpus.end();
6862 ++it)
6863 {
6864 const settings::Cpu &cpu = *it;
6865
6866 mHWData->mCPUAttached[cpu.ulId] = true;
6867 }
6868 }
6869
6870 // cpuid leafs
6871 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
6872 it != data.llCpuIdLeafs.end();
6873 ++it)
6874 {
6875 const settings::CpuIdLeaf &leaf = *it;
6876
6877 switch (leaf.ulId)
6878 {
6879 case 0x0:
6880 case 0x1:
6881 case 0x2:
6882 case 0x3:
6883 case 0x4:
6884 case 0x5:
6885 case 0x6:
6886 case 0x7:
6887 case 0x8:
6888 case 0x9:
6889 case 0xA:
6890 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
6891 break;
6892
6893 case 0x80000000:
6894 case 0x80000001:
6895 case 0x80000002:
6896 case 0x80000003:
6897 case 0x80000004:
6898 case 0x80000005:
6899 case 0x80000006:
6900 case 0x80000007:
6901 case 0x80000008:
6902 case 0x80000009:
6903 case 0x8000000A:
6904 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
6905 break;
6906
6907 default:
6908 /* just ignore */
6909 break;
6910 }
6911 }
6912
6913 mHWData->mMemorySize = data.ulMemorySizeMB;
6914 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
6915
6916 // boot order
6917 for (size_t i = 0;
6918 i < RT_ELEMENTS(mHWData->mBootOrder);
6919 i++)
6920 {
6921 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
6922 if (it == data.mapBootOrder.end())
6923 mHWData->mBootOrder[i] = DeviceType_Null;
6924 else
6925 mHWData->mBootOrder[i] = it->second;
6926 }
6927
6928 mHWData->mVRAMSize = data.ulVRAMSizeMB;
6929 mHWData->mMonitorCount = data.cMonitors;
6930 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
6931 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
6932 mHWData->mFirmwareType = data.firmwareType;
6933 mHWData->mPointingHidType = data.pointingHidType;
6934 mHWData->mKeyboardHidType = data.keyboardHidType;
6935 mHWData->mHpetEnabled = data.fHpetEnabled;
6936
6937#ifdef VBOX_WITH_VRDP
6938 /* RemoteDisplay */
6939 rc = mVRDPServer->loadSettings(data.vrdpSettings);
6940 if (FAILED(rc)) return rc;
6941#endif
6942
6943 /* BIOS */
6944 rc = mBIOSSettings->loadSettings(data.biosSettings);
6945 if (FAILED(rc)) return rc;
6946
6947 /* USB Controller */
6948 rc = mUSBController->loadSettings(data.usbController);
6949 if (FAILED(rc)) return rc;
6950
6951 // network adapters
6952 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
6953 it != data.llNetworkAdapters.end();
6954 ++it)
6955 {
6956 const settings::NetworkAdapter &nic = *it;
6957
6958 /* slot unicity is guaranteed by XML Schema */
6959 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
6960 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
6961 if (FAILED(rc)) return rc;
6962 }
6963
6964 // serial ports
6965 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
6966 it != data.llSerialPorts.end();
6967 ++it)
6968 {
6969 const settings::SerialPort &s = *it;
6970
6971 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
6972 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
6973 if (FAILED(rc)) return rc;
6974 }
6975
6976 // parallel ports (optional)
6977 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
6978 it != data.llParallelPorts.end();
6979 ++it)
6980 {
6981 const settings::ParallelPort &p = *it;
6982
6983 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
6984 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
6985 if (FAILED(rc)) return rc;
6986 }
6987
6988 /* AudioAdapter */
6989 rc = mAudioAdapter->loadSettings(data.audioAdapter);
6990 if (FAILED(rc)) return rc;
6991
6992 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
6993 it != data.llSharedFolders.end();
6994 ++it)
6995 {
6996 const settings::SharedFolder &sf = *it;
6997 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable, sf.fAutoMount);
6998 if (FAILED(rc)) return rc;
6999 }
7000
7001 // Clipboard
7002 mHWData->mClipboardMode = data.clipboardMode;
7003
7004 // guest settings
7005 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7006
7007 // IO settings
7008 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7009 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7010
7011#ifdef VBOX_WITH_GUEST_PROPS
7012 /* Guest properties (optional) */
7013 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7014 it != data.llGuestProperties.end();
7015 ++it)
7016 {
7017 const settings::GuestProperty &prop = *it;
7018 uint32_t fFlags = guestProp::NILFLAG;
7019 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7020 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7021 mHWData->mGuestProperties.push_back(property);
7022 }
7023
7024 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7025#endif /* VBOX_WITH_GUEST_PROPS defined */
7026 }
7027 catch(std::bad_alloc &)
7028 {
7029 return E_OUTOFMEMORY;
7030 }
7031
7032 AssertComRC(rc);
7033 return rc;
7034}
7035
7036 /**
7037 * @param aNode <StorageControllers> node.
7038 */
7039HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7040 const Guid *aSnapshotId /* = NULL */)
7041{
7042 AssertReturn(!isSessionMachine(), E_FAIL);
7043
7044 HRESULT rc = S_OK;
7045
7046 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7047 it != data.llStorageControllers.end();
7048 ++it)
7049 {
7050 const settings::StorageController &ctlData = *it;
7051
7052 ComObjPtr<StorageController> pCtl;
7053 /* Try to find one with the name first. */
7054 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7055 if (SUCCEEDED(rc))
7056 return setError(VBOX_E_OBJECT_IN_USE,
7057 tr("Storage controller named '%s' already exists"),
7058 ctlData.strName.c_str());
7059
7060 pCtl.createObject();
7061 rc = pCtl->init(this,
7062 ctlData.strName,
7063 ctlData.storageBus,
7064 ctlData.ulInstance);
7065 if (FAILED(rc)) return rc;
7066
7067 mStorageControllers->push_back(pCtl);
7068
7069 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7070 if (FAILED(rc)) return rc;
7071
7072 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7073 if (FAILED(rc)) return rc;
7074
7075 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7076 if (FAILED(rc)) return rc;
7077
7078 /* Set IDE emulation settings (only for AHCI controller). */
7079 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7080 {
7081 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7082 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7083 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7084 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7085 )
7086 return rc;
7087 }
7088
7089 /* Load the attached devices now. */
7090 rc = loadStorageDevices(pCtl,
7091 ctlData,
7092 aSnapshotId);
7093 if (FAILED(rc)) return rc;
7094 }
7095
7096 return S_OK;
7097}
7098
7099/**
7100 * @param aNode <HardDiskAttachments> node.
7101 * @param fAllowStorage if false, we produce an error if the config requests media attachments
7102 * (used with importing unregistered machines which cannot have media attachments)
7103 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7104 *
7105 * @note Lock mParent for reading and hard disks for writing before calling.
7106 */
7107HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7108 const settings::StorageController &data,
7109 const Guid *aSnapshotId /*= NULL*/)
7110{
7111 HRESULT rc = S_OK;
7112
7113 /* paranoia: detect duplicate attachments */
7114 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7115 it != data.llAttachedDevices.end();
7116 ++it)
7117 {
7118 const settings::AttachedDevice &ad = *it;
7119
7120 for (settings::AttachedDevicesList::const_iterator it2 = it;
7121 it2 != data.llAttachedDevices.end();
7122 ++it2)
7123 {
7124 if (it == it2)
7125 continue;
7126
7127 const settings::AttachedDevice &ad2 = *it2;
7128
7129 if ( ad.lPort == ad2.lPort
7130 && ad.lDevice == ad2.lDevice)
7131 {
7132 return setError(E_FAIL,
7133 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7134 aStorageController->getName().c_str(),
7135 ad.lPort,
7136 ad.lDevice,
7137 mUserData->s.strName.c_str());
7138 }
7139 }
7140 }
7141
7142 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7143 it != data.llAttachedDevices.end();
7144 ++it)
7145 {
7146 const settings::AttachedDevice &dev = *it;
7147 ComObjPtr<Medium> medium;
7148
7149 switch (dev.deviceType)
7150 {
7151 case DeviceType_Floppy:
7152 case DeviceType_DVD:
7153 rc = mParent->findRemoveableMedium(dev.deviceType, dev.uuid, false /* fRefresh */, medium);
7154 if (FAILED(rc))
7155 return rc;
7156 break;
7157
7158 case DeviceType_HardDisk:
7159 {
7160 /* find a hard disk by UUID */
7161 rc = mParent->findHardDisk(&dev.uuid, Utf8Str::Empty, true /* aDoSetError */, &medium);
7162 if (FAILED(rc))
7163 {
7164 if (isSnapshotMachine())
7165 {
7166 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7167 // so the user knows that the bad disk is in a snapshot somewhere
7168 com::ErrorInfo info;
7169 return setError(E_FAIL,
7170 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7171 aSnapshotId->raw(),
7172 info.getText().raw());
7173 }
7174 else
7175 return rc;
7176 }
7177
7178 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7179
7180 if (medium->getType() == MediumType_Immutable)
7181 {
7182 if (isSnapshotMachine())
7183 return setError(E_FAIL,
7184 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7185 "of the virtual machine '%s' ('%s')"),
7186 medium->getLocationFull().c_str(),
7187 dev.uuid.raw(),
7188 aSnapshotId->raw(),
7189 mUserData->s.strName.c_str(),
7190 mData->m_strConfigFileFull.c_str());
7191
7192 return setError(E_FAIL,
7193 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7194 medium->getLocationFull().c_str(),
7195 dev.uuid.raw(),
7196 mUserData->s.strName.c_str(),
7197 mData->m_strConfigFileFull.c_str());
7198 }
7199
7200 if ( !isSnapshotMachine()
7201 && medium->getChildren().size() != 0
7202 )
7203 return setError(E_FAIL,
7204 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7205 "because it has %d differencing child hard disks"),
7206 medium->getLocationFull().c_str(),
7207 dev.uuid.raw(),
7208 mUserData->s.strName.c_str(),
7209 mData->m_strConfigFileFull.c_str(),
7210 medium->getChildren().size());
7211
7212 if (findAttachment(mMediaData->mAttachments,
7213 medium))
7214 return setError(E_FAIL,
7215 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7216 medium->getLocationFull().c_str(),
7217 dev.uuid.raw(),
7218 mUserData->s.strName.c_str(),
7219 mData->m_strConfigFileFull.c_str());
7220
7221 break;
7222 }
7223
7224 default:
7225 return setError(E_FAIL,
7226 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7227 medium->getLocationFull().c_str(),
7228 mUserData->s.strName.c_str(),
7229 mData->m_strConfigFileFull.c_str());
7230 }
7231
7232 if (FAILED(rc))
7233 break;
7234
7235 const Bstr controllerName = aStorageController->getName();
7236 ComObjPtr<MediumAttachment> pAttachment;
7237 pAttachment.createObject();
7238 rc = pAttachment->init(this,
7239 medium,
7240 controllerName,
7241 dev.lPort,
7242 dev.lDevice,
7243 dev.deviceType,
7244 dev.fPassThrough,
7245 dev.ulBandwidthLimit);
7246 if (FAILED(rc)) break;
7247
7248 /* associate the medium with this machine and snapshot */
7249 if (!medium.isNull())
7250 {
7251 if (isSnapshotMachine())
7252 rc = medium->addBackReference(mData->mUuid, *aSnapshotId);
7253 else
7254 rc = medium->addBackReference(mData->mUuid);
7255 }
7256
7257 if (FAILED(rc))
7258 break;
7259
7260 /* back up mMediaData to let registeredInit() properly rollback on failure
7261 * (= limited accessibility) */
7262 setModified(IsModified_Storage);
7263 mMediaData.backup();
7264 mMediaData->mAttachments.push_back(pAttachment);
7265 }
7266
7267 return rc;
7268}
7269
7270/**
7271 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7272 *
7273 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7274 * @param aSnapshot where to return the found snapshot
7275 * @param aSetError true to set extended error info on failure
7276 */
7277HRESULT Machine::findSnapshot(const Guid &aId,
7278 ComObjPtr<Snapshot> &aSnapshot,
7279 bool aSetError /* = false */)
7280{
7281 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7282
7283 if (!mData->mFirstSnapshot)
7284 {
7285 if (aSetError)
7286 return setError(E_FAIL,
7287 tr("This machine does not have any snapshots"));
7288 return E_FAIL;
7289 }
7290
7291 if (aId.isEmpty())
7292 aSnapshot = mData->mFirstSnapshot;
7293 else
7294 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
7295
7296 if (!aSnapshot)
7297 {
7298 if (aSetError)
7299 return setError(E_FAIL,
7300 tr("Could not find a snapshot with UUID {%s}"),
7301 aId.toString().c_str());
7302 return E_FAIL;
7303 }
7304
7305 return S_OK;
7306}
7307
7308/**
7309 * Returns the snapshot with the given name or fails of no such snapshot.
7310 *
7311 * @param aName snapshot name to find
7312 * @param aSnapshot where to return the found snapshot
7313 * @param aSetError true to set extended error info on failure
7314 */
7315HRESULT Machine::findSnapshot(IN_BSTR aName,
7316 ComObjPtr<Snapshot> &aSnapshot,
7317 bool aSetError /* = false */)
7318{
7319 AssertReturn(aName, E_INVALIDARG);
7320
7321 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7322
7323 if (!mData->mFirstSnapshot)
7324 {
7325 if (aSetError)
7326 return setError(VBOX_E_OBJECT_NOT_FOUND,
7327 tr("This machine does not have any snapshots"));
7328 return VBOX_E_OBJECT_NOT_FOUND;
7329 }
7330
7331 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aName);
7332
7333 if (!aSnapshot)
7334 {
7335 if (aSetError)
7336 return setError(VBOX_E_OBJECT_NOT_FOUND,
7337 tr("Could not find a snapshot named '%ls'"), aName);
7338 return VBOX_E_OBJECT_NOT_FOUND;
7339 }
7340
7341 return S_OK;
7342}
7343
7344/**
7345 * Returns a storage controller object with the given name.
7346 *
7347 * @param aName storage controller name to find
7348 * @param aStorageController where to return the found storage controller
7349 * @param aSetError true to set extended error info on failure
7350 */
7351HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7352 ComObjPtr<StorageController> &aStorageController,
7353 bool aSetError /* = false */)
7354{
7355 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7356
7357 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7358 it != mStorageControllers->end();
7359 ++it)
7360 {
7361 if ((*it)->getName() == aName)
7362 {
7363 aStorageController = (*it);
7364 return S_OK;
7365 }
7366 }
7367
7368 if (aSetError)
7369 return setError(VBOX_E_OBJECT_NOT_FOUND,
7370 tr("Could not find a storage controller named '%s'"),
7371 aName.c_str());
7372 return VBOX_E_OBJECT_NOT_FOUND;
7373}
7374
7375HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7376 MediaData::AttachmentList &atts)
7377{
7378 AutoCaller autoCaller(this);
7379 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7380
7381 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7382
7383 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7384 it != mMediaData->mAttachments.end();
7385 ++it)
7386 {
7387 const ComObjPtr<MediumAttachment> &pAtt = *it;
7388
7389 // should never happen, but deal with NULL pointers in the list.
7390 AssertStmt(!pAtt.isNull(), continue);
7391
7392 // getControllerName() needs caller+read lock
7393 AutoCaller autoAttCaller(pAtt);
7394 if (FAILED(autoAttCaller.rc()))
7395 {
7396 atts.clear();
7397 return autoAttCaller.rc();
7398 }
7399 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7400
7401 if (pAtt->getControllerName() == aName)
7402 atts.push_back(pAtt);
7403 }
7404
7405 return S_OK;
7406}
7407
7408/**
7409 * Helper for #saveSettings. Cares about renaming the settings directory and
7410 * file if the machine name was changed and about creating a new settings file
7411 * if this is a new machine.
7412 *
7413 * @note Must be never called directly but only from #saveSettings().
7414 */
7415HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7416{
7417 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7418
7419 HRESULT rc = S_OK;
7420
7421 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7422
7423 /* attempt to rename the settings file if machine name is changed */
7424 if ( mUserData->s.fNameSync
7425 && mUserData.isBackedUp()
7426 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7427 )
7428 {
7429 bool dirRenamed = false;
7430 bool fileRenamed = false;
7431
7432 Utf8Str configFile, newConfigFile;
7433 Utf8Str configDir, newConfigDir;
7434
7435 do
7436 {
7437 int vrc = VINF_SUCCESS;
7438
7439 Utf8Str name = mUserData.backedUpData()->s.strName;
7440 Utf8Str newName = mUserData->s.strName;
7441
7442 configFile = mData->m_strConfigFileFull;
7443
7444 /* first, rename the directory if it matches the machine name */
7445 configDir = configFile;
7446 configDir.stripFilename();
7447 newConfigDir = configDir;
7448 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7449 {
7450 newConfigDir.stripFilename();
7451 newConfigDir.append(RTPATH_DELIMITER);
7452 newConfigDir.append(newName);
7453 /* new dir and old dir cannot be equal here because of 'if'
7454 * above and because name != newName */
7455 Assert(configDir != newConfigDir);
7456 if (!fSettingsFileIsNew)
7457 {
7458 /* perform real rename only if the machine is not new */
7459 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7460 if (RT_FAILURE(vrc))
7461 {
7462 rc = setError(E_FAIL,
7463 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7464 configDir.c_str(),
7465 newConfigDir.c_str(),
7466 vrc);
7467 break;
7468 }
7469 dirRenamed = true;
7470 }
7471 }
7472
7473 newConfigFile = Utf8StrFmt("%s%c%s.xml",
7474 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7475
7476 /* then try to rename the settings file itself */
7477 if (newConfigFile != configFile)
7478 {
7479 /* get the path to old settings file in renamed directory */
7480 configFile = Utf8StrFmt("%s%c%s",
7481 newConfigDir.c_str(),
7482 RTPATH_DELIMITER,
7483 RTPathFilename(configFile.c_str()));
7484 if (!fSettingsFileIsNew)
7485 {
7486 /* perform real rename only if the machine is not new */
7487 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7488 if (RT_FAILURE(vrc))
7489 {
7490 rc = setError(E_FAIL,
7491 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7492 configFile.c_str(),
7493 newConfigFile.c_str(),
7494 vrc);
7495 break;
7496 }
7497 fileRenamed = true;
7498 }
7499 }
7500
7501 /* update m_strConfigFileFull amd mConfigFile */
7502 mData->m_strConfigFileFull = newConfigFile;
7503 // compute the relative path too
7504 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7505
7506 // store the old and new so that VirtualBox::saveSettings() can update
7507 // the media registry
7508 if ( mData->mRegistered
7509 && configDir != newConfigDir)
7510 {
7511 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7512
7513 if (pfNeedsGlobalSaveSettings)
7514 *pfNeedsGlobalSaveSettings = true;
7515 }
7516
7517 /* update the snapshot folder */
7518 if (RTPathStartsWith(mUserData->m_strSnapshotFolderFull.c_str(),
7519 configDir.c_str()))
7520 {
7521 mUserData->m_strSnapshotFolderFull = Utf8StrFmt("%s%s",
7522 newConfigDir.c_str(),
7523 mUserData->m_strSnapshotFolderFull.c_str() + configDir.length());
7524 copyPathRelativeToMachine(mUserData->m_strSnapshotFolderFull,
7525 mUserData->s.strSnapshotFolder);
7526 }
7527
7528 /* update the saved state file path */
7529 Utf8Str path = mSSData->mStateFilePath;
7530 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7531 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
7532 newConfigDir.c_str(),
7533 path.c_str() + configDir.length());
7534
7535 /* Update saved state file paths of all online snapshots.
7536 * Note that saveSettings() will recognize name change
7537 * and will save all snapshots in this case. */
7538 if (mData->mFirstSnapshot)
7539 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7540 newConfigDir.c_str());
7541 }
7542 while (0);
7543
7544 if (FAILED(rc))
7545 {
7546 /* silently try to rename everything back */
7547 if (fileRenamed)
7548 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
7549 if (dirRenamed)
7550 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
7551 }
7552
7553 if (FAILED(rc)) return rc;
7554 }
7555
7556 if (fSettingsFileIsNew)
7557 {
7558 /* create a virgin config file */
7559 int vrc = VINF_SUCCESS;
7560
7561 /* ensure the settings directory exists */
7562 Utf8Str path(mData->m_strConfigFileFull);
7563 path.stripFilename();
7564 if (!RTDirExists(path.c_str()))
7565 {
7566 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7567 if (RT_FAILURE(vrc))
7568 {
7569 return setError(E_FAIL,
7570 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7571 path.c_str(),
7572 vrc);
7573 }
7574 }
7575
7576 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7577 path = Utf8Str(mData->m_strConfigFileFull);
7578 RTFILE f = NIL_RTFILE;
7579 vrc = RTFileOpen(&f, path.c_str(),
7580 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7581 if (RT_FAILURE(vrc))
7582 return setError(E_FAIL,
7583 tr("Could not create the settings file '%s' (%Rrc)"),
7584 path.c_str(),
7585 vrc);
7586 RTFileClose(f);
7587 }
7588
7589 return rc;
7590}
7591
7592/**
7593 * Saves and commits machine data, user data and hardware data.
7594 *
7595 * Note that on failure, the data remains uncommitted.
7596 *
7597 * @a aFlags may combine the following flags:
7598 *
7599 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7600 * Used when saving settings after an operation that makes them 100%
7601 * correspond to the settings from the current snapshot.
7602 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7603 * #isReallyModified() returns false. This is necessary for cases when we
7604 * change machine data directly, not through the backup()/commit() mechanism.
7605 * - SaveS_Force: settings will be saved without doing a deep compare of the
7606 * settings structures. This is used when this is called because snapshots
7607 * have changed to avoid the overhead of the deep compare.
7608 *
7609 * @note Must be called from under this object's write lock. Locks children for
7610 * writing.
7611 *
7612 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7613 * initialized to false and that will be set to true by this function if
7614 * the caller must invoke VirtualBox::saveSettings() because the global
7615 * settings have changed. This will happen if a machine rename has been
7616 * saved and the global machine and media registries will therefore need
7617 * updating.
7618 */
7619HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7620 int aFlags /*= 0*/)
7621{
7622 LogFlowThisFuncEnter();
7623
7624 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7625
7626 /* make sure child objects are unable to modify the settings while we are
7627 * saving them */
7628 ensureNoStateDependencies();
7629
7630 AssertReturn(!isSnapshotMachine(),
7631 E_FAIL);
7632
7633 HRESULT rc = S_OK;
7634 bool fNeedsWrite = false;
7635
7636 /* First, prepare to save settings. It will care about renaming the
7637 * settings directory and file if the machine name was changed and about
7638 * creating a new settings file if this is a new machine. */
7639 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7640 if (FAILED(rc)) return rc;
7641
7642 // keep a pointer to the current settings structures
7643 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7644 settings::MachineConfigFile *pNewConfig = NULL;
7645
7646 try
7647 {
7648 // make a fresh one to have everyone write stuff into
7649 pNewConfig = new settings::MachineConfigFile(NULL);
7650 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7651
7652 // now go and copy all the settings data from COM to the settings structures
7653 // (this calles saveSettings() on all the COM objects in the machine)
7654 copyMachineDataToSettings(*pNewConfig);
7655
7656 if (aFlags & SaveS_ResetCurStateModified)
7657 {
7658 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7659 mData->mCurrentStateModified = FALSE;
7660 fNeedsWrite = true; // always, no need to compare
7661 }
7662 else if (aFlags & SaveS_Force)
7663 {
7664 fNeedsWrite = true; // always, no need to compare
7665 }
7666 else
7667 {
7668 if (!mData->mCurrentStateModified)
7669 {
7670 // do a deep compare of the settings that we just saved with the settings
7671 // previously stored in the config file; this invokes MachineConfigFile::operator==
7672 // which does a deep compare of all the settings, which is expensive but less expensive
7673 // than writing out XML in vain
7674 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7675
7676 // could still be modified if any settings changed
7677 mData->mCurrentStateModified = fAnySettingsChanged;
7678
7679 fNeedsWrite = fAnySettingsChanged;
7680 }
7681 else
7682 fNeedsWrite = true;
7683 }
7684
7685 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7686
7687 if (fNeedsWrite)
7688 // now spit it all out!
7689 pNewConfig->write(mData->m_strConfigFileFull);
7690
7691 mData->pMachineConfigFile = pNewConfig;
7692 delete pOldConfig;
7693 commit();
7694
7695 // after saving settings, we are no longer different from the XML on disk
7696 mData->flModifications = 0;
7697 }
7698 catch (HRESULT err)
7699 {
7700 // we assume that error info is set by the thrower
7701 rc = err;
7702
7703 // restore old config
7704 delete pNewConfig;
7705 mData->pMachineConfigFile = pOldConfig;
7706 }
7707 catch (...)
7708 {
7709 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7710 }
7711
7712 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7713 {
7714 /* Fire the data change event, even on failure (since we've already
7715 * committed all data). This is done only for SessionMachines because
7716 * mutable Machine instances are always not registered (i.e. private
7717 * to the client process that creates them) and thus don't need to
7718 * inform callbacks. */
7719 if (isSessionMachine())
7720 mParent->onMachineDataChange(mData->mUuid);
7721 }
7722
7723 LogFlowThisFunc(("rc=%08X\n", rc));
7724 LogFlowThisFuncLeave();
7725 return rc;
7726}
7727
7728/**
7729 * Implementation for saving the machine settings into the given
7730 * settings::MachineConfigFile instance. This copies machine extradata
7731 * from the previous machine config file in the instance data, if any.
7732 *
7733 * This gets called from two locations:
7734 *
7735 * -- Machine::saveSettings(), during the regular XML writing;
7736 *
7737 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7738 * exported to OVF and we write the VirtualBox proprietary XML
7739 * into a <vbox:Machine> tag.
7740 *
7741 * This routine fills all the fields in there, including snapshots, *except*
7742 * for the following:
7743 *
7744 * -- fCurrentStateModified. There is some special logic associated with that.
7745 *
7746 * The caller can then call MachineConfigFile::write() or do something else
7747 * with it.
7748 *
7749 * Caller must hold the machine lock!
7750 *
7751 * This throws XML errors and HRESULT, so the caller must have a catch block!
7752 */
7753void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7754{
7755 // deep copy extradata
7756 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7757
7758 config.uuid = mData->mUuid;
7759
7760 // copy name, description, OS type, teleport, UTC etc.
7761 config.machineUserData = mUserData->s;
7762
7763 if ( mData->mMachineState == MachineState_Saved
7764 || mData->mMachineState == MachineState_Restoring
7765 // when deleting a snapshot we may or may not have a saved state in the current state,
7766 // so let's not assert here please
7767 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7768 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7769 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7770 && (!mSSData->mStateFilePath.isEmpty())
7771 )
7772 )
7773 {
7774 Assert(!mSSData->mStateFilePath.isEmpty());
7775 /* try to make the file name relative to the settings file dir */
7776 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
7777 }
7778 else
7779 {
7780 Assert(mSSData->mStateFilePath.isEmpty());
7781 config.strStateFile.setNull();
7782 }
7783
7784 if (mData->mCurrentSnapshot)
7785 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7786 else
7787 config.uuidCurrentSnapshot.clear();
7788
7789 config.timeLastStateChange = mData->mLastStateChange;
7790 config.fAborted = (mData->mMachineState == MachineState_Aborted);
7791 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
7792
7793 HRESULT rc = saveHardware(config.hardwareMachine);
7794 if (FAILED(rc)) throw rc;
7795
7796 rc = saveStorageControllers(config.storageMachine);
7797 if (FAILED(rc)) throw rc;
7798
7799 // save machine's media registry if this is VirtualBox 3.3 or later
7800 if (config.canHaveOwnMediaRegistry())
7801 mParent->saveMediaRegistry(config.mediaRegistry,
7802 getId()); // only media with registry ID == machine UUID
7803 // this throws HRESULT
7804
7805 // save snapshots
7806 rc = saveAllSnapshots(config);
7807 if (FAILED(rc)) throw rc;
7808}
7809
7810/**
7811 * Saves all snapshots of the machine into the given machine config file. Called
7812 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
7813 * @param config
7814 * @return
7815 */
7816HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
7817{
7818 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7819
7820 HRESULT rc = S_OK;
7821
7822 try
7823 {
7824 config.llFirstSnapshot.clear();
7825
7826 if (mData->mFirstSnapshot)
7827 {
7828 settings::Snapshot snapNew;
7829 config.llFirstSnapshot.push_back(snapNew);
7830
7831 // get reference to the fresh copy of the snapshot on the list and
7832 // work on that copy directly to avoid excessive copying later
7833 settings::Snapshot &snap = config.llFirstSnapshot.front();
7834
7835 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
7836 if (FAILED(rc)) throw rc;
7837 }
7838
7839// if (mType == IsSessionMachine)
7840// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
7841
7842 }
7843 catch (HRESULT err)
7844 {
7845 /* we assume that error info is set by the thrower */
7846 rc = err;
7847 }
7848 catch (...)
7849 {
7850 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7851 }
7852
7853 return rc;
7854}
7855
7856/**
7857 * Saves the VM hardware configuration. It is assumed that the
7858 * given node is empty.
7859 *
7860 * @param aNode <Hardware> node to save the VM hardware confguration to.
7861 */
7862HRESULT Machine::saveHardware(settings::Hardware &data)
7863{
7864 HRESULT rc = S_OK;
7865
7866 try
7867 {
7868 /* The hardware version attribute (optional).
7869 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
7870 if ( mHWData->mHWVersion == "1"
7871 && mSSData->mStateFilePath.isEmpty()
7872 )
7873 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. */
7874
7875 data.strVersion = mHWData->mHWVersion;
7876 data.uuid = mHWData->mHardwareUUID;
7877
7878 // CPU
7879 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
7880 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
7881 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
7882 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
7883 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
7884 data.fPAE = !!mHWData->mPAEEnabled;
7885 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
7886
7887 /* Standard and Extended CPUID leafs. */
7888 data.llCpuIdLeafs.clear();
7889 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
7890 {
7891 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
7892 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
7893 }
7894 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
7895 {
7896 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
7897 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
7898 }
7899
7900 data.cCPUs = mHWData->mCPUCount;
7901 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
7902 data.ulCpuPriority = mHWData->mCpuPriority;
7903
7904 data.llCpus.clear();
7905 if (data.fCpuHotPlug)
7906 {
7907 for (unsigned idx = 0; idx < data.cCPUs; idx++)
7908 {
7909 if (mHWData->mCPUAttached[idx])
7910 {
7911 settings::Cpu cpu;
7912 cpu.ulId = idx;
7913 data.llCpus.push_back(cpu);
7914 }
7915 }
7916 }
7917
7918 // memory
7919 data.ulMemorySizeMB = mHWData->mMemorySize;
7920 data.fPageFusionEnabled = mHWData->mPageFusionEnabled;
7921
7922 // firmware
7923 data.firmwareType = mHWData->mFirmwareType;
7924
7925 // HID
7926 data.pointingHidType = mHWData->mPointingHidType;
7927 data.keyboardHidType = mHWData->mKeyboardHidType;
7928
7929 // HPET
7930 data.fHpetEnabled = !!mHWData->mHpetEnabled;
7931
7932 // boot order
7933 data.mapBootOrder.clear();
7934 for (size_t i = 0;
7935 i < RT_ELEMENTS(mHWData->mBootOrder);
7936 ++i)
7937 data.mapBootOrder[i] = mHWData->mBootOrder[i];
7938
7939 // display
7940 data.ulVRAMSizeMB = mHWData->mVRAMSize;
7941 data.cMonitors = mHWData->mMonitorCount;
7942 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
7943 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
7944
7945#ifdef VBOX_WITH_VRDP
7946 /* VRDP settings (optional) */
7947 rc = mVRDPServer->saveSettings(data.vrdpSettings);
7948 if (FAILED(rc)) throw rc;
7949#endif
7950
7951 /* BIOS (required) */
7952 rc = mBIOSSettings->saveSettings(data.biosSettings);
7953 if (FAILED(rc)) throw rc;
7954
7955 /* USB Controller (required) */
7956 rc = mUSBController->saveSettings(data.usbController);
7957 if (FAILED(rc)) throw rc;
7958
7959 /* Network adapters (required) */
7960 data.llNetworkAdapters.clear();
7961 for (ULONG slot = 0;
7962 slot < RT_ELEMENTS(mNetworkAdapters);
7963 ++slot)
7964 {
7965 settings::NetworkAdapter nic;
7966 nic.ulSlot = slot;
7967 rc = mNetworkAdapters[slot]->saveSettings(nic);
7968 if (FAILED(rc)) throw rc;
7969
7970 data.llNetworkAdapters.push_back(nic);
7971 }
7972
7973 /* Serial ports */
7974 data.llSerialPorts.clear();
7975 for (ULONG slot = 0;
7976 slot < RT_ELEMENTS(mSerialPorts);
7977 ++slot)
7978 {
7979 settings::SerialPort s;
7980 s.ulSlot = slot;
7981 rc = mSerialPorts[slot]->saveSettings(s);
7982 if (FAILED(rc)) return rc;
7983
7984 data.llSerialPorts.push_back(s);
7985 }
7986
7987 /* Parallel ports */
7988 data.llParallelPorts.clear();
7989 for (ULONG slot = 0;
7990 slot < RT_ELEMENTS(mParallelPorts);
7991 ++slot)
7992 {
7993 settings::ParallelPort p;
7994 p.ulSlot = slot;
7995 rc = mParallelPorts[slot]->saveSettings(p);
7996 if (FAILED(rc)) return rc;
7997
7998 data.llParallelPorts.push_back(p);
7999 }
8000
8001 /* Audio adapter */
8002 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8003 if (FAILED(rc)) return rc;
8004
8005 /* Shared folders */
8006 data.llSharedFolders.clear();
8007 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8008 it != mHWData->mSharedFolders.end();
8009 ++it)
8010 {
8011 ComObjPtr<SharedFolder> pFolder = *it;
8012 settings::SharedFolder sf;
8013 sf.strName = pFolder->getName();
8014 sf.strHostPath = pFolder->getHostPath();
8015 sf.fWritable = !!pFolder->isWritable();
8016 sf.fAutoMount = !!pFolder->isAutoMounted();
8017
8018 data.llSharedFolders.push_back(sf);
8019 }
8020
8021 // clipboard
8022 data.clipboardMode = mHWData->mClipboardMode;
8023
8024 /* Guest */
8025 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8026
8027 // IO settings
8028 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8029 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8030
8031 // guest properties
8032 data.llGuestProperties.clear();
8033#ifdef VBOX_WITH_GUEST_PROPS
8034 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8035 it != mHWData->mGuestProperties.end();
8036 ++it)
8037 {
8038 HWData::GuestProperty property = *it;
8039
8040 /* Remove transient guest properties at shutdown unless we
8041 * are saving state */
8042 if ( ( mData->mMachineState == MachineState_PoweredOff
8043 || mData->mMachineState == MachineState_Aborted
8044 || mData->mMachineState == MachineState_Teleported)
8045 && property.mFlags & guestProp::TRANSIENT)
8046 continue;
8047 settings::GuestProperty prop;
8048 prop.strName = property.strName;
8049 prop.strValue = property.strValue;
8050 prop.timestamp = property.mTimestamp;
8051 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8052 guestProp::writeFlags(property.mFlags, szFlags);
8053 prop.strFlags = szFlags;
8054
8055 data.llGuestProperties.push_back(prop);
8056 }
8057
8058 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8059 /* I presume this doesn't require a backup(). */
8060 mData->mGuestPropertiesModified = FALSE;
8061#endif /* VBOX_WITH_GUEST_PROPS defined */
8062 }
8063 catch(std::bad_alloc &)
8064 {
8065 return E_OUTOFMEMORY;
8066 }
8067
8068 AssertComRC(rc);
8069 return rc;
8070}
8071
8072/**
8073 * Saves the storage controller configuration.
8074 *
8075 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
8076 */
8077HRESULT Machine::saveStorageControllers(settings::Storage &data)
8078{
8079 data.llStorageControllers.clear();
8080
8081 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8082 it != mStorageControllers->end();
8083 ++it)
8084 {
8085 HRESULT rc;
8086 ComObjPtr<StorageController> pCtl = *it;
8087
8088 settings::StorageController ctl;
8089 ctl.strName = pCtl->getName();
8090 ctl.controllerType = pCtl->getControllerType();
8091 ctl.storageBus = pCtl->getStorageBus();
8092 ctl.ulInstance = pCtl->getInstance();
8093
8094 /* Save the port count. */
8095 ULONG portCount;
8096 rc = pCtl->COMGETTER(PortCount)(&portCount);
8097 ComAssertComRCRet(rc, rc);
8098 ctl.ulPortCount = portCount;
8099
8100 /* Save fUseHostIOCache */
8101 BOOL fUseHostIOCache;
8102 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8103 ComAssertComRCRet(rc, rc);
8104 ctl.fUseHostIOCache = !!fUseHostIOCache;
8105
8106 /* Save IDE emulation settings. */
8107 if (ctl.controllerType == StorageControllerType_IntelAhci)
8108 {
8109 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8110 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8111 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8112 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8113 )
8114 ComAssertComRCRet(rc, rc);
8115 }
8116
8117 /* save the devices now. */
8118 rc = saveStorageDevices(pCtl, ctl);
8119 ComAssertComRCRet(rc, rc);
8120
8121 data.llStorageControllers.push_back(ctl);
8122 }
8123
8124 return S_OK;
8125}
8126
8127/**
8128 * Saves the hard disk confguration.
8129 */
8130HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8131 settings::StorageController &data)
8132{
8133 MediaData::AttachmentList atts;
8134
8135 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()), atts);
8136 if (FAILED(rc)) return rc;
8137
8138 data.llAttachedDevices.clear();
8139 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8140 it != atts.end();
8141 ++it)
8142 {
8143 settings::AttachedDevice dev;
8144
8145 MediumAttachment *pAttach = *it;
8146 Medium *pMedium = pAttach->getMedium();
8147
8148 dev.deviceType = pAttach->getType();
8149 dev.lPort = pAttach->getPort();
8150 dev.lDevice = pAttach->getDevice();
8151 if (pMedium)
8152 {
8153 if (pMedium->isHostDrive())
8154 dev.strHostDriveSrc = pMedium->getLocation();
8155 else
8156 dev.uuid = pMedium->getId();
8157 dev.fPassThrough = pAttach->getPassthrough();
8158 }
8159
8160 data.llAttachedDevices.push_back(dev);
8161 }
8162
8163 return S_OK;
8164}
8165
8166/**
8167 * Saves machine state settings as defined by aFlags
8168 * (SaveSTS_* values).
8169 *
8170 * @param aFlags Combination of SaveSTS_* flags.
8171 *
8172 * @note Locks objects for writing.
8173 */
8174HRESULT Machine::saveStateSettings(int aFlags)
8175{
8176 if (aFlags == 0)
8177 return S_OK;
8178
8179 AutoCaller autoCaller(this);
8180 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8181
8182 /* This object's write lock is also necessary to serialize file access
8183 * (prevent concurrent reads and writes) */
8184 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8185
8186 HRESULT rc = S_OK;
8187
8188 Assert(mData->pMachineConfigFile);
8189
8190 try
8191 {
8192 if (aFlags & SaveSTS_CurStateModified)
8193 mData->pMachineConfigFile->fCurrentStateModified = true;
8194
8195 if (aFlags & SaveSTS_StateFilePath)
8196 {
8197 if (!mSSData->mStateFilePath.isEmpty())
8198 /* try to make the file name relative to the settings file dir */
8199 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8200 else
8201 mData->pMachineConfigFile->strStateFile.setNull();
8202 }
8203
8204 if (aFlags & SaveSTS_StateTimeStamp)
8205 {
8206 Assert( mData->mMachineState != MachineState_Aborted
8207 || mSSData->mStateFilePath.isEmpty());
8208
8209 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8210
8211 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8212//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8213 }
8214
8215 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8216 }
8217 catch (...)
8218 {
8219 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8220 }
8221
8222 return rc;
8223}
8224
8225/**
8226 * Creates differencing hard disks for all normal hard disks attached to this
8227 * machine and a new set of attachments to refer to created disks.
8228 *
8229 * Used when taking a snapshot or when deleting the current state. Gets called
8230 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8231 *
8232 * This method assumes that mMediaData contains the original hard disk attachments
8233 * it needs to create diffs for. On success, these attachments will be replaced
8234 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8235 * called to delete created diffs which will also rollback mMediaData and restore
8236 * whatever was backed up before calling this method.
8237 *
8238 * Attachments with non-normal hard disks are left as is.
8239 *
8240 * If @a aOnline is @c false then the original hard disks that require implicit
8241 * diffs will be locked for reading. Otherwise it is assumed that they are
8242 * already locked for writing (when the VM was started). Note that in the latter
8243 * case it is responsibility of the caller to lock the newly created diffs for
8244 * writing if this method succeeds.
8245 *
8246 * @param aProgress Progress object to run (must contain at least as
8247 * many operations left as the number of hard disks
8248 * attached).
8249 * @param aOnline Whether the VM was online prior to this operation.
8250 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8251 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8252 *
8253 * @note The progress object is not marked as completed, neither on success nor
8254 * on failure. This is a responsibility of the caller.
8255 *
8256 * @note Locks this object for writing.
8257 */
8258HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8259 ULONG aWeight,
8260 bool aOnline,
8261 bool *pfNeedsSaveSettings)
8262{
8263 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8264
8265 AutoCaller autoCaller(this);
8266 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8267
8268 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8269
8270 /* must be in a protective state because we leave the lock below */
8271 AssertReturn( mData->mMachineState == MachineState_Saving
8272 || mData->mMachineState == MachineState_LiveSnapshotting
8273 || mData->mMachineState == MachineState_RestoringSnapshot
8274 || mData->mMachineState == MachineState_DeletingSnapshot
8275 , E_FAIL);
8276
8277 HRESULT rc = S_OK;
8278
8279 MediumLockListMap lockedMediaOffline;
8280 MediumLockListMap *lockedMediaMap;
8281 if (aOnline)
8282 lockedMediaMap = &mData->mSession.mLockedMedia;
8283 else
8284 lockedMediaMap = &lockedMediaOffline;
8285
8286 try
8287 {
8288 if (!aOnline)
8289 {
8290 /* lock all attached hard disks early to detect "in use"
8291 * situations before creating actual diffs */
8292 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8293 it != mMediaData->mAttachments.end();
8294 ++it)
8295 {
8296 MediumAttachment* pAtt = *it;
8297 if (pAtt->getType() == DeviceType_HardDisk)
8298 {
8299 Medium* pMedium = pAtt->getMedium();
8300 Assert(pMedium);
8301
8302 MediumLockList *pMediumLockList(new MediumLockList());
8303 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8304 false /* fMediumLockWrite */,
8305 NULL,
8306 *pMediumLockList);
8307 if (FAILED(rc))
8308 {
8309 delete pMediumLockList;
8310 throw rc;
8311 }
8312 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8313 if (FAILED(rc))
8314 {
8315 throw setError(rc,
8316 tr("Collecting locking information for all attached media failed"));
8317 }
8318 }
8319 }
8320
8321 /* Now lock all media. If this fails, nothing is locked. */
8322 rc = lockedMediaMap->Lock();
8323 if (FAILED(rc))
8324 {
8325 throw setError(rc,
8326 tr("Locking of attached media failed"));
8327 }
8328 }
8329
8330 /* remember the current list (note that we don't use backup() since
8331 * mMediaData may be already backed up) */
8332 MediaData::AttachmentList atts = mMediaData->mAttachments;
8333
8334 /* start from scratch */
8335 mMediaData->mAttachments.clear();
8336
8337 /* go through remembered attachments and create diffs for normal hard
8338 * disks and attach them */
8339 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8340 it != atts.end();
8341 ++it)
8342 {
8343 MediumAttachment* pAtt = *it;
8344
8345 DeviceType_T devType = pAtt->getType();
8346 Medium* pMedium = pAtt->getMedium();
8347
8348 if ( devType != DeviceType_HardDisk
8349 || pMedium == NULL
8350 || pMedium->getType() != MediumType_Normal)
8351 {
8352 /* copy the attachment as is */
8353
8354 /** @todo the progress object created in Console::TakeSnaphot
8355 * only expects operations for hard disks. Later other
8356 * device types need to show up in the progress as well. */
8357 if (devType == DeviceType_HardDisk)
8358 {
8359 if (pMedium == NULL)
8360 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
8361 aWeight); // weight
8362 else
8363 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8364 pMedium->getBase()->getName().c_str()),
8365 aWeight); // weight
8366 }
8367
8368 mMediaData->mAttachments.push_back(pAtt);
8369 continue;
8370 }
8371
8372 /* need a diff */
8373 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8374 pMedium->getBase()->getName().c_str()),
8375 aWeight); // weight
8376
8377 ComObjPtr<Medium> diff;
8378 diff.createObject();
8379 rc = diff->init(mParent,
8380 pMedium->getPreferredDiffFormat(),
8381 Utf8Str(mUserData->m_strSnapshotFolderFull).append(RTPATH_SLASH_STR),
8382 pMedium->getRegistryMachineId(), // store the diff in the same registry as the parent
8383 pfNeedsSaveSettings);
8384 if (FAILED(rc)) throw rc;
8385
8386 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8387 * the push_back? Looks like we're going to leave medium with the
8388 * wrong kind of lock (general issue with if we fail anywhere at all)
8389 * and an orphaned VDI in the snapshots folder. */
8390
8391 /* update the appropriate lock list */
8392 MediumLockList *pMediumLockList;
8393 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8394 AssertComRCThrowRC(rc);
8395 if (aOnline)
8396 {
8397 rc = pMediumLockList->Update(pMedium, false);
8398 AssertComRCThrowRC(rc);
8399 }
8400
8401 /* leave the lock before the potentially lengthy operation */
8402 alock.leave();
8403 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8404 pMediumLockList,
8405 NULL /* aProgress */,
8406 true /* aWait */,
8407 pfNeedsSaveSettings);
8408 alock.enter();
8409 if (FAILED(rc)) throw rc;
8410
8411 rc = lockedMediaMap->Unlock();
8412 AssertComRCThrowRC(rc);
8413 rc = pMediumLockList->Append(diff, true);
8414 AssertComRCThrowRC(rc);
8415 rc = lockedMediaMap->Lock();
8416 AssertComRCThrowRC(rc);
8417
8418 rc = diff->addBackReference(mData->mUuid);
8419 AssertComRCThrowRC(rc);
8420
8421 /* add a new attachment */
8422 ComObjPtr<MediumAttachment> attachment;
8423 attachment.createObject();
8424 rc = attachment->init(this,
8425 diff,
8426 pAtt->getControllerName(),
8427 pAtt->getPort(),
8428 pAtt->getDevice(),
8429 DeviceType_HardDisk,
8430 true /* aImplicit */,
8431 0 /* No bandwidth limit */);
8432 if (FAILED(rc)) throw rc;
8433
8434 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8435 AssertComRCThrowRC(rc);
8436 mMediaData->mAttachments.push_back(attachment);
8437 }
8438 }
8439 catch (HRESULT aRC) { rc = aRC; }
8440
8441 /* unlock all hard disks we locked */
8442 if (!aOnline)
8443 {
8444 ErrorInfoKeeper eik;
8445
8446 rc = lockedMediaMap->Clear();
8447 AssertComRC(rc);
8448 }
8449
8450 if (FAILED(rc))
8451 {
8452 MultiResult mrc = rc;
8453
8454 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8455 }
8456
8457 return rc;
8458}
8459
8460/**
8461 * Deletes implicit differencing hard disks created either by
8462 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8463 *
8464 * Note that to delete hard disks created by #AttachMedium() this method is
8465 * called from #fixupMedia() when the changes are rolled back.
8466 *
8467 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8468 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8469 *
8470 * @note Locks this object for writing.
8471 */
8472HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8473{
8474 AutoCaller autoCaller(this);
8475 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8476
8477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8478 LogFlowThisFuncEnter();
8479
8480 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8481
8482 HRESULT rc = S_OK;
8483
8484 MediaData::AttachmentList implicitAtts;
8485
8486 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8487
8488 /* enumerate new attachments */
8489 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8490 it != mMediaData->mAttachments.end();
8491 ++it)
8492 {
8493 ComObjPtr<Medium> hd = (*it)->getMedium();
8494 if (hd.isNull())
8495 continue;
8496
8497 if ((*it)->isImplicit())
8498 {
8499 /* deassociate and mark for deletion */
8500 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8501 rc = hd->removeBackReference(mData->mUuid);
8502 AssertComRC(rc);
8503 implicitAtts.push_back(*it);
8504 continue;
8505 }
8506
8507 /* was this hard disk attached before? */
8508 if (!findAttachment(oldAtts, hd))
8509 {
8510 /* no: de-associate */
8511 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8512 rc = hd->removeBackReference(mData->mUuid);
8513 AssertComRC(rc);
8514 continue;
8515 }
8516 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8517 }
8518
8519 /* rollback hard disk changes */
8520 mMediaData.rollback();
8521
8522 MultiResult mrc(S_OK);
8523
8524 /* delete unused implicit diffs */
8525 if (implicitAtts.size() != 0)
8526 {
8527 /* will leave the lock before the potentially lengthy
8528 * operation, so protect with the special state (unless already
8529 * protected) */
8530 MachineState_T oldState = mData->mMachineState;
8531 if ( oldState != MachineState_Saving
8532 && oldState != MachineState_LiveSnapshotting
8533 && oldState != MachineState_RestoringSnapshot
8534 && oldState != MachineState_DeletingSnapshot
8535 && oldState != MachineState_DeletingSnapshotOnline
8536 && oldState != MachineState_DeletingSnapshotPaused
8537 )
8538 setMachineState(MachineState_SettingUp);
8539
8540 alock.leave();
8541
8542 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8543 it != implicitAtts.end();
8544 ++it)
8545 {
8546 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8547 ComObjPtr<Medium> hd = (*it)->getMedium();
8548
8549 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8550 pfNeedsSaveSettings);
8551 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8552 mrc = rc;
8553 }
8554
8555 alock.enter();
8556
8557 if (mData->mMachineState == MachineState_SettingUp)
8558 {
8559 setMachineState(oldState);
8560 }
8561 }
8562
8563 return mrc;
8564}
8565
8566/**
8567 * Looks through the given list of media attachments for one with the given parameters
8568 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8569 * can be searched as well if needed.
8570 *
8571 * @param list
8572 * @param aControllerName
8573 * @param aControllerPort
8574 * @param aDevice
8575 * @return
8576 */
8577MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8578 IN_BSTR aControllerName,
8579 LONG aControllerPort,
8580 LONG aDevice)
8581{
8582 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8583 it != ll.end();
8584 ++it)
8585 {
8586 MediumAttachment *pAttach = *it;
8587 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8588 return pAttach;
8589 }
8590
8591 return NULL;
8592}
8593
8594/**
8595 * Looks through the given list of media attachments for one with the given parameters
8596 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8597 * can be searched as well if needed.
8598 *
8599 * @param list
8600 * @param aControllerName
8601 * @param aControllerPort
8602 * @param aDevice
8603 * @return
8604 */
8605MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8606 ComObjPtr<Medium> pMedium)
8607{
8608 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8609 it != ll.end();
8610 ++it)
8611 {
8612 MediumAttachment *pAttach = *it;
8613 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8614 if (pMediumThis == pMedium)
8615 return pAttach;
8616 }
8617
8618 return NULL;
8619}
8620
8621/**
8622 * Looks through the given list of media attachments for one with the given parameters
8623 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8624 * can be searched as well if needed.
8625 *
8626 * @param list
8627 * @param aControllerName
8628 * @param aControllerPort
8629 * @param aDevice
8630 * @return
8631 */
8632MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8633 Guid &id)
8634{
8635 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8636 it != ll.end();
8637 ++it)
8638 {
8639 MediumAttachment *pAttach = *it;
8640 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8641 if (pMediumThis->getId() == id)
8642 return pAttach;
8643 }
8644
8645 return NULL;
8646}
8647
8648/**
8649 * Main implementation for Machine::DetachDevice. This also gets called
8650 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8651 *
8652 * @param pAttach Medium attachment to detach.
8653 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8654 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8655 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8656 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8657 * @return
8658 */
8659HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8660 AutoWriteLock &writeLock,
8661 Snapshot *pSnapshot,
8662 bool *pfNeedsSaveSettings)
8663{
8664 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8665 DeviceType_T mediumType = pAttach->getType();
8666
8667 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8668
8669 if (pAttach->isImplicit())
8670 {
8671 /* attempt to implicitly delete the implicitly created diff */
8672
8673 /// @todo move the implicit flag from MediumAttachment to Medium
8674 /// and forbid any hard disk operation when it is implicit. Or maybe
8675 /// a special media state for it to make it even more simple.
8676
8677 Assert(mMediaData.isBackedUp());
8678
8679 /* will leave the lock before the potentially lengthy operation, so
8680 * protect with the special state */
8681 MachineState_T oldState = mData->mMachineState;
8682 setMachineState(MachineState_SettingUp);
8683
8684 writeLock.release();
8685
8686 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8687 pfNeedsSaveSettings);
8688
8689 writeLock.acquire();
8690
8691 setMachineState(oldState);
8692
8693 if (FAILED(rc)) return rc;
8694 }
8695
8696 setModified(IsModified_Storage);
8697 mMediaData.backup();
8698
8699 // we cannot use erase (it) below because backup() above will create
8700 // a copy of the list and make this copy active, but the iterator
8701 // still refers to the original and is not valid for the copy
8702 mMediaData->mAttachments.remove(pAttach);
8703
8704 if (!oldmedium.isNull())
8705 {
8706 // if this is from a snapshot, do not defer detachment to commitMedia()
8707 if (pSnapshot)
8708 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8709 // else if non-hard disk media, do not defer detachment to commitMedia() either
8710 else if (mediumType != DeviceType_HardDisk)
8711 oldmedium->removeBackReference(mData->mUuid);
8712 }
8713
8714 return S_OK;
8715}
8716
8717/**
8718 * Goes thru all medium attachments of the list and calls detachDevice() on each
8719 * of them and attaches all Medium objects found in the process to the given list,
8720 * depending on cleanupMode.
8721 *
8722 * This gets called from Machine::Unregister, both for the actual Machine and
8723 * the SnapshotMachine objects that might be found in the snapshots.
8724 *
8725 * Requires caller and locking.
8726 *
8727 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8728 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8729 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
8730 * otherwise no media get added.
8731 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
8732 * @return
8733 */
8734HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8735 Snapshot *pSnapshot,
8736 CleanupMode_T cleanupMode,
8737 MediaList &llMedia)
8738{
8739 Assert(isWriteLockOnCurrentThread());
8740
8741 HRESULT rc;
8742
8743 // make a temporary list because detachDevice invalidates iterators into
8744 // mMediaData->mAttachments
8745 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8746
8747 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8748 it != llAttachments2.end();
8749 ++it)
8750 {
8751 ComObjPtr<MediumAttachment> pAttach = *it;
8752 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8753
8754 if (!pMedium.isNull())
8755 {
8756 DeviceType_T devType = pMedium->getDeviceType();
8757 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
8758 && devType == DeviceType_HardDisk)
8759 || (cleanupMode == CleanupMode_Full)
8760 )
8761 llMedia.push_back(pMedium);
8762 }
8763
8764 // real machine: then we need to use the proper method
8765 rc = detachDevice(pAttach,
8766 writeLock,
8767 pSnapshot,
8768 NULL /* pfNeedsSaveSettings */);
8769
8770 if (FAILED(rc))
8771 return rc;
8772 }
8773
8774 return S_OK;
8775}
8776
8777/**
8778 * Perform deferred hard disk detachments.
8779 *
8780 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8781 * backed up).
8782 *
8783 * If @a aOnline is @c true then this method will also unlock the old hard disks
8784 * for which the new implicit diffs were created and will lock these new diffs for
8785 * writing.
8786 *
8787 * @param aOnline Whether the VM was online prior to this operation.
8788 *
8789 * @note Locks this object for writing!
8790 */
8791void Machine::commitMedia(bool aOnline /*= false*/)
8792{
8793 AutoCaller autoCaller(this);
8794 AssertComRCReturnVoid(autoCaller.rc());
8795
8796 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8797
8798 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
8799
8800 HRESULT rc = S_OK;
8801
8802 /* no attach/detach operations -- nothing to do */
8803 if (!mMediaData.isBackedUp())
8804 return;
8805
8806 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8807 bool fMediaNeedsLocking = false;
8808
8809 /* enumerate new attachments */
8810 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8811 it != mMediaData->mAttachments.end();
8812 ++it)
8813 {
8814 MediumAttachment *pAttach = *it;
8815
8816 pAttach->commit();
8817
8818 Medium* pMedium = pAttach->getMedium();
8819 bool fImplicit = pAttach->isImplicit();
8820
8821 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
8822 (pMedium) ? pMedium->getName().c_str() : "NULL",
8823 fImplicit));
8824
8825 /** @todo convert all this Machine-based voodoo to MediumAttachment
8826 * based commit logic. */
8827 if (fImplicit)
8828 {
8829 /* convert implicit attachment to normal */
8830 pAttach->setImplicit(false);
8831
8832 if ( aOnline
8833 && pMedium
8834 && pAttach->getType() == DeviceType_HardDisk
8835 )
8836 {
8837 ComObjPtr<Medium> parent = pMedium->getParent();
8838 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8839
8840 /* update the appropriate lock list */
8841 MediumLockList *pMediumLockList;
8842 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8843 AssertComRC(rc);
8844 if (pMediumLockList)
8845 {
8846 /* unlock if there's a need to change the locking */
8847 if (!fMediaNeedsLocking)
8848 {
8849 rc = mData->mSession.mLockedMedia.Unlock();
8850 AssertComRC(rc);
8851 fMediaNeedsLocking = true;
8852 }
8853 rc = pMediumLockList->Update(parent, false);
8854 AssertComRC(rc);
8855 rc = pMediumLockList->Append(pMedium, true);
8856 AssertComRC(rc);
8857 }
8858 }
8859
8860 continue;
8861 }
8862
8863 if (pMedium)
8864 {
8865 /* was this medium attached before? */
8866 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
8867 oldIt != oldAtts.end();
8868 ++oldIt)
8869 {
8870 MediumAttachment *pOldAttach = *oldIt;
8871 if (pOldAttach->getMedium() == pMedium)
8872 {
8873 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
8874
8875 /* yes: remove from old to avoid de-association */
8876 oldAtts.erase(oldIt);
8877 break;
8878 }
8879 }
8880 }
8881 }
8882
8883 /* enumerate remaining old attachments and de-associate from the
8884 * current machine state */
8885 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
8886 it != oldAtts.end();
8887 ++it)
8888 {
8889 MediumAttachment *pAttach = *it;
8890 Medium* pMedium = pAttach->getMedium();
8891
8892 /* Detach only hard disks, since DVD/floppy media is detached
8893 * instantly in MountMedium. */
8894 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
8895 {
8896 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
8897
8898 /* now de-associate from the current machine state */
8899 rc = pMedium->removeBackReference(mData->mUuid);
8900 AssertComRC(rc);
8901
8902 if (aOnline)
8903 {
8904 /* unlock since medium is not used anymore */
8905 MediumLockList *pMediumLockList;
8906 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8907 AssertComRC(rc);
8908 if (pMediumLockList)
8909 {
8910 rc = mData->mSession.mLockedMedia.Remove(pAttach);
8911 AssertComRC(rc);
8912 }
8913 }
8914 }
8915 }
8916
8917 /* take media locks again so that the locking state is consistent */
8918 if (fMediaNeedsLocking)
8919 {
8920 Assert(aOnline);
8921 rc = mData->mSession.mLockedMedia.Lock();
8922 AssertComRC(rc);
8923 }
8924
8925 /* commit the hard disk changes */
8926 mMediaData.commit();
8927
8928 if (isSessionMachine())
8929 {
8930 /* attach new data to the primary machine and reshare it */
8931 mPeer->mMediaData.attach(mMediaData);
8932 }
8933
8934 return;
8935}
8936
8937/**
8938 * Perform deferred deletion of implicitly created diffs.
8939 *
8940 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8941 * backed up).
8942 *
8943 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8944 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8945 *
8946 * @note Locks this object for writing!
8947 */
8948void Machine::rollbackMedia()
8949{
8950 AutoCaller autoCaller(this);
8951 AssertComRCReturnVoid (autoCaller.rc());
8952
8953 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8954
8955 LogFlowThisFunc(("Entering\n"));
8956
8957 HRESULT rc = S_OK;
8958
8959 /* no attach/detach operations -- nothing to do */
8960 if (!mMediaData.isBackedUp())
8961 return;
8962
8963 /* enumerate new attachments */
8964 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8965 it != mMediaData->mAttachments.end();
8966 ++it)
8967 {
8968 MediumAttachment *pAttach = *it;
8969 /* Fix up the backrefs for DVD/floppy media. */
8970 if (pAttach->getType() != DeviceType_HardDisk)
8971 {
8972 Medium* pMedium = pAttach->getMedium();
8973 if (pMedium)
8974 {
8975 rc = pMedium->removeBackReference(mData->mUuid);
8976 AssertComRC(rc);
8977 }
8978 }
8979
8980 (*it)->rollback();
8981
8982 pAttach = *it;
8983 /* Fix up the backrefs for DVD/floppy media. */
8984 if (pAttach->getType() != DeviceType_HardDisk)
8985 {
8986 Medium* pMedium = pAttach->getMedium();
8987 if (pMedium)
8988 {
8989 rc = pMedium->addBackReference(mData->mUuid);
8990 AssertComRC(rc);
8991 }
8992 }
8993 }
8994
8995 /** @todo convert all this Machine-based voodoo to MediumAttachment
8996 * based rollback logic. */
8997 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
8998 // which gets called if Machine::registeredInit() fails...
8999 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9000
9001 return;
9002}
9003
9004/**
9005 * Returns true if the settings file is located in the directory named exactly
9006 * as the machine. This will be true if the machine settings structure was
9007 * created by default in #openConfigLoader().
9008 *
9009 * @param aSettingsDir if not NULL, the full machine settings file directory
9010 * name will be assigned there.
9011 *
9012 * @note Doesn't lock anything.
9013 * @note Not thread safe (must be called from this object's lock).
9014 */
9015bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9016{
9017 Utf8Str settingsDir = mData->m_strConfigFileFull;
9018 settingsDir.stripFilename();
9019 Utf8Str strDirName = RTPathFilename(settingsDir.c_str());
9020
9021 AssertReturn(!strDirName.isEmpty(), false);
9022
9023 /* if we don't rename anything on name change, return false shorlty */
9024 if (!mUserData->s.fNameSync)
9025 return false;
9026
9027 if (aSettingsDir)
9028 *aSettingsDir = settingsDir;
9029
9030 return strDirName == mUserData->s.strName;
9031}
9032
9033/**
9034 * Discards all changes to machine settings.
9035 *
9036 * @param aNotify Whether to notify the direct session about changes or not.
9037 *
9038 * @note Locks objects for writing!
9039 */
9040void Machine::rollback(bool aNotify)
9041{
9042 AutoCaller autoCaller(this);
9043 AssertComRCReturn(autoCaller.rc(), (void)0);
9044
9045 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9046
9047 if (!mStorageControllers.isNull())
9048 {
9049 if (mStorageControllers.isBackedUp())
9050 {
9051 /* unitialize all new devices (absent in the backed up list). */
9052 StorageControllerList::const_iterator it = mStorageControllers->begin();
9053 StorageControllerList *backedList = mStorageControllers.backedUpData();
9054 while (it != mStorageControllers->end())
9055 {
9056 if ( std::find(backedList->begin(), backedList->end(), *it)
9057 == backedList->end()
9058 )
9059 {
9060 (*it)->uninit();
9061 }
9062 ++it;
9063 }
9064
9065 /* restore the list */
9066 mStorageControllers.rollback();
9067 }
9068
9069 /* rollback any changes to devices after restoring the list */
9070 if (mData->flModifications & IsModified_Storage)
9071 {
9072 StorageControllerList::const_iterator it = mStorageControllers->begin();
9073 while (it != mStorageControllers->end())
9074 {
9075 (*it)->rollback();
9076 ++it;
9077 }
9078 }
9079 }
9080
9081 mUserData.rollback();
9082
9083 mHWData.rollback();
9084
9085 if (mData->flModifications & IsModified_Storage)
9086 rollbackMedia();
9087
9088 if (mBIOSSettings)
9089 mBIOSSettings->rollback();
9090
9091#ifdef VBOX_WITH_VRDP
9092 if (mVRDPServer && (mData->flModifications & IsModified_VRDPServer))
9093 mVRDPServer->rollback();
9094#endif
9095
9096 if (mAudioAdapter)
9097 mAudioAdapter->rollback();
9098
9099 if (mUSBController && (mData->flModifications & IsModified_USB))
9100 mUSBController->rollback();
9101
9102 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9103 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9104 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9105
9106 if (mData->flModifications & IsModified_NetworkAdapters)
9107 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9108 if ( mNetworkAdapters[slot]
9109 && mNetworkAdapters[slot]->isModified())
9110 {
9111 mNetworkAdapters[slot]->rollback();
9112 networkAdapters[slot] = mNetworkAdapters[slot];
9113 }
9114
9115 if (mData->flModifications & IsModified_SerialPorts)
9116 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9117 if ( mSerialPorts[slot]
9118 && mSerialPorts[slot]->isModified())
9119 {
9120 mSerialPorts[slot]->rollback();
9121 serialPorts[slot] = mSerialPorts[slot];
9122 }
9123
9124 if (mData->flModifications & IsModified_ParallelPorts)
9125 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9126 if ( mParallelPorts[slot]
9127 && mParallelPorts[slot]->isModified())
9128 {
9129 mParallelPorts[slot]->rollback();
9130 parallelPorts[slot] = mParallelPorts[slot];
9131 }
9132
9133 if (aNotify)
9134 {
9135 /* inform the direct session about changes */
9136
9137 ComObjPtr<Machine> that = this;
9138 uint32_t flModifications = mData->flModifications;
9139 alock.leave();
9140
9141 if (flModifications & IsModified_SharedFolders)
9142 that->onSharedFolderChange();
9143
9144 if (flModifications & IsModified_VRDPServer)
9145 that->onVRDPServerChange(/* aRestart */ TRUE);
9146 if (flModifications & IsModified_USB)
9147 that->onUSBControllerChange();
9148
9149 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9150 if (networkAdapters[slot])
9151 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9152 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9153 if (serialPorts[slot])
9154 that->onSerialPortChange(serialPorts[slot]);
9155 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9156 if (parallelPorts[slot])
9157 that->onParallelPortChange(parallelPorts[slot]);
9158
9159 if (flModifications & IsModified_Storage)
9160 that->onStorageControllerChange();
9161 }
9162}
9163
9164/**
9165 * Commits all the changes to machine settings.
9166 *
9167 * Note that this operation is supposed to never fail.
9168 *
9169 * @note Locks this object and children for writing.
9170 */
9171void Machine::commit()
9172{
9173 AutoCaller autoCaller(this);
9174 AssertComRCReturnVoid(autoCaller.rc());
9175
9176 AutoCaller peerCaller(mPeer);
9177 AssertComRCReturnVoid(peerCaller.rc());
9178
9179 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9180
9181 /*
9182 * use safe commit to ensure Snapshot machines (that share mUserData)
9183 * will still refer to a valid memory location
9184 */
9185 mUserData.commitCopy();
9186
9187 mHWData.commit();
9188
9189 if (mMediaData.isBackedUp())
9190 commitMedia();
9191
9192 mBIOSSettings->commit();
9193#ifdef VBOX_WITH_VRDP
9194 mVRDPServer->commit();
9195#endif
9196 mAudioAdapter->commit();
9197 mUSBController->commit();
9198
9199 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9200 mNetworkAdapters[slot]->commit();
9201 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9202 mSerialPorts[slot]->commit();
9203 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9204 mParallelPorts[slot]->commit();
9205
9206 bool commitStorageControllers = false;
9207
9208 if (mStorageControllers.isBackedUp())
9209 {
9210 mStorageControllers.commit();
9211
9212 if (mPeer)
9213 {
9214 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9215
9216 /* Commit all changes to new controllers (this will reshare data with
9217 * peers for thos who have peers) */
9218 StorageControllerList *newList = new StorageControllerList();
9219 StorageControllerList::const_iterator it = mStorageControllers->begin();
9220 while (it != mStorageControllers->end())
9221 {
9222 (*it)->commit();
9223
9224 /* look if this controller has a peer device */
9225 ComObjPtr<StorageController> peer = (*it)->getPeer();
9226 if (!peer)
9227 {
9228 /* no peer means the device is a newly created one;
9229 * create a peer owning data this device share it with */
9230 peer.createObject();
9231 peer->init(mPeer, *it, true /* aReshare */);
9232 }
9233 else
9234 {
9235 /* remove peer from the old list */
9236 mPeer->mStorageControllers->remove(peer);
9237 }
9238 /* and add it to the new list */
9239 newList->push_back(peer);
9240
9241 ++it;
9242 }
9243
9244 /* uninit old peer's controllers that are left */
9245 it = mPeer->mStorageControllers->begin();
9246 while (it != mPeer->mStorageControllers->end())
9247 {
9248 (*it)->uninit();
9249 ++it;
9250 }
9251
9252 /* attach new list of controllers to our peer */
9253 mPeer->mStorageControllers.attach(newList);
9254 }
9255 else
9256 {
9257 /* we have no peer (our parent is the newly created machine);
9258 * just commit changes to devices */
9259 commitStorageControllers = true;
9260 }
9261 }
9262 else
9263 {
9264 /* the list of controllers itself is not changed,
9265 * just commit changes to controllers themselves */
9266 commitStorageControllers = true;
9267 }
9268
9269 if (commitStorageControllers)
9270 {
9271 StorageControllerList::const_iterator it = mStorageControllers->begin();
9272 while (it != mStorageControllers->end())
9273 {
9274 (*it)->commit();
9275 ++it;
9276 }
9277 }
9278
9279 if (isSessionMachine())
9280 {
9281 /* attach new data to the primary machine and reshare it */
9282 mPeer->mUserData.attach(mUserData);
9283 mPeer->mHWData.attach(mHWData);
9284 /* mMediaData is reshared by fixupMedia */
9285 // mPeer->mMediaData.attach(mMediaData);
9286 Assert(mPeer->mMediaData.data() == mMediaData.data());
9287 }
9288}
9289
9290/**
9291 * Copies all the hardware data from the given machine.
9292 *
9293 * Currently, only called when the VM is being restored from a snapshot. In
9294 * particular, this implies that the VM is not running during this method's
9295 * call.
9296 *
9297 * @note This method must be called from under this object's lock.
9298 *
9299 * @note This method doesn't call #commit(), so all data remains backed up and
9300 * unsaved.
9301 */
9302void Machine::copyFrom(Machine *aThat)
9303{
9304 AssertReturnVoid(!isSnapshotMachine());
9305 AssertReturnVoid(aThat->isSnapshotMachine());
9306
9307 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9308
9309 mHWData.assignCopy(aThat->mHWData);
9310
9311 // create copies of all shared folders (mHWData after attiching a copy
9312 // contains just references to original objects)
9313 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9314 it != mHWData->mSharedFolders.end();
9315 ++it)
9316 {
9317 ComObjPtr<SharedFolder> folder;
9318 folder.createObject();
9319 HRESULT rc = folder->initCopy(getMachine(), *it);
9320 AssertComRC(rc);
9321 *it = folder;
9322 }
9323
9324 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9325#ifdef VBOX_WITH_VRDP
9326 mVRDPServer->copyFrom(aThat->mVRDPServer);
9327#endif
9328 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9329 mUSBController->copyFrom(aThat->mUSBController);
9330
9331 /* create private copies of all controllers */
9332 mStorageControllers.backup();
9333 mStorageControllers->clear();
9334 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9335 it != aThat->mStorageControllers->end();
9336 ++it)
9337 {
9338 ComObjPtr<StorageController> ctrl;
9339 ctrl.createObject();
9340 ctrl->initCopy(this, *it);
9341 mStorageControllers->push_back(ctrl);
9342 }
9343
9344 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9345 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9346 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9347 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9348 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9349 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9350}
9351
9352#ifdef VBOX_WITH_RESOURCE_USAGE_API
9353
9354void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9355{
9356 AssertReturnVoid(isWriteLockOnCurrentThread());
9357 AssertPtrReturnVoid(aCollector);
9358
9359 pm::CollectorHAL *hal = aCollector->getHAL();
9360 /* Create sub metrics */
9361 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9362 "Percentage of processor time spent in user mode by the VM process.");
9363 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9364 "Percentage of processor time spent in kernel mode by the VM process.");
9365 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9366 "Size of resident portion of VM process in memory.");
9367 /* Create and register base metrics */
9368 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9369 cpuLoadUser, cpuLoadKernel);
9370 aCollector->registerBaseMetric(cpuLoad);
9371 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9372 ramUsageUsed);
9373 aCollector->registerBaseMetric(ramUsage);
9374
9375 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9376 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9377 new pm::AggregateAvg()));
9378 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9379 new pm::AggregateMin()));
9380 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9381 new pm::AggregateMax()));
9382 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9383 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9384 new pm::AggregateAvg()));
9385 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9386 new pm::AggregateMin()));
9387 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9388 new pm::AggregateMax()));
9389
9390 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9391 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9392 new pm::AggregateAvg()));
9393 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9394 new pm::AggregateMin()));
9395 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9396 new pm::AggregateMax()));
9397
9398
9399 /* Guest metrics */
9400 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9401
9402 /* Create sub metrics */
9403 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9404 "Percentage of processor time spent in user mode as seen by the guest.");
9405 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9406 "Percentage of processor time spent in kernel mode as seen by the guest.");
9407 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9408 "Percentage of processor time spent idling as seen by the guest.");
9409
9410 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9411 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9412 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9413 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9414 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9415 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9416
9417 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9418
9419 /* Create and register base metrics */
9420 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9421 aCollector->registerBaseMetric(guestCpuLoad);
9422
9423 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9424 guestMemCache, guestPagedTotal);
9425 aCollector->registerBaseMetric(guestCpuMem);
9426
9427 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9428 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9429 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9430 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9431
9432 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9433 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9434 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9435 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9436
9437 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9438 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9439 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9440 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9441
9442 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9443 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9444 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9445 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9446
9447 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9448 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9449 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9450 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9451
9452 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9453 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9454 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9455 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9456
9457 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9458 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9459 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9460 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9461
9462 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9463 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9464 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9465 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9466
9467 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9468 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9469 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9470 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9471}
9472
9473void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9474{
9475 AssertReturnVoid(isWriteLockOnCurrentThread());
9476
9477 if (aCollector)
9478 {
9479 aCollector->unregisterMetricsFor(aMachine);
9480 aCollector->unregisterBaseMetricsFor(aMachine);
9481 }
9482
9483 if (mGuestHAL)
9484 {
9485 delete mGuestHAL;
9486 mGuestHAL = NULL;
9487 }
9488}
9489
9490#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9491
9492
9493////////////////////////////////////////////////////////////////////////////////
9494
9495DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9496
9497HRESULT SessionMachine::FinalConstruct()
9498{
9499 LogFlowThisFunc(("\n"));
9500
9501#if defined(RT_OS_WINDOWS)
9502 mIPCSem = NULL;
9503#elif defined(RT_OS_OS2)
9504 mIPCSem = NULLHANDLE;
9505#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9506 mIPCSem = -1;
9507#else
9508# error "Port me!"
9509#endif
9510
9511 return S_OK;
9512}
9513
9514void SessionMachine::FinalRelease()
9515{
9516 LogFlowThisFunc(("\n"));
9517
9518 uninit(Uninit::Unexpected);
9519}
9520
9521/**
9522 * @note Must be called only by Machine::openSession() from its own write lock.
9523 */
9524HRESULT SessionMachine::init(Machine *aMachine)
9525{
9526 LogFlowThisFuncEnter();
9527 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9528
9529 AssertReturn(aMachine, E_INVALIDARG);
9530
9531 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9532
9533 /* Enclose the state transition NotReady->InInit->Ready */
9534 AutoInitSpan autoInitSpan(this);
9535 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9536
9537 /* create the interprocess semaphore */
9538#if defined(RT_OS_WINDOWS)
9539 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9540 for (size_t i = 0; i < mIPCSemName.length(); i++)
9541 if (mIPCSemName[i] == '\\')
9542 mIPCSemName[i] = '/';
9543 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName);
9544 ComAssertMsgRet(mIPCSem,
9545 ("Cannot create IPC mutex '%ls', err=%d",
9546 mIPCSemName.raw(), ::GetLastError()),
9547 E_FAIL);
9548#elif defined(RT_OS_OS2)
9549 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9550 aMachine->mData->mUuid.raw());
9551 mIPCSemName = ipcSem;
9552 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.raw(), &mIPCSem, 0, FALSE);
9553 ComAssertMsgRet(arc == NO_ERROR,
9554 ("Cannot create IPC mutex '%s', arc=%ld",
9555 ipcSem.raw(), arc),
9556 E_FAIL);
9557#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9558# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9559# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9560 /** @todo Check that this still works correctly. */
9561 AssertCompileSize(key_t, 8);
9562# else
9563 AssertCompileSize(key_t, 4);
9564# endif
9565 key_t key;
9566 mIPCSem = -1;
9567 mIPCKey = "0";
9568 for (uint32_t i = 0; i < 1 << 24; i++)
9569 {
9570 key = ((uint32_t)'V' << 24) | i;
9571 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9572 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9573 {
9574 mIPCSem = sem;
9575 if (sem >= 0)
9576 mIPCKey = BstrFmt("%u", key);
9577 break;
9578 }
9579 }
9580# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9581 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9582 char *pszSemName = NULL;
9583 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9584 key_t key = ::ftok(pszSemName, 'V');
9585 RTStrFree(pszSemName);
9586
9587 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9588# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9589
9590 int errnoSave = errno;
9591 if (mIPCSem < 0 && errnoSave == ENOSYS)
9592 {
9593 setError(E_FAIL,
9594 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9595 "support for SysV IPC. Check the host kernel configuration for "
9596 "CONFIG_SYSVIPC=y"));
9597 return E_FAIL;
9598 }
9599 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9600 * the IPC semaphores */
9601 if (mIPCSem < 0 && errnoSave == ENOSPC)
9602 {
9603#ifdef RT_OS_LINUX
9604 setError(E_FAIL,
9605 tr("Cannot create IPC semaphore because the system limit for the "
9606 "maximum number of semaphore sets (SEMMNI), or the system wide "
9607 "maximum number of sempahores (SEMMNS) would be exceeded. The "
9608 "current set of SysV IPC semaphores can be determined from "
9609 "the file /proc/sysvipc/sem"));
9610#else
9611 setError(E_FAIL,
9612 tr("Cannot create IPC semaphore because the system-imposed limit "
9613 "on the maximum number of allowed semaphores or semaphore "
9614 "identifiers system-wide would be exceeded"));
9615#endif
9616 return E_FAIL;
9617 }
9618 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9619 E_FAIL);
9620 /* set the initial value to 1 */
9621 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9622 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9623 E_FAIL);
9624#else
9625# error "Port me!"
9626#endif
9627
9628 /* memorize the peer Machine */
9629 unconst(mPeer) = aMachine;
9630 /* share the parent pointer */
9631 unconst(mParent) = aMachine->mParent;
9632
9633 /* take the pointers to data to share */
9634 mData.share(aMachine->mData);
9635 mSSData.share(aMachine->mSSData);
9636
9637 mUserData.share(aMachine->mUserData);
9638 mHWData.share(aMachine->mHWData);
9639 mMediaData.share(aMachine->mMediaData);
9640
9641 mStorageControllers.allocate();
9642 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9643 it != aMachine->mStorageControllers->end();
9644 ++it)
9645 {
9646 ComObjPtr<StorageController> ctl;
9647 ctl.createObject();
9648 ctl->init(this, *it);
9649 mStorageControllers->push_back(ctl);
9650 }
9651
9652 unconst(mBIOSSettings).createObject();
9653 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9654#ifdef VBOX_WITH_VRDP
9655 /* create another VRDPServer object that will be mutable */
9656 unconst(mVRDPServer).createObject();
9657 mVRDPServer->init(this, aMachine->mVRDPServer);
9658#endif
9659 /* create another audio adapter object that will be mutable */
9660 unconst(mAudioAdapter).createObject();
9661 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9662 /* create a list of serial ports that will be mutable */
9663 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9664 {
9665 unconst(mSerialPorts[slot]).createObject();
9666 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9667 }
9668 /* create a list of parallel ports that will be mutable */
9669 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9670 {
9671 unconst(mParallelPorts[slot]).createObject();
9672 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9673 }
9674 /* create another USB controller object that will be mutable */
9675 unconst(mUSBController).createObject();
9676 mUSBController->init(this, aMachine->mUSBController);
9677
9678 /* create a list of network adapters that will be mutable */
9679 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9680 {
9681 unconst(mNetworkAdapters[slot]).createObject();
9682 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9683 }
9684
9685 /* default is to delete saved state on Saved -> PoweredOff transition */
9686 mRemoveSavedState = true;
9687
9688 /* Confirm a successful initialization when it's the case */
9689 autoInitSpan.setSucceeded();
9690
9691 LogFlowThisFuncLeave();
9692 return S_OK;
9693}
9694
9695/**
9696 * Uninitializes this session object. If the reason is other than
9697 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9698 *
9699 * @param aReason uninitialization reason
9700 *
9701 * @note Locks mParent + this object for writing.
9702 */
9703void SessionMachine::uninit(Uninit::Reason aReason)
9704{
9705 LogFlowThisFuncEnter();
9706 LogFlowThisFunc(("reason=%d\n", aReason));
9707
9708 /*
9709 * Strongly reference ourselves to prevent this object deletion after
9710 * mData->mSession.mMachine.setNull() below (which can release the last
9711 * reference and call the destructor). Important: this must be done before
9712 * accessing any members (and before AutoUninitSpan that does it as well).
9713 * This self reference will be released as the very last step on return.
9714 */
9715 ComObjPtr<SessionMachine> selfRef = this;
9716
9717 /* Enclose the state transition Ready->InUninit->NotReady */
9718 AutoUninitSpan autoUninitSpan(this);
9719 if (autoUninitSpan.uninitDone())
9720 {
9721 LogFlowThisFunc(("Already uninitialized\n"));
9722 LogFlowThisFuncLeave();
9723 return;
9724 }
9725
9726 if (autoUninitSpan.initFailed())
9727 {
9728 /* We've been called by init() because it's failed. It's not really
9729 * necessary (nor it's safe) to perform the regular uninit sequense
9730 * below, the following is enough.
9731 */
9732 LogFlowThisFunc(("Initialization failed.\n"));
9733#if defined(RT_OS_WINDOWS)
9734 if (mIPCSem)
9735 ::CloseHandle(mIPCSem);
9736 mIPCSem = NULL;
9737#elif defined(RT_OS_OS2)
9738 if (mIPCSem != NULLHANDLE)
9739 ::DosCloseMutexSem(mIPCSem);
9740 mIPCSem = NULLHANDLE;
9741#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9742 if (mIPCSem >= 0)
9743 ::semctl(mIPCSem, 0, IPC_RMID);
9744 mIPCSem = -1;
9745# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9746 mIPCKey = "0";
9747# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9748#else
9749# error "Port me!"
9750#endif
9751 uninitDataAndChildObjects();
9752 mData.free();
9753 unconst(mParent) = NULL;
9754 unconst(mPeer) = NULL;
9755 LogFlowThisFuncLeave();
9756 return;
9757 }
9758
9759 MachineState_T lastState;
9760 {
9761 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9762 lastState = mData->mMachineState;
9763 }
9764 NOREF(lastState);
9765
9766#ifdef VBOX_WITH_USB
9767 // release all captured USB devices, but do this before requesting the locks below
9768 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9769 {
9770 /* Console::captureUSBDevices() is called in the VM process only after
9771 * setting the machine state to Starting or Restoring.
9772 * Console::detachAllUSBDevices() will be called upon successful
9773 * termination. So, we need to release USB devices only if there was
9774 * an abnormal termination of a running VM.
9775 *
9776 * This is identical to SessionMachine::DetachAllUSBDevices except
9777 * for the aAbnormal argument. */
9778 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9779 AssertComRC(rc);
9780 NOREF(rc);
9781
9782 USBProxyService *service = mParent->host()->usbProxyService();
9783 if (service)
9784 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9785 }
9786#endif /* VBOX_WITH_USB */
9787
9788 // we need to lock this object in uninit() because the lock is shared
9789 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
9790 // and others need mParent lock, and USB needs host lock.
9791 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
9792
9793 // Trigger async cleanup tasks, avoid doing things here which are not
9794 // vital to be done immediately and maybe need more locks. This calls
9795 // Machine::unregisterMetrics().
9796 mParent->onMachineUninit(mPeer);
9797
9798 if (aReason == Uninit::Abnormal)
9799 {
9800 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
9801 Global::IsOnlineOrTransient(lastState)));
9802
9803 /* reset the state to Aborted */
9804 if (mData->mMachineState != MachineState_Aborted)
9805 setMachineState(MachineState_Aborted);
9806 }
9807
9808 // any machine settings modified?
9809 if (mData->flModifications)
9810 {
9811 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
9812 rollback(false /* aNotify */);
9813 }
9814
9815 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
9816 if (!mSnapshotData.mStateFilePath.isEmpty())
9817 {
9818 LogWarningThisFunc(("canceling failed save state request!\n"));
9819 endSavingState(FALSE /* aSuccess */);
9820 }
9821 else if (!mSnapshotData.mSnapshot.isNull())
9822 {
9823 LogWarningThisFunc(("canceling untaken snapshot!\n"));
9824
9825 /* delete all differencing hard disks created (this will also attach
9826 * their parents back by rolling back mMediaData) */
9827 rollbackMedia();
9828 /* delete the saved state file (it might have been already created) */
9829 if (mSnapshotData.mSnapshot->stateFilePath().length())
9830 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
9831
9832 mSnapshotData.mSnapshot->uninit();
9833 }
9834
9835 if (!mData->mSession.mType.isEmpty())
9836 {
9837 /* mType is not null when this machine's process has been started by
9838 * Machine::launchVMProcess(), therefore it is our child. We
9839 * need to queue the PID to reap the process (and avoid zombies on
9840 * Linux). */
9841 Assert(mData->mSession.mPid != NIL_RTPROCESS);
9842 mParent->addProcessToReap(mData->mSession.mPid);
9843 }
9844
9845 mData->mSession.mPid = NIL_RTPROCESS;
9846
9847 if (aReason == Uninit::Unexpected)
9848 {
9849 /* Uninitialization didn't come from #checkForDeath(), so tell the
9850 * client watcher thread to update the set of machines that have open
9851 * sessions. */
9852 mParent->updateClientWatcher();
9853 }
9854
9855 /* uninitialize all remote controls */
9856 if (mData->mSession.mRemoteControls.size())
9857 {
9858 LogFlowThisFunc(("Closing remote sessions (%d):\n",
9859 mData->mSession.mRemoteControls.size()));
9860
9861 Data::Session::RemoteControlList::iterator it =
9862 mData->mSession.mRemoteControls.begin();
9863 while (it != mData->mSession.mRemoteControls.end())
9864 {
9865 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
9866 HRESULT rc = (*it)->Uninitialize();
9867 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
9868 if (FAILED(rc))
9869 LogWarningThisFunc(("Forgot to close the remote session?\n"));
9870 ++it;
9871 }
9872 mData->mSession.mRemoteControls.clear();
9873 }
9874
9875 /*
9876 * An expected uninitialization can come only from #checkForDeath().
9877 * Otherwise it means that something's got really wrong (for examlple,
9878 * the Session implementation has released the VirtualBox reference
9879 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
9880 * etc). However, it's also possible, that the client releases the IPC
9881 * semaphore correctly (i.e. before it releases the VirtualBox reference),
9882 * but the VirtualBox release event comes first to the server process.
9883 * This case is practically possible, so we should not assert on an
9884 * unexpected uninit, just log a warning.
9885 */
9886
9887 if ((aReason == Uninit::Unexpected))
9888 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
9889
9890 if (aReason != Uninit::Normal)
9891 {
9892 mData->mSession.mDirectControl.setNull();
9893 }
9894 else
9895 {
9896 /* this must be null here (see #OnSessionEnd()) */
9897 Assert(mData->mSession.mDirectControl.isNull());
9898 Assert(mData->mSession.mState == SessionState_Unlocking);
9899 Assert(!mData->mSession.mProgress.isNull());
9900 }
9901 if (mData->mSession.mProgress)
9902 {
9903 if (aReason == Uninit::Normal)
9904 mData->mSession.mProgress->notifyComplete(S_OK);
9905 else
9906 mData->mSession.mProgress->notifyComplete(E_FAIL,
9907 COM_IIDOF(ISession),
9908 getComponentName(),
9909 tr("The VM session was aborted"));
9910 mData->mSession.mProgress.setNull();
9911 }
9912
9913 /* remove the association between the peer machine and this session machine */
9914 Assert( (SessionMachine*)mData->mSession.mMachine == this
9915 || aReason == Uninit::Unexpected);
9916
9917 /* reset the rest of session data */
9918 mData->mSession.mMachine.setNull();
9919 mData->mSession.mState = SessionState_Unlocked;
9920 mData->mSession.mType.setNull();
9921
9922 /* close the interprocess semaphore before leaving the exclusive lock */
9923#if defined(RT_OS_WINDOWS)
9924 if (mIPCSem)
9925 ::CloseHandle(mIPCSem);
9926 mIPCSem = NULL;
9927#elif defined(RT_OS_OS2)
9928 if (mIPCSem != NULLHANDLE)
9929 ::DosCloseMutexSem(mIPCSem);
9930 mIPCSem = NULLHANDLE;
9931#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9932 if (mIPCSem >= 0)
9933 ::semctl(mIPCSem, 0, IPC_RMID);
9934 mIPCSem = -1;
9935# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9936 mIPCKey = "0";
9937# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9938#else
9939# error "Port me!"
9940#endif
9941
9942 /* fire an event */
9943 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
9944
9945 uninitDataAndChildObjects();
9946
9947 /* free the essential data structure last */
9948 mData.free();
9949
9950#if 1 /** @todo Please review this change! (bird) */
9951 /* drop the exclusive lock before setting the below two to NULL */
9952 multilock.release();
9953#else
9954 /* leave the exclusive lock before setting the below two to NULL */
9955 multilock.leave();
9956#endif
9957
9958 unconst(mParent) = NULL;
9959 unconst(mPeer) = NULL;
9960
9961 LogFlowThisFuncLeave();
9962}
9963
9964// util::Lockable interface
9965////////////////////////////////////////////////////////////////////////////////
9966
9967/**
9968 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
9969 * with the primary Machine instance (mPeer).
9970 */
9971RWLockHandle *SessionMachine::lockHandle() const
9972{
9973 AssertReturn(mPeer != NULL, NULL);
9974 return mPeer->lockHandle();
9975}
9976
9977// IInternalMachineControl methods
9978////////////////////////////////////////////////////////////////////////////////
9979
9980/**
9981 * @note Locks this object for writing.
9982 */
9983STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
9984{
9985 AutoCaller autoCaller(this);
9986 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9987
9988 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9989
9990 mRemoveSavedState = aRemove;
9991
9992 return S_OK;
9993}
9994
9995/**
9996 * @note Locks the same as #setMachineState() does.
9997 */
9998STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
9999{
10000 return setMachineState(aMachineState);
10001}
10002
10003/**
10004 * @note Locks this object for reading.
10005 */
10006STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10007{
10008 AutoCaller autoCaller(this);
10009 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10010
10011 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10012
10013#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10014 mIPCSemName.cloneTo(aId);
10015 return S_OK;
10016#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10017# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10018 mIPCKey.cloneTo(aId);
10019# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10020 mData->m_strConfigFileFull.cloneTo(aId);
10021# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10022 return S_OK;
10023#else
10024# error "Port me!"
10025#endif
10026}
10027
10028/**
10029 * @note Locks this object for writing.
10030 */
10031STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10032{
10033 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10034 AutoCaller autoCaller(this);
10035 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10036
10037 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10038
10039 if (mData->mSession.mState != SessionState_Locked)
10040 return VBOX_E_INVALID_OBJECT_STATE;
10041
10042 if (!mData->mSession.mProgress.isNull())
10043 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10044
10045 LogFlowThisFunc(("returns S_OK.\n"));
10046 return S_OK;
10047}
10048
10049
10050/**
10051 * @note Locks this object for writing.
10052 */
10053STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10054{
10055 AutoCaller autoCaller(this);
10056 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10057
10058 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10059
10060 if (mData->mSession.mState != SessionState_Locked)
10061 return VBOX_E_INVALID_OBJECT_STATE;
10062
10063 /* Finalize the openRemoteSession progress object. */
10064 if (mData->mSession.mProgress)
10065 {
10066 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10067 mData->mSession.mProgress.setNull();
10068
10069 if (SUCCEEDED((HRESULT)iResult))
10070 {
10071#ifdef VBOX_WITH_RESOURCE_USAGE_API
10072 /* The VM has been powered up successfully, so it makes sense
10073 * now to offer the performance metrics for a running machine
10074 * object. Doing it earlier wouldn't be safe. */
10075 registerMetrics(mParent->performanceCollector(), mPeer,
10076 mData->mSession.mPid);
10077#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10078
10079 }
10080 }
10081 return S_OK;
10082}
10083
10084/**
10085 * Goes through the USB filters of the given machine to see if the given
10086 * device matches any filter or not.
10087 *
10088 * @note Locks the same as USBController::hasMatchingFilter() does.
10089 */
10090STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10091 BOOL *aMatched,
10092 ULONG *aMaskedIfs)
10093{
10094 LogFlowThisFunc(("\n"));
10095
10096 CheckComArgNotNull(aUSBDevice);
10097 CheckComArgOutPointerValid(aMatched);
10098
10099 AutoCaller autoCaller(this);
10100 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10101
10102#ifdef VBOX_WITH_USB
10103 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10104#else
10105 NOREF(aUSBDevice);
10106 NOREF(aMaskedIfs);
10107 *aMatched = FALSE;
10108#endif
10109
10110 return S_OK;
10111}
10112
10113/**
10114 * @note Locks the same as Host::captureUSBDevice() does.
10115 */
10116STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10117{
10118 LogFlowThisFunc(("\n"));
10119
10120 AutoCaller autoCaller(this);
10121 AssertComRCReturnRC(autoCaller.rc());
10122
10123#ifdef VBOX_WITH_USB
10124 /* if captureDeviceForVM() fails, it must have set extended error info */
10125 MultiResult rc = mParent->host()->checkUSBProxyService();
10126 if (FAILED(rc)) return rc;
10127
10128 USBProxyService *service = mParent->host()->usbProxyService();
10129 AssertReturn(service, E_FAIL);
10130 return service->captureDeviceForVM(this, Guid(aId));
10131#else
10132 NOREF(aId);
10133 return E_NOTIMPL;
10134#endif
10135}
10136
10137/**
10138 * @note Locks the same as Host::detachUSBDevice() does.
10139 */
10140STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10141{
10142 LogFlowThisFunc(("\n"));
10143
10144 AutoCaller autoCaller(this);
10145 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10146
10147#ifdef VBOX_WITH_USB
10148 USBProxyService *service = mParent->host()->usbProxyService();
10149 AssertReturn(service, E_FAIL);
10150 return service->detachDeviceFromVM(this, Guid(aId), !!aDone);
10151#else
10152 NOREF(aId);
10153 NOREF(aDone);
10154 return E_NOTIMPL;
10155#endif
10156}
10157
10158/**
10159 * Inserts all machine filters to the USB proxy service and then calls
10160 * Host::autoCaptureUSBDevices().
10161 *
10162 * Called by Console from the VM process upon VM startup.
10163 *
10164 * @note Locks what called methods lock.
10165 */
10166STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10167{
10168 LogFlowThisFunc(("\n"));
10169
10170 AutoCaller autoCaller(this);
10171 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10172
10173#ifdef VBOX_WITH_USB
10174 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10175 AssertComRC(rc);
10176 NOREF(rc);
10177
10178 USBProxyService *service = mParent->host()->usbProxyService();
10179 AssertReturn(service, E_FAIL);
10180 return service->autoCaptureDevicesForVM(this);
10181#else
10182 return S_OK;
10183#endif
10184}
10185
10186/**
10187 * Removes all machine filters from the USB proxy service and then calls
10188 * Host::detachAllUSBDevices().
10189 *
10190 * Called by Console from the VM process upon normal VM termination or by
10191 * SessionMachine::uninit() upon abnormal VM termination (from under the
10192 * Machine/SessionMachine lock).
10193 *
10194 * @note Locks what called methods lock.
10195 */
10196STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10197{
10198 LogFlowThisFunc(("\n"));
10199
10200 AutoCaller autoCaller(this);
10201 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10202
10203#ifdef VBOX_WITH_USB
10204 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10205 AssertComRC(rc);
10206 NOREF(rc);
10207
10208 USBProxyService *service = mParent->host()->usbProxyService();
10209 AssertReturn(service, E_FAIL);
10210 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10211#else
10212 NOREF(aDone);
10213 return S_OK;
10214#endif
10215}
10216
10217/**
10218 * @note Locks this object for writing.
10219 */
10220STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10221 IProgress **aProgress)
10222{
10223 LogFlowThisFuncEnter();
10224
10225 AssertReturn(aSession, E_INVALIDARG);
10226 AssertReturn(aProgress, E_INVALIDARG);
10227
10228 AutoCaller autoCaller(this);
10229
10230 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10231 /*
10232 * We don't assert below because it might happen that a non-direct session
10233 * informs us it is closed right after we've been uninitialized -- it's ok.
10234 */
10235 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10236
10237 /* get IInternalSessionControl interface */
10238 ComPtr<IInternalSessionControl> control(aSession);
10239
10240 ComAssertRet(!control.isNull(), E_INVALIDARG);
10241
10242 /* Creating a Progress object requires the VirtualBox lock, and
10243 * thus locking it here is required by the lock order rules. */
10244 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10245
10246 if (control == mData->mSession.mDirectControl)
10247 {
10248 ComAssertRet(aProgress, E_POINTER);
10249
10250 /* The direct session is being normally closed by the client process
10251 * ----------------------------------------------------------------- */
10252
10253 /* go to the closing state (essential for all open*Session() calls and
10254 * for #checkForDeath()) */
10255 Assert(mData->mSession.mState == SessionState_Locked);
10256 mData->mSession.mState = SessionState_Unlocking;
10257
10258 /* set direct control to NULL to release the remote instance */
10259 mData->mSession.mDirectControl.setNull();
10260 LogFlowThisFunc(("Direct control is set to NULL\n"));
10261
10262 if (mData->mSession.mProgress)
10263 {
10264 /* finalize the progress, someone might wait if a frontend
10265 * closes the session before powering on the VM. */
10266 mData->mSession.mProgress->notifyComplete(E_FAIL,
10267 COM_IIDOF(ISession),
10268 getComponentName(),
10269 tr("The VM session was closed before any attempt to power it on"));
10270 mData->mSession.mProgress.setNull();
10271 }
10272
10273 /* Create the progress object the client will use to wait until
10274 * #checkForDeath() is called to uninitialize this session object after
10275 * it releases the IPC semaphore.
10276 * Note! Because we're "reusing" mProgress here, this must be a proxy
10277 * object just like for openRemoteSession. */
10278 Assert(mData->mSession.mProgress.isNull());
10279 ComObjPtr<ProgressProxy> progress;
10280 progress.createObject();
10281 ComPtr<IUnknown> pPeer(mPeer);
10282 progress->init(mParent, pPeer,
10283 Bstr(tr("Closing session")),
10284 FALSE /* aCancelable */);
10285 progress.queryInterfaceTo(aProgress);
10286 mData->mSession.mProgress = progress;
10287 }
10288 else
10289 {
10290 /* the remote session is being normally closed */
10291 Data::Session::RemoteControlList::iterator it =
10292 mData->mSession.mRemoteControls.begin();
10293 while (it != mData->mSession.mRemoteControls.end())
10294 {
10295 if (control == *it)
10296 break;
10297 ++it;
10298 }
10299 BOOL found = it != mData->mSession.mRemoteControls.end();
10300 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10301 E_INVALIDARG);
10302 mData->mSession.mRemoteControls.remove(*it);
10303 }
10304
10305 LogFlowThisFuncLeave();
10306 return S_OK;
10307}
10308
10309/**
10310 * @note Locks this object for writing.
10311 */
10312STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10313{
10314 LogFlowThisFuncEnter();
10315
10316 AssertReturn(aProgress, E_INVALIDARG);
10317 AssertReturn(aStateFilePath, E_POINTER);
10318
10319 AutoCaller autoCaller(this);
10320 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10321
10322 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10323
10324 AssertReturn( mData->mMachineState == MachineState_Paused
10325 && mSnapshotData.mLastState == MachineState_Null
10326 && mSnapshotData.mProgressId.isEmpty()
10327 && mSnapshotData.mStateFilePath.isEmpty(),
10328 E_FAIL);
10329
10330 /* memorize the progress ID and add it to the global collection */
10331 Bstr progressId;
10332 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10333 AssertComRCReturn(rc, rc);
10334 rc = mParent->addProgress(aProgress);
10335 AssertComRCReturn(rc, rc);
10336
10337 Bstr stateFilePath;
10338 /* stateFilePath is null when the machine is not running */
10339 if (mData->mMachineState == MachineState_Paused)
10340 {
10341 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10342 mUserData->m_strSnapshotFolderFull.c_str(),
10343 RTPATH_DELIMITER, mData->mUuid.raw());
10344 }
10345
10346 /* fill in the snapshot data */
10347 mSnapshotData.mLastState = mData->mMachineState;
10348 mSnapshotData.mProgressId = Guid(progressId);
10349 mSnapshotData.mStateFilePath = stateFilePath;
10350
10351 /* set the state to Saving (this is expected by Console::SaveState()) */
10352 setMachineState(MachineState_Saving);
10353
10354 stateFilePath.cloneTo(aStateFilePath);
10355
10356 return S_OK;
10357}
10358
10359/**
10360 * @note Locks mParent + this object for writing.
10361 */
10362STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10363{
10364 LogFlowThisFunc(("\n"));
10365
10366 AutoCaller autoCaller(this);
10367 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10368
10369 /* endSavingState() need mParent lock */
10370 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10371
10372 AssertReturn( mData->mMachineState == MachineState_Saving
10373 && mSnapshotData.mLastState != MachineState_Null
10374 && !mSnapshotData.mProgressId.isEmpty()
10375 && !mSnapshotData.mStateFilePath.isEmpty(),
10376 E_FAIL);
10377
10378 /*
10379 * on success, set the state to Saved;
10380 * on failure, set the state to the state we had when BeginSavingState() was
10381 * called (this is expected by Console::SaveState() and
10382 * Console::saveStateThread())
10383 */
10384 if (aSuccess)
10385 setMachineState(MachineState_Saved);
10386 else
10387 setMachineState(mSnapshotData.mLastState);
10388
10389 return endSavingState(aSuccess);
10390}
10391
10392/**
10393 * @note Locks this object for writing.
10394 */
10395STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10396{
10397 LogFlowThisFunc(("\n"));
10398
10399 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10400
10401 AutoCaller autoCaller(this);
10402 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10403
10404 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10405
10406 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10407 || mData->mMachineState == MachineState_Teleported
10408 || mData->mMachineState == MachineState_Aborted
10409 , E_FAIL); /** @todo setError. */
10410
10411 Utf8Str stateFilePathFull = aSavedStateFile;
10412 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10413 if (RT_FAILURE(vrc))
10414 return setError(VBOX_E_FILE_ERROR,
10415 tr("Invalid saved state file path '%ls' (%Rrc)"),
10416 aSavedStateFile,
10417 vrc);
10418
10419 mSSData->mStateFilePath = stateFilePathFull;
10420
10421 /* The below setMachineState() will detect the state transition and will
10422 * update the settings file */
10423
10424 return setMachineState(MachineState_Saved);
10425}
10426
10427STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10428 ComSafeArrayOut(BSTR, aValues),
10429 ComSafeArrayOut(ULONG64, aTimestamps),
10430 ComSafeArrayOut(BSTR, aFlags))
10431{
10432 LogFlowThisFunc(("\n"));
10433
10434#ifdef VBOX_WITH_GUEST_PROPS
10435 using namespace guestProp;
10436
10437 AutoCaller autoCaller(this);
10438 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10439
10440 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10441
10442 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10443 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10444 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10445 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10446
10447 size_t cEntries = mHWData->mGuestProperties.size();
10448 com::SafeArray<BSTR> names(cEntries);
10449 com::SafeArray<BSTR> values(cEntries);
10450 com::SafeArray<ULONG64> timestamps(cEntries);
10451 com::SafeArray<BSTR> flags(cEntries);
10452 unsigned i = 0;
10453 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10454 it != mHWData->mGuestProperties.end();
10455 ++it)
10456 {
10457 char szFlags[MAX_FLAGS_LEN + 1];
10458 it->strName.cloneTo(&names[i]);
10459 it->strValue.cloneTo(&values[i]);
10460 timestamps[i] = it->mTimestamp;
10461 /* If it is NULL, keep it NULL. */
10462 if (it->mFlags)
10463 {
10464 writeFlags(it->mFlags, szFlags);
10465 Bstr(szFlags).cloneTo(&flags[i]);
10466 }
10467 else
10468 flags[i] = NULL;
10469 ++i;
10470 }
10471 names.detachTo(ComSafeArrayOutArg(aNames));
10472 values.detachTo(ComSafeArrayOutArg(aValues));
10473 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10474 flags.detachTo(ComSafeArrayOutArg(aFlags));
10475 return S_OK;
10476#else
10477 ReturnComNotImplemented();
10478#endif
10479}
10480
10481STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10482 IN_BSTR aValue,
10483 ULONG64 aTimestamp,
10484 IN_BSTR aFlags)
10485{
10486 LogFlowThisFunc(("\n"));
10487
10488#ifdef VBOX_WITH_GUEST_PROPS
10489 using namespace guestProp;
10490
10491 CheckComArgStrNotEmptyOrNull(aName);
10492 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10493 return E_POINTER; /* aValue can be NULL to indicate deletion */
10494
10495 try
10496 {
10497 /*
10498 * Convert input up front.
10499 */
10500 Utf8Str utf8Name(aName);
10501 uint32_t fFlags = NILFLAG;
10502 if (aFlags)
10503 {
10504 Utf8Str utf8Flags(aFlags);
10505 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
10506 AssertRCReturn(vrc, E_INVALIDARG);
10507 }
10508
10509 /*
10510 * Now grab the object lock, validate the state and do the update.
10511 */
10512 AutoCaller autoCaller(this);
10513 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10514
10515 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10516
10517 switch (mData->mMachineState)
10518 {
10519 case MachineState_Paused:
10520 case MachineState_Running:
10521 case MachineState_Teleporting:
10522 case MachineState_TeleportingPausedVM:
10523 case MachineState_LiveSnapshotting:
10524 case MachineState_DeletingSnapshotOnline:
10525 case MachineState_DeletingSnapshotPaused:
10526 case MachineState_Saving:
10527 break;
10528
10529 default:
10530 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10531 VBOX_E_INVALID_VM_STATE);
10532 }
10533
10534 setModified(IsModified_MachineData);
10535 mHWData.backup();
10536
10537 /** @todo r=bird: The careful memory handling doesn't work out here because
10538 * the catch block won't undo any damange we've done. So, if push_back throws
10539 * bad_alloc then you've lost the value.
10540 *
10541 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10542 * since values that changes actually bubbles to the end of the list. Using
10543 * something that has an efficient lookup and can tollerate a bit of updates
10544 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10545 * combination of RTStrCache (for sharing names and getting uniqueness into
10546 * the bargain) and hash/tree is another. */
10547 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10548 iter != mHWData->mGuestProperties.end();
10549 ++iter)
10550 if (utf8Name == iter->strName)
10551 {
10552 mHWData->mGuestProperties.erase(iter);
10553 mData->mGuestPropertiesModified = TRUE;
10554 break;
10555 }
10556 if (aValue != NULL)
10557 {
10558 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10559 mHWData->mGuestProperties.push_back(property);
10560 mData->mGuestPropertiesModified = TRUE;
10561 }
10562
10563 /*
10564 * Send a callback notification if appropriate
10565 */
10566 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10567 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
10568 RTSTR_MAX,
10569 utf8Name.c_str(),
10570 RTSTR_MAX, NULL)
10571 )
10572 {
10573 alock.leave();
10574
10575 mParent->onGuestPropertyChange(mData->mUuid,
10576 aName,
10577 aValue,
10578 aFlags);
10579 }
10580 }
10581 catch (...)
10582 {
10583 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10584 }
10585 return S_OK;
10586#else
10587 ReturnComNotImplemented();
10588#endif
10589}
10590
10591// public methods only for internal purposes
10592/////////////////////////////////////////////////////////////////////////////
10593
10594/**
10595 * Called from the client watcher thread to check for expected or unexpected
10596 * death of the client process that has a direct session to this machine.
10597 *
10598 * On Win32 and on OS/2, this method is called only when we've got the
10599 * mutex (i.e. the client has either died or terminated normally) so it always
10600 * returns @c true (the client is terminated, the session machine is
10601 * uninitialized).
10602 *
10603 * On other platforms, the method returns @c true if the client process has
10604 * terminated normally or abnormally and the session machine was uninitialized,
10605 * and @c false if the client process is still alive.
10606 *
10607 * @note Locks this object for writing.
10608 */
10609bool SessionMachine::checkForDeath()
10610{
10611 Uninit::Reason reason;
10612 bool terminated = false;
10613
10614 /* Enclose autoCaller with a block because calling uninit() from under it
10615 * will deadlock. */
10616 {
10617 AutoCaller autoCaller(this);
10618 if (!autoCaller.isOk())
10619 {
10620 /* return true if not ready, to cause the client watcher to exclude
10621 * the corresponding session from watching */
10622 LogFlowThisFunc(("Already uninitialized!\n"));
10623 return true;
10624 }
10625
10626 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10627
10628 /* Determine the reason of death: if the session state is Closing here,
10629 * everything is fine. Otherwise it means that the client did not call
10630 * OnSessionEnd() before it released the IPC semaphore. This may happen
10631 * either because the client process has abnormally terminated, or
10632 * because it simply forgot to call ISession::Close() before exiting. We
10633 * threat the latter also as an abnormal termination (see
10634 * Session::uninit() for details). */
10635 reason = mData->mSession.mState == SessionState_Unlocking ?
10636 Uninit::Normal :
10637 Uninit::Abnormal;
10638
10639#if defined(RT_OS_WINDOWS)
10640
10641 AssertMsg(mIPCSem, ("semaphore must be created"));
10642
10643 /* release the IPC mutex */
10644 ::ReleaseMutex(mIPCSem);
10645
10646 terminated = true;
10647
10648#elif defined(RT_OS_OS2)
10649
10650 AssertMsg(mIPCSem, ("semaphore must be created"));
10651
10652 /* release the IPC mutex */
10653 ::DosReleaseMutexSem(mIPCSem);
10654
10655 terminated = true;
10656
10657#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10658
10659 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10660
10661 int val = ::semctl(mIPCSem, 0, GETVAL);
10662 if (val > 0)
10663 {
10664 /* the semaphore is signaled, meaning the session is terminated */
10665 terminated = true;
10666 }
10667
10668#else
10669# error "Port me!"
10670#endif
10671
10672 } /* AutoCaller block */
10673
10674 if (terminated)
10675 uninit(reason);
10676
10677 return terminated;
10678}
10679
10680/**
10681 * @note Locks this object for reading.
10682 */
10683HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10684{
10685 LogFlowThisFunc(("\n"));
10686
10687 AutoCaller autoCaller(this);
10688 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10689
10690 ComPtr<IInternalSessionControl> directControl;
10691 {
10692 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10693 directControl = mData->mSession.mDirectControl;
10694 }
10695
10696 /* ignore notifications sent after #OnSessionEnd() is called */
10697 if (!directControl)
10698 return S_OK;
10699
10700 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10701}
10702
10703/**
10704 * @note Locks this object for reading.
10705 */
10706HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10707{
10708 LogFlowThisFunc(("\n"));
10709
10710 AutoCaller autoCaller(this);
10711 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10712
10713 ComPtr<IInternalSessionControl> directControl;
10714 {
10715 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10716 directControl = mData->mSession.mDirectControl;
10717 }
10718
10719 /* ignore notifications sent after #OnSessionEnd() is called */
10720 if (!directControl)
10721 return S_OK;
10722
10723 return directControl->OnSerialPortChange(serialPort);
10724}
10725
10726/**
10727 * @note Locks this object for reading.
10728 */
10729HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10730{
10731 LogFlowThisFunc(("\n"));
10732
10733 AutoCaller autoCaller(this);
10734 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10735
10736 ComPtr<IInternalSessionControl> directControl;
10737 {
10738 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10739 directControl = mData->mSession.mDirectControl;
10740 }
10741
10742 /* ignore notifications sent after #OnSessionEnd() is called */
10743 if (!directControl)
10744 return S_OK;
10745
10746 return directControl->OnParallelPortChange(parallelPort);
10747}
10748
10749/**
10750 * @note Locks this object for reading.
10751 */
10752HRESULT SessionMachine::onStorageControllerChange()
10753{
10754 LogFlowThisFunc(("\n"));
10755
10756 AutoCaller autoCaller(this);
10757 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10758
10759 ComPtr<IInternalSessionControl> directControl;
10760 {
10761 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10762 directControl = mData->mSession.mDirectControl;
10763 }
10764
10765 /* ignore notifications sent after #OnSessionEnd() is called */
10766 if (!directControl)
10767 return S_OK;
10768
10769 return directControl->OnStorageControllerChange();
10770}
10771
10772/**
10773 * @note Locks this object for reading.
10774 */
10775HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10776{
10777 LogFlowThisFunc(("\n"));
10778
10779 AutoCaller autoCaller(this);
10780 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10781
10782 ComPtr<IInternalSessionControl> directControl;
10783 {
10784 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10785 directControl = mData->mSession.mDirectControl;
10786 }
10787
10788 /* ignore notifications sent after #OnSessionEnd() is called */
10789 if (!directControl)
10790 return S_OK;
10791
10792 return directControl->OnMediumChange(aAttachment, aForce);
10793}
10794
10795/**
10796 * @note Locks this object for reading.
10797 */
10798HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
10799{
10800 LogFlowThisFunc(("\n"));
10801
10802 AutoCaller autoCaller(this);
10803 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10804
10805 ComPtr<IInternalSessionControl> directControl;
10806 {
10807 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10808 directControl = mData->mSession.mDirectControl;
10809 }
10810
10811 /* ignore notifications sent after #OnSessionEnd() is called */
10812 if (!directControl)
10813 return S_OK;
10814
10815 return directControl->OnCPUChange(aCPU, aRemove);
10816}
10817
10818HRESULT SessionMachine::onCPUPriorityChange(ULONG aCpuPriority)
10819{
10820 LogFlowThisFunc(("\n"));
10821
10822 AutoCaller autoCaller(this);
10823 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10824
10825 ComPtr<IInternalSessionControl> directControl;
10826 {
10827 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10828 directControl = mData->mSession.mDirectControl;
10829 }
10830
10831 /* ignore notifications sent after #OnSessionEnd() is called */
10832 if (!directControl)
10833 return S_OK;
10834
10835 return directControl->OnCPUPriorityChange(aCpuPriority);
10836}
10837
10838/**
10839 * @note Locks this object for reading.
10840 */
10841HRESULT SessionMachine::onVRDPServerChange(BOOL aRestart)
10842{
10843 LogFlowThisFunc(("\n"));
10844
10845 AutoCaller autoCaller(this);
10846 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10847
10848 ComPtr<IInternalSessionControl> directControl;
10849 {
10850 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10851 directControl = mData->mSession.mDirectControl;
10852 }
10853
10854 /* ignore notifications sent after #OnSessionEnd() is called */
10855 if (!directControl)
10856 return S_OK;
10857
10858 return directControl->OnVRDPServerChange(aRestart);
10859}
10860
10861/**
10862 * @note Locks this object for reading.
10863 */
10864HRESULT SessionMachine::onUSBControllerChange()
10865{
10866 LogFlowThisFunc(("\n"));
10867
10868 AutoCaller autoCaller(this);
10869 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10870
10871 ComPtr<IInternalSessionControl> directControl;
10872 {
10873 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10874 directControl = mData->mSession.mDirectControl;
10875 }
10876
10877 /* ignore notifications sent after #OnSessionEnd() is called */
10878 if (!directControl)
10879 return S_OK;
10880
10881 return directControl->OnUSBControllerChange();
10882}
10883
10884/**
10885 * @note Locks this object for reading.
10886 */
10887HRESULT SessionMachine::onSharedFolderChange()
10888{
10889 LogFlowThisFunc(("\n"));
10890
10891 AutoCaller autoCaller(this);
10892 AssertComRCReturnRC(autoCaller.rc());
10893
10894 ComPtr<IInternalSessionControl> directControl;
10895 {
10896 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10897 directControl = mData->mSession.mDirectControl;
10898 }
10899
10900 /* ignore notifications sent after #OnSessionEnd() is called */
10901 if (!directControl)
10902 return S_OK;
10903
10904 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
10905}
10906
10907/**
10908 * Returns @c true if this machine's USB controller reports it has a matching
10909 * filter for the given USB device and @c false otherwise.
10910 *
10911 * @note Caller must have requested machine read lock.
10912 */
10913bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
10914{
10915 AutoCaller autoCaller(this);
10916 /* silently return if not ready -- this method may be called after the
10917 * direct machine session has been called */
10918 if (!autoCaller.isOk())
10919 return false;
10920
10921
10922#ifdef VBOX_WITH_USB
10923 switch (mData->mMachineState)
10924 {
10925 case MachineState_Starting:
10926 case MachineState_Restoring:
10927 case MachineState_TeleportingIn:
10928 case MachineState_Paused:
10929 case MachineState_Running:
10930 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
10931 * elsewhere... */
10932 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
10933 default: break;
10934 }
10935#else
10936 NOREF(aDevice);
10937 NOREF(aMaskedIfs);
10938#endif
10939 return false;
10940}
10941
10942/**
10943 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10944 */
10945HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
10946 IVirtualBoxErrorInfo *aError,
10947 ULONG aMaskedIfs)
10948{
10949 LogFlowThisFunc(("\n"));
10950
10951 AutoCaller autoCaller(this);
10952
10953 /* This notification may happen after the machine object has been
10954 * uninitialized (the session was closed), so don't assert. */
10955 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10956
10957 ComPtr<IInternalSessionControl> directControl;
10958 {
10959 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10960 directControl = mData->mSession.mDirectControl;
10961 }
10962
10963 /* fail on notifications sent after #OnSessionEnd() is called, it is
10964 * expected by the caller */
10965 if (!directControl)
10966 return E_FAIL;
10967
10968 /* No locks should be held at this point. */
10969 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10970 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10971
10972 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
10973}
10974
10975/**
10976 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10977 */
10978HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
10979 IVirtualBoxErrorInfo *aError)
10980{
10981 LogFlowThisFunc(("\n"));
10982
10983 AutoCaller autoCaller(this);
10984
10985 /* This notification may happen after the machine object has been
10986 * uninitialized (the session was closed), so don't assert. */
10987 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10988
10989 ComPtr<IInternalSessionControl> directControl;
10990 {
10991 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10992 directControl = mData->mSession.mDirectControl;
10993 }
10994
10995 /* fail on notifications sent after #OnSessionEnd() is called, it is
10996 * expected by the caller */
10997 if (!directControl)
10998 return E_FAIL;
10999
11000 /* No locks should be held at this point. */
11001 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11002 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11003
11004 return directControl->OnUSBDeviceDetach(aId, aError);
11005}
11006
11007// protected methods
11008/////////////////////////////////////////////////////////////////////////////
11009
11010/**
11011 * Helper method to finalize saving the state.
11012 *
11013 * @note Must be called from under this object's lock.
11014 *
11015 * @param aSuccess TRUE if the snapshot has been taken successfully
11016 *
11017 * @note Locks mParent + this objects for writing.
11018 */
11019HRESULT SessionMachine::endSavingState(BOOL aSuccess)
11020{
11021 LogFlowThisFuncEnter();
11022
11023 AutoCaller autoCaller(this);
11024 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11025
11026 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11027
11028 HRESULT rc = S_OK;
11029
11030 if (aSuccess)
11031 {
11032 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11033
11034 /* save all VM settings */
11035 rc = saveSettings(NULL);
11036 // no need to check whether VirtualBox.xml needs saving also since
11037 // we can't have a name change pending at this point
11038 }
11039 else
11040 {
11041 /* delete the saved state file (it might have been already created) */
11042 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11043 }
11044
11045 /* remove the completed progress object */
11046 mParent->removeProgress(mSnapshotData.mProgressId);
11047
11048 /* clear out the temporary saved state data */
11049 mSnapshotData.mLastState = MachineState_Null;
11050 mSnapshotData.mProgressId.clear();
11051 mSnapshotData.mStateFilePath.setNull();
11052
11053 LogFlowThisFuncLeave();
11054 return rc;
11055}
11056
11057/**
11058 * Locks the attached media.
11059 *
11060 * All attached hard disks are locked for writing and DVD/floppy are locked for
11061 * reading. Parents of attached hard disks (if any) are locked for reading.
11062 *
11063 * This method also performs accessibility check of all media it locks: if some
11064 * media is inaccessible, the method will return a failure and a bunch of
11065 * extended error info objects per each inaccessible medium.
11066 *
11067 * Note that this method is atomic: if it returns a success, all media are
11068 * locked as described above; on failure no media is locked at all (all
11069 * succeeded individual locks will be undone).
11070 *
11071 * This method is intended to be called when the machine is in Starting or
11072 * Restoring state and asserts otherwise.
11073 *
11074 * The locks made by this method must be undone by calling #unlockMedia() when
11075 * no more needed.
11076 */
11077HRESULT SessionMachine::lockMedia()
11078{
11079 AutoCaller autoCaller(this);
11080 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11081
11082 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11083
11084 AssertReturn( mData->mMachineState == MachineState_Starting
11085 || mData->mMachineState == MachineState_Restoring
11086 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11087 /* bail out if trying to lock things with already set up locking */
11088 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11089
11090 MultiResult mrc(S_OK);
11091
11092 /* Collect locking information for all medium objects attached to the VM. */
11093 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11094 it != mMediaData->mAttachments.end();
11095 ++it)
11096 {
11097 MediumAttachment* pAtt = *it;
11098 DeviceType_T devType = pAtt->getType();
11099 Medium *pMedium = pAtt->getMedium();
11100
11101 MediumLockList *pMediumLockList(new MediumLockList());
11102 // There can be attachments without a medium (floppy/dvd), and thus
11103 // it's impossible to create a medium lock list. It still makes sense
11104 // to have the empty medium lock list in the map in case a medium is
11105 // attached later.
11106 if (pMedium != NULL)
11107 {
11108 MediumType_T mediumType = pMedium->getType();
11109 bool fIsReadOnlyImage = devType == DeviceType_DVD
11110 || mediumType == MediumType_Shareable;
11111 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11112
11113 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11114 !fIsReadOnlyImage /* fMediumLockWrite */,
11115 NULL,
11116 *pMediumLockList);
11117 if (FAILED(mrc))
11118 {
11119 delete pMediumLockList;
11120 mData->mSession.mLockedMedia.Clear();
11121 break;
11122 }
11123 }
11124
11125 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11126 if (FAILED(rc))
11127 {
11128 mData->mSession.mLockedMedia.Clear();
11129 mrc = setError(rc,
11130 tr("Collecting locking information for all attached media failed"));
11131 break;
11132 }
11133 }
11134
11135 if (SUCCEEDED(mrc))
11136 {
11137 /* Now lock all media. If this fails, nothing is locked. */
11138 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11139 if (FAILED(rc))
11140 {
11141 mrc = setError(rc,
11142 tr("Locking of attached media failed"));
11143 }
11144 }
11145
11146 return mrc;
11147}
11148
11149/**
11150 * Undoes the locks made by by #lockMedia().
11151 */
11152void SessionMachine::unlockMedia()
11153{
11154 AutoCaller autoCaller(this);
11155 AssertComRCReturnVoid(autoCaller.rc());
11156
11157 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11158
11159 /* we may be holding important error info on the current thread;
11160 * preserve it */
11161 ErrorInfoKeeper eik;
11162
11163 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11164 AssertComRC(rc);
11165}
11166
11167/**
11168 * Helper to change the machine state (reimplementation).
11169 *
11170 * @note Locks this object for writing.
11171 */
11172HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11173{
11174 LogFlowThisFuncEnter();
11175 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11176
11177 AutoCaller autoCaller(this);
11178 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11179
11180 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11181
11182 MachineState_T oldMachineState = mData->mMachineState;
11183
11184 AssertMsgReturn(oldMachineState != aMachineState,
11185 ("oldMachineState=%s, aMachineState=%s\n",
11186 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11187 E_FAIL);
11188
11189 HRESULT rc = S_OK;
11190
11191 int stsFlags = 0;
11192 bool deleteSavedState = false;
11193
11194 /* detect some state transitions */
11195
11196 if ( ( oldMachineState == MachineState_Saved
11197 && aMachineState == MachineState_Restoring)
11198 || ( ( oldMachineState == MachineState_PoweredOff
11199 || oldMachineState == MachineState_Teleported
11200 || oldMachineState == MachineState_Aborted
11201 )
11202 && ( aMachineState == MachineState_TeleportingIn
11203 || aMachineState == MachineState_Starting
11204 )
11205 )
11206 )
11207 {
11208 /* The EMT thread is about to start */
11209
11210 /* Nothing to do here for now... */
11211
11212 /// @todo NEWMEDIA don't let mDVDDrive and other children
11213 /// change anything when in the Starting/Restoring state
11214 }
11215 else if ( ( oldMachineState == MachineState_Running
11216 || oldMachineState == MachineState_Paused
11217 || oldMachineState == MachineState_Teleporting
11218 || oldMachineState == MachineState_LiveSnapshotting
11219 || oldMachineState == MachineState_Stuck
11220 || oldMachineState == MachineState_Starting
11221 || oldMachineState == MachineState_Stopping
11222 || oldMachineState == MachineState_Saving
11223 || oldMachineState == MachineState_Restoring
11224 || oldMachineState == MachineState_TeleportingPausedVM
11225 || oldMachineState == MachineState_TeleportingIn
11226 )
11227 && ( aMachineState == MachineState_PoweredOff
11228 || aMachineState == MachineState_Saved
11229 || aMachineState == MachineState_Teleported
11230 || aMachineState == MachineState_Aborted
11231 )
11232 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11233 * snapshot */
11234 && ( mSnapshotData.mSnapshot.isNull()
11235 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11236 )
11237 )
11238 {
11239 /* The EMT thread has just stopped, unlock attached media. Note that as
11240 * opposed to locking that is done from Console, we do unlocking here
11241 * because the VM process may have aborted before having a chance to
11242 * properly unlock all media it locked. */
11243
11244 unlockMedia();
11245 }
11246
11247 if (oldMachineState == MachineState_Restoring)
11248 {
11249 if (aMachineState != MachineState_Saved)
11250 {
11251 /*
11252 * delete the saved state file once the machine has finished
11253 * restoring from it (note that Console sets the state from
11254 * Restoring to Saved if the VM couldn't restore successfully,
11255 * to give the user an ability to fix an error and retry --
11256 * we keep the saved state file in this case)
11257 */
11258 deleteSavedState = true;
11259 }
11260 }
11261 else if ( oldMachineState == MachineState_Saved
11262 && ( aMachineState == MachineState_PoweredOff
11263 || aMachineState == MachineState_Aborted
11264 || aMachineState == MachineState_Teleported
11265 )
11266 )
11267 {
11268 /*
11269 * delete the saved state after Console::ForgetSavedState() is called
11270 * or if the VM process (owning a direct VM session) crashed while the
11271 * VM was Saved
11272 */
11273
11274 /// @todo (dmik)
11275 // Not sure that deleting the saved state file just because of the
11276 // client death before it attempted to restore the VM is a good
11277 // thing. But when it crashes we need to go to the Aborted state
11278 // which cannot have the saved state file associated... The only
11279 // way to fix this is to make the Aborted condition not a VM state
11280 // but a bool flag: i.e., when a crash occurs, set it to true and
11281 // change the state to PoweredOff or Saved depending on the
11282 // saved state presence.
11283
11284 deleteSavedState = true;
11285 mData->mCurrentStateModified = TRUE;
11286 stsFlags |= SaveSTS_CurStateModified;
11287 }
11288
11289 if ( aMachineState == MachineState_Starting
11290 || aMachineState == MachineState_Restoring
11291 || aMachineState == MachineState_TeleportingIn
11292 )
11293 {
11294 /* set the current state modified flag to indicate that the current
11295 * state is no more identical to the state in the
11296 * current snapshot */
11297 if (!mData->mCurrentSnapshot.isNull())
11298 {
11299 mData->mCurrentStateModified = TRUE;
11300 stsFlags |= SaveSTS_CurStateModified;
11301 }
11302 }
11303
11304 if (deleteSavedState)
11305 {
11306 if (mRemoveSavedState)
11307 {
11308 Assert(!mSSData->mStateFilePath.isEmpty());
11309 RTFileDelete(mSSData->mStateFilePath.c_str());
11310 }
11311 mSSData->mStateFilePath.setNull();
11312 stsFlags |= SaveSTS_StateFilePath;
11313 }
11314
11315 /* redirect to the underlying peer machine */
11316 mPeer->setMachineState(aMachineState);
11317
11318 if ( aMachineState == MachineState_PoweredOff
11319 || aMachineState == MachineState_Teleported
11320 || aMachineState == MachineState_Aborted
11321 || aMachineState == MachineState_Saved)
11322 {
11323 /* the machine has stopped execution
11324 * (or the saved state file was adopted) */
11325 stsFlags |= SaveSTS_StateTimeStamp;
11326 }
11327
11328 if ( ( oldMachineState == MachineState_PoweredOff
11329 || oldMachineState == MachineState_Aborted
11330 || oldMachineState == MachineState_Teleported
11331 )
11332 && aMachineState == MachineState_Saved)
11333 {
11334 /* the saved state file was adopted */
11335 Assert(!mSSData->mStateFilePath.isEmpty());
11336 stsFlags |= SaveSTS_StateFilePath;
11337 }
11338
11339 if ( aMachineState == MachineState_PoweredOff
11340 || aMachineState == MachineState_Aborted
11341 || aMachineState == MachineState_Teleported)
11342 {
11343 /* Make sure any transient guest properties get removed from the
11344 * property store on shutdown. */
11345
11346 HWData::GuestPropertyList::iterator it;
11347 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11348 if (!fNeedsSaving)
11349 for (it = mHWData->mGuestProperties.begin();
11350 it != mHWData->mGuestProperties.end(); ++it)
11351 if (it->mFlags & guestProp::TRANSIENT)
11352 {
11353 fNeedsSaving = true;
11354 break;
11355 }
11356 if (fNeedsSaving)
11357 {
11358 mData->mCurrentStateModified = TRUE;
11359 stsFlags |= SaveSTS_CurStateModified;
11360 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11361 }
11362 }
11363
11364 rc = saveStateSettings(stsFlags);
11365
11366 if ( ( oldMachineState != MachineState_PoweredOff
11367 && oldMachineState != MachineState_Aborted
11368 && oldMachineState != MachineState_Teleported
11369 )
11370 && ( aMachineState == MachineState_PoweredOff
11371 || aMachineState == MachineState_Aborted
11372 || aMachineState == MachineState_Teleported
11373 )
11374 )
11375 {
11376 /* we've been shut down for any reason */
11377 /* no special action so far */
11378 }
11379
11380 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11381 LogFlowThisFuncLeave();
11382 return rc;
11383}
11384
11385/**
11386 * Sends the current machine state value to the VM process.
11387 *
11388 * @note Locks this object for reading, then calls a client process.
11389 */
11390HRESULT SessionMachine::updateMachineStateOnClient()
11391{
11392 AutoCaller autoCaller(this);
11393 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11394
11395 ComPtr<IInternalSessionControl> directControl;
11396 {
11397 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11398 AssertReturn(!!mData, E_FAIL);
11399 directControl = mData->mSession.mDirectControl;
11400
11401 /* directControl may be already set to NULL here in #OnSessionEnd()
11402 * called too early by the direct session process while there is still
11403 * some operation (like deleting the snapshot) in progress. The client
11404 * process in this case is waiting inside Session::close() for the
11405 * "end session" process object to complete, while #uninit() called by
11406 * #checkForDeath() on the Watcher thread is waiting for the pending
11407 * operation to complete. For now, we accept this inconsitent behavior
11408 * and simply do nothing here. */
11409
11410 if (mData->mSession.mState == SessionState_Unlocking)
11411 return S_OK;
11412
11413 AssertReturn(!directControl.isNull(), E_FAIL);
11414 }
11415
11416 return directControl->UpdateMachineState(mData->mMachineState);
11417}
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