VirtualBox

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

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

Main: Implemenation of per-machine media registries; VirtualBox::openMedium() no longer adds media to the global registry, instead a media are stored in a machine XML registry after Machine::AttachDevice() has been called; Machine::AttachDevice() now takes an IMedium object instead of a UUID; also make Machine::Unregister() work again for inaccessible machines

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 374.7 KB
Line 
1/* $Id: MachineImpl.cpp 31615 2010-08-12 18:12:39Z 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 ComObjPtr<Medium> pBase = pMedium->getBase();
8348
8349 if ( devType != DeviceType_HardDisk
8350 || pMedium == NULL
8351 || pMedium->getType() != MediumType_Normal)
8352 {
8353 /* copy the attachment as is */
8354
8355 /** @todo the progress object created in Console::TakeSnaphot
8356 * only expects operations for hard disks. Later other
8357 * device types need to show up in the progress as well. */
8358 if (devType == DeviceType_HardDisk)
8359 {
8360 if (pMedium == NULL)
8361 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
8362 aWeight); // weight
8363 else
8364 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8365 pBase->getName().c_str()),
8366 aWeight); // weight
8367 }
8368
8369 mMediaData->mAttachments.push_back(pAtt);
8370 continue;
8371 }
8372
8373 /* need a diff */
8374 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8375 pBase->getName().c_str()),
8376 aWeight); // weight
8377
8378 ComObjPtr<Medium> diff;
8379 diff.createObject();
8380 rc = diff->init(mParent,
8381 pMedium->getPreferredDiffFormat(),
8382 Utf8Str(mUserData->m_strSnapshotFolderFull).append(RTPATH_SLASH_STR),
8383 pMedium->getRegistryMachineId(), // store the diff in the same registry as the parent
8384 pfNeedsSaveSettings);
8385 if (FAILED(rc)) throw rc;
8386
8387 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8388 * the push_back? Looks like we're going to leave medium with the
8389 * wrong kind of lock (general issue with if we fail anywhere at all)
8390 * and an orphaned VDI in the snapshots folder. */
8391
8392 /* update the appropriate lock list */
8393 MediumLockList *pMediumLockList;
8394 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8395 AssertComRCThrowRC(rc);
8396 if (aOnline)
8397 {
8398 rc = pMediumLockList->Update(pMedium, false);
8399 AssertComRCThrowRC(rc);
8400 }
8401
8402 /* leave the lock before the potentially lengthy operation */
8403 alock.leave();
8404 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8405 pMediumLockList,
8406 NULL /* aProgress */,
8407 true /* aWait */,
8408 pfNeedsSaveSettings);
8409 alock.enter();
8410 if (FAILED(rc)) throw rc;
8411
8412 rc = lockedMediaMap->Unlock();
8413 AssertComRCThrowRC(rc);
8414 rc = pMediumLockList->Append(diff, true);
8415 AssertComRCThrowRC(rc);
8416 rc = lockedMediaMap->Lock();
8417 AssertComRCThrowRC(rc);
8418
8419 rc = diff->addBackReference(mData->mUuid);
8420 AssertComRCThrowRC(rc);
8421
8422 /* add a new attachment */
8423 ComObjPtr<MediumAttachment> attachment;
8424 attachment.createObject();
8425 rc = attachment->init(this,
8426 diff,
8427 pAtt->getControllerName(),
8428 pAtt->getPort(),
8429 pAtt->getDevice(),
8430 DeviceType_HardDisk,
8431 true /* aImplicit */,
8432 0 /* No bandwidth limit */);
8433 if (FAILED(rc)) throw rc;
8434
8435 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8436 AssertComRCThrowRC(rc);
8437 mMediaData->mAttachments.push_back(attachment);
8438 }
8439 }
8440 catch (HRESULT aRC) { rc = aRC; }
8441
8442 /* unlock all hard disks we locked */
8443 if (!aOnline)
8444 {
8445 ErrorInfoKeeper eik;
8446
8447 rc = lockedMediaMap->Clear();
8448 AssertComRC(rc);
8449 }
8450
8451 if (FAILED(rc))
8452 {
8453 MultiResult mrc = rc;
8454
8455 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8456 }
8457
8458 return rc;
8459}
8460
8461/**
8462 * Deletes implicit differencing hard disks created either by
8463 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8464 *
8465 * Note that to delete hard disks created by #AttachMedium() this method is
8466 * called from #fixupMedia() when the changes are rolled back.
8467 *
8468 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8469 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8470 *
8471 * @note Locks this object for writing.
8472 */
8473HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8474{
8475 AutoCaller autoCaller(this);
8476 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8477
8478 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8479 LogFlowThisFuncEnter();
8480
8481 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8482
8483 HRESULT rc = S_OK;
8484
8485 MediaData::AttachmentList implicitAtts;
8486
8487 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8488
8489 /* enumerate new attachments */
8490 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8491 it != mMediaData->mAttachments.end();
8492 ++it)
8493 {
8494 ComObjPtr<Medium> hd = (*it)->getMedium();
8495 if (hd.isNull())
8496 continue;
8497
8498 if ((*it)->isImplicit())
8499 {
8500 /* deassociate and mark for deletion */
8501 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8502 rc = hd->removeBackReference(mData->mUuid);
8503 AssertComRC(rc);
8504 implicitAtts.push_back(*it);
8505 continue;
8506 }
8507
8508 /* was this hard disk attached before? */
8509 if (!findAttachment(oldAtts, hd))
8510 {
8511 /* no: de-associate */
8512 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8513 rc = hd->removeBackReference(mData->mUuid);
8514 AssertComRC(rc);
8515 continue;
8516 }
8517 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8518 }
8519
8520 /* rollback hard disk changes */
8521 mMediaData.rollback();
8522
8523 MultiResult mrc(S_OK);
8524
8525 /* delete unused implicit diffs */
8526 if (implicitAtts.size() != 0)
8527 {
8528 /* will leave the lock before the potentially lengthy
8529 * operation, so protect with the special state (unless already
8530 * protected) */
8531 MachineState_T oldState = mData->mMachineState;
8532 if ( oldState != MachineState_Saving
8533 && oldState != MachineState_LiveSnapshotting
8534 && oldState != MachineState_RestoringSnapshot
8535 && oldState != MachineState_DeletingSnapshot
8536 && oldState != MachineState_DeletingSnapshotOnline
8537 && oldState != MachineState_DeletingSnapshotPaused
8538 )
8539 setMachineState(MachineState_SettingUp);
8540
8541 alock.leave();
8542
8543 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8544 it != implicitAtts.end();
8545 ++it)
8546 {
8547 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8548 ComObjPtr<Medium> hd = (*it)->getMedium();
8549
8550 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8551 pfNeedsSaveSettings);
8552 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8553 mrc = rc;
8554 }
8555
8556 alock.enter();
8557
8558 if (mData->mMachineState == MachineState_SettingUp)
8559 {
8560 setMachineState(oldState);
8561 }
8562 }
8563
8564 return mrc;
8565}
8566
8567/**
8568 * Looks through the given list of media attachments for one with the given parameters
8569 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8570 * can be searched as well if needed.
8571 *
8572 * @param list
8573 * @param aControllerName
8574 * @param aControllerPort
8575 * @param aDevice
8576 * @return
8577 */
8578MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8579 IN_BSTR aControllerName,
8580 LONG aControllerPort,
8581 LONG aDevice)
8582{
8583 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8584 it != ll.end();
8585 ++it)
8586 {
8587 MediumAttachment *pAttach = *it;
8588 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8589 return pAttach;
8590 }
8591
8592 return NULL;
8593}
8594
8595/**
8596 * Looks through the given list of media attachments for one with the given parameters
8597 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8598 * can be searched as well if needed.
8599 *
8600 * @param list
8601 * @param aControllerName
8602 * @param aControllerPort
8603 * @param aDevice
8604 * @return
8605 */
8606MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8607 ComObjPtr<Medium> pMedium)
8608{
8609 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8610 it != ll.end();
8611 ++it)
8612 {
8613 MediumAttachment *pAttach = *it;
8614 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8615 if (pMediumThis == pMedium)
8616 return pAttach;
8617 }
8618
8619 return NULL;
8620}
8621
8622/**
8623 * Looks through the given list of media attachments for one with the given parameters
8624 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8625 * can be searched as well if needed.
8626 *
8627 * @param list
8628 * @param aControllerName
8629 * @param aControllerPort
8630 * @param aDevice
8631 * @return
8632 */
8633MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8634 Guid &id)
8635{
8636 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8637 it != ll.end();
8638 ++it)
8639 {
8640 MediumAttachment *pAttach = *it;
8641 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8642 if (pMediumThis->getId() == id)
8643 return pAttach;
8644 }
8645
8646 return NULL;
8647}
8648
8649/**
8650 * Main implementation for Machine::DetachDevice. This also gets called
8651 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8652 *
8653 * @param pAttach Medium attachment to detach.
8654 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8655 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8656 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8657 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8658 * @return
8659 */
8660HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8661 AutoWriteLock &writeLock,
8662 Snapshot *pSnapshot,
8663 bool *pfNeedsSaveSettings)
8664{
8665 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8666 DeviceType_T mediumType = pAttach->getType();
8667
8668 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8669
8670 if (pAttach->isImplicit())
8671 {
8672 /* attempt to implicitly delete the implicitly created diff */
8673
8674 /// @todo move the implicit flag from MediumAttachment to Medium
8675 /// and forbid any hard disk operation when it is implicit. Or maybe
8676 /// a special media state for it to make it even more simple.
8677
8678 Assert(mMediaData.isBackedUp());
8679
8680 /* will leave the lock before the potentially lengthy operation, so
8681 * protect with the special state */
8682 MachineState_T oldState = mData->mMachineState;
8683 setMachineState(MachineState_SettingUp);
8684
8685 writeLock.release();
8686
8687 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8688 pfNeedsSaveSettings);
8689
8690 writeLock.acquire();
8691
8692 setMachineState(oldState);
8693
8694 if (FAILED(rc)) return rc;
8695 }
8696
8697 setModified(IsModified_Storage);
8698 mMediaData.backup();
8699
8700 // we cannot use erase (it) below because backup() above will create
8701 // a copy of the list and make this copy active, but the iterator
8702 // still refers to the original and is not valid for the copy
8703 mMediaData->mAttachments.remove(pAttach);
8704
8705 if (!oldmedium.isNull())
8706 {
8707 // if this is from a snapshot, do not defer detachment to commitMedia()
8708 if (pSnapshot)
8709 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8710 // else if non-hard disk media, do not defer detachment to commitMedia() either
8711 else if (mediumType != DeviceType_HardDisk)
8712 oldmedium->removeBackReference(mData->mUuid);
8713 }
8714
8715 return S_OK;
8716}
8717
8718/**
8719 * Goes thru all medium attachments of the list and calls detachDevice() on each
8720 * of them and attaches all Medium objects found in the process to the given list,
8721 * depending on cleanupMode.
8722 *
8723 * This gets called from Machine::Unregister, both for the actual Machine and
8724 * the SnapshotMachine objects that might be found in the snapshots.
8725 *
8726 * Requires caller and locking.
8727 *
8728 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8729 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8730 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
8731 * otherwise no media get added.
8732 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
8733 * @return
8734 */
8735HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8736 Snapshot *pSnapshot,
8737 CleanupMode_T cleanupMode,
8738 MediaList &llMedia)
8739{
8740 Assert(isWriteLockOnCurrentThread());
8741
8742 HRESULT rc;
8743
8744 // make a temporary list because detachDevice invalidates iterators into
8745 // mMediaData->mAttachments
8746 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8747
8748 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8749 it != llAttachments2.end();
8750 ++it)
8751 {
8752 ComObjPtr<MediumAttachment> pAttach = *it;
8753 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8754
8755 if (!pMedium.isNull())
8756 {
8757 DeviceType_T devType = pMedium->getDeviceType();
8758 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
8759 && devType == DeviceType_HardDisk)
8760 || (cleanupMode == CleanupMode_Full)
8761 )
8762 llMedia.push_back(pMedium);
8763 }
8764
8765 // real machine: then we need to use the proper method
8766 rc = detachDevice(pAttach,
8767 writeLock,
8768 pSnapshot,
8769 NULL /* pfNeedsSaveSettings */);
8770
8771 if (FAILED(rc))
8772 return rc;
8773 }
8774
8775 return S_OK;
8776}
8777
8778/**
8779 * Perform deferred hard disk detachments.
8780 *
8781 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8782 * backed up).
8783 *
8784 * If @a aOnline is @c true then this method will also unlock the old hard disks
8785 * for which the new implicit diffs were created and will lock these new diffs for
8786 * writing.
8787 *
8788 * @param aOnline Whether the VM was online prior to this operation.
8789 *
8790 * @note Locks this object for writing!
8791 */
8792void Machine::commitMedia(bool aOnline /*= false*/)
8793{
8794 AutoCaller autoCaller(this);
8795 AssertComRCReturnVoid(autoCaller.rc());
8796
8797 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8798
8799 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
8800
8801 HRESULT rc = S_OK;
8802
8803 /* no attach/detach operations -- nothing to do */
8804 if (!mMediaData.isBackedUp())
8805 return;
8806
8807 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8808 bool fMediaNeedsLocking = false;
8809
8810 /* enumerate new attachments */
8811 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8812 it != mMediaData->mAttachments.end();
8813 ++it)
8814 {
8815 MediumAttachment *pAttach = *it;
8816
8817 pAttach->commit();
8818
8819 Medium* pMedium = pAttach->getMedium();
8820 bool fImplicit = pAttach->isImplicit();
8821
8822 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
8823 (pMedium) ? pMedium->getName().c_str() : "NULL",
8824 fImplicit));
8825
8826 /** @todo convert all this Machine-based voodoo to MediumAttachment
8827 * based commit logic. */
8828 if (fImplicit)
8829 {
8830 /* convert implicit attachment to normal */
8831 pAttach->setImplicit(false);
8832
8833 if ( aOnline
8834 && pMedium
8835 && pAttach->getType() == DeviceType_HardDisk
8836 )
8837 {
8838 ComObjPtr<Medium> parent = pMedium->getParent();
8839 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8840
8841 /* update the appropriate lock list */
8842 MediumLockList *pMediumLockList;
8843 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8844 AssertComRC(rc);
8845 if (pMediumLockList)
8846 {
8847 /* unlock if there's a need to change the locking */
8848 if (!fMediaNeedsLocking)
8849 {
8850 rc = mData->mSession.mLockedMedia.Unlock();
8851 AssertComRC(rc);
8852 fMediaNeedsLocking = true;
8853 }
8854 rc = pMediumLockList->Update(parent, false);
8855 AssertComRC(rc);
8856 rc = pMediumLockList->Append(pMedium, true);
8857 AssertComRC(rc);
8858 }
8859 }
8860
8861 continue;
8862 }
8863
8864 if (pMedium)
8865 {
8866 /* was this medium attached before? */
8867 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
8868 oldIt != oldAtts.end();
8869 ++oldIt)
8870 {
8871 MediumAttachment *pOldAttach = *oldIt;
8872 if (pOldAttach->getMedium() == pMedium)
8873 {
8874 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
8875
8876 /* yes: remove from old to avoid de-association */
8877 oldAtts.erase(oldIt);
8878 break;
8879 }
8880 }
8881 }
8882 }
8883
8884 /* enumerate remaining old attachments and de-associate from the
8885 * current machine state */
8886 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
8887 it != oldAtts.end();
8888 ++it)
8889 {
8890 MediumAttachment *pAttach = *it;
8891 Medium* pMedium = pAttach->getMedium();
8892
8893 /* Detach only hard disks, since DVD/floppy media is detached
8894 * instantly in MountMedium. */
8895 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
8896 {
8897 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
8898
8899 /* now de-associate from the current machine state */
8900 rc = pMedium->removeBackReference(mData->mUuid);
8901 AssertComRC(rc);
8902
8903 if (aOnline)
8904 {
8905 /* unlock since medium is not used anymore */
8906 MediumLockList *pMediumLockList;
8907 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8908 AssertComRC(rc);
8909 if (pMediumLockList)
8910 {
8911 rc = mData->mSession.mLockedMedia.Remove(pAttach);
8912 AssertComRC(rc);
8913 }
8914 }
8915 }
8916 }
8917
8918 /* take media locks again so that the locking state is consistent */
8919 if (fMediaNeedsLocking)
8920 {
8921 Assert(aOnline);
8922 rc = mData->mSession.mLockedMedia.Lock();
8923 AssertComRC(rc);
8924 }
8925
8926 /* commit the hard disk changes */
8927 mMediaData.commit();
8928
8929 if (isSessionMachine())
8930 {
8931 /* attach new data to the primary machine and reshare it */
8932 mPeer->mMediaData.attach(mMediaData);
8933 }
8934
8935 return;
8936}
8937
8938/**
8939 * Perform deferred deletion of implicitly created diffs.
8940 *
8941 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8942 * backed up).
8943 *
8944 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8945 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8946 *
8947 * @note Locks this object for writing!
8948 */
8949void Machine::rollbackMedia()
8950{
8951 AutoCaller autoCaller(this);
8952 AssertComRCReturnVoid (autoCaller.rc());
8953
8954 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8955
8956 LogFlowThisFunc(("Entering\n"));
8957
8958 HRESULT rc = S_OK;
8959
8960 /* no attach/detach operations -- nothing to do */
8961 if (!mMediaData.isBackedUp())
8962 return;
8963
8964 /* enumerate new attachments */
8965 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8966 it != mMediaData->mAttachments.end();
8967 ++it)
8968 {
8969 MediumAttachment *pAttach = *it;
8970 /* Fix up the backrefs for DVD/floppy media. */
8971 if (pAttach->getType() != DeviceType_HardDisk)
8972 {
8973 Medium* pMedium = pAttach->getMedium();
8974 if (pMedium)
8975 {
8976 rc = pMedium->removeBackReference(mData->mUuid);
8977 AssertComRC(rc);
8978 }
8979 }
8980
8981 (*it)->rollback();
8982
8983 pAttach = *it;
8984 /* Fix up the backrefs for DVD/floppy media. */
8985 if (pAttach->getType() != DeviceType_HardDisk)
8986 {
8987 Medium* pMedium = pAttach->getMedium();
8988 if (pMedium)
8989 {
8990 rc = pMedium->addBackReference(mData->mUuid);
8991 AssertComRC(rc);
8992 }
8993 }
8994 }
8995
8996 /** @todo convert all this Machine-based voodoo to MediumAttachment
8997 * based rollback logic. */
8998 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
8999 // which gets called if Machine::registeredInit() fails...
9000 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9001
9002 return;
9003}
9004
9005/**
9006 * Returns true if the settings file is located in the directory named exactly
9007 * as the machine. This will be true if the machine settings structure was
9008 * created by default in #openConfigLoader().
9009 *
9010 * @param aSettingsDir if not NULL, the full machine settings file directory
9011 * name will be assigned there.
9012 *
9013 * @note Doesn't lock anything.
9014 * @note Not thread safe (must be called from this object's lock).
9015 */
9016bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9017{
9018 Utf8Str settingsDir = mData->m_strConfigFileFull;
9019 settingsDir.stripFilename();
9020 Utf8Str strDirName = RTPathFilename(settingsDir.c_str());
9021
9022 AssertReturn(!strDirName.isEmpty(), false);
9023
9024 /* if we don't rename anything on name change, return false shorlty */
9025 if (!mUserData->s.fNameSync)
9026 return false;
9027
9028 if (aSettingsDir)
9029 *aSettingsDir = settingsDir;
9030
9031 return strDirName == mUserData->s.strName;
9032}
9033
9034/**
9035 * Discards all changes to machine settings.
9036 *
9037 * @param aNotify Whether to notify the direct session about changes or not.
9038 *
9039 * @note Locks objects for writing!
9040 */
9041void Machine::rollback(bool aNotify)
9042{
9043 AutoCaller autoCaller(this);
9044 AssertComRCReturn(autoCaller.rc(), (void)0);
9045
9046 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9047
9048 if (!mStorageControllers.isNull())
9049 {
9050 if (mStorageControllers.isBackedUp())
9051 {
9052 /* unitialize all new devices (absent in the backed up list). */
9053 StorageControllerList::const_iterator it = mStorageControllers->begin();
9054 StorageControllerList *backedList = mStorageControllers.backedUpData();
9055 while (it != mStorageControllers->end())
9056 {
9057 if ( std::find(backedList->begin(), backedList->end(), *it)
9058 == backedList->end()
9059 )
9060 {
9061 (*it)->uninit();
9062 }
9063 ++it;
9064 }
9065
9066 /* restore the list */
9067 mStorageControllers.rollback();
9068 }
9069
9070 /* rollback any changes to devices after restoring the list */
9071 if (mData->flModifications & IsModified_Storage)
9072 {
9073 StorageControllerList::const_iterator it = mStorageControllers->begin();
9074 while (it != mStorageControllers->end())
9075 {
9076 (*it)->rollback();
9077 ++it;
9078 }
9079 }
9080 }
9081
9082 mUserData.rollback();
9083
9084 mHWData.rollback();
9085
9086 if (mData->flModifications & IsModified_Storage)
9087 rollbackMedia();
9088
9089 if (mBIOSSettings)
9090 mBIOSSettings->rollback();
9091
9092#ifdef VBOX_WITH_VRDP
9093 if (mVRDPServer && (mData->flModifications & IsModified_VRDPServer))
9094 mVRDPServer->rollback();
9095#endif
9096
9097 if (mAudioAdapter)
9098 mAudioAdapter->rollback();
9099
9100 if (mUSBController && (mData->flModifications & IsModified_USB))
9101 mUSBController->rollback();
9102
9103 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9104 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9105 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9106
9107 if (mData->flModifications & IsModified_NetworkAdapters)
9108 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9109 if ( mNetworkAdapters[slot]
9110 && mNetworkAdapters[slot]->isModified())
9111 {
9112 mNetworkAdapters[slot]->rollback();
9113 networkAdapters[slot] = mNetworkAdapters[slot];
9114 }
9115
9116 if (mData->flModifications & IsModified_SerialPorts)
9117 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9118 if ( mSerialPorts[slot]
9119 && mSerialPorts[slot]->isModified())
9120 {
9121 mSerialPorts[slot]->rollback();
9122 serialPorts[slot] = mSerialPorts[slot];
9123 }
9124
9125 if (mData->flModifications & IsModified_ParallelPorts)
9126 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9127 if ( mParallelPorts[slot]
9128 && mParallelPorts[slot]->isModified())
9129 {
9130 mParallelPorts[slot]->rollback();
9131 parallelPorts[slot] = mParallelPorts[slot];
9132 }
9133
9134 if (aNotify)
9135 {
9136 /* inform the direct session about changes */
9137
9138 ComObjPtr<Machine> that = this;
9139 uint32_t flModifications = mData->flModifications;
9140 alock.leave();
9141
9142 if (flModifications & IsModified_SharedFolders)
9143 that->onSharedFolderChange();
9144
9145 if (flModifications & IsModified_VRDPServer)
9146 that->onVRDPServerChange(/* aRestart */ TRUE);
9147 if (flModifications & IsModified_USB)
9148 that->onUSBControllerChange();
9149
9150 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9151 if (networkAdapters[slot])
9152 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9153 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9154 if (serialPorts[slot])
9155 that->onSerialPortChange(serialPorts[slot]);
9156 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9157 if (parallelPorts[slot])
9158 that->onParallelPortChange(parallelPorts[slot]);
9159
9160 if (flModifications & IsModified_Storage)
9161 that->onStorageControllerChange();
9162 }
9163}
9164
9165/**
9166 * Commits all the changes to machine settings.
9167 *
9168 * Note that this operation is supposed to never fail.
9169 *
9170 * @note Locks this object and children for writing.
9171 */
9172void Machine::commit()
9173{
9174 AutoCaller autoCaller(this);
9175 AssertComRCReturnVoid(autoCaller.rc());
9176
9177 AutoCaller peerCaller(mPeer);
9178 AssertComRCReturnVoid(peerCaller.rc());
9179
9180 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9181
9182 /*
9183 * use safe commit to ensure Snapshot machines (that share mUserData)
9184 * will still refer to a valid memory location
9185 */
9186 mUserData.commitCopy();
9187
9188 mHWData.commit();
9189
9190 if (mMediaData.isBackedUp())
9191 commitMedia();
9192
9193 mBIOSSettings->commit();
9194#ifdef VBOX_WITH_VRDP
9195 mVRDPServer->commit();
9196#endif
9197 mAudioAdapter->commit();
9198 mUSBController->commit();
9199
9200 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9201 mNetworkAdapters[slot]->commit();
9202 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9203 mSerialPorts[slot]->commit();
9204 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9205 mParallelPorts[slot]->commit();
9206
9207 bool commitStorageControllers = false;
9208
9209 if (mStorageControllers.isBackedUp())
9210 {
9211 mStorageControllers.commit();
9212
9213 if (mPeer)
9214 {
9215 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9216
9217 /* Commit all changes to new controllers (this will reshare data with
9218 * peers for thos who have peers) */
9219 StorageControllerList *newList = new StorageControllerList();
9220 StorageControllerList::const_iterator it = mStorageControllers->begin();
9221 while (it != mStorageControllers->end())
9222 {
9223 (*it)->commit();
9224
9225 /* look if this controller has a peer device */
9226 ComObjPtr<StorageController> peer = (*it)->getPeer();
9227 if (!peer)
9228 {
9229 /* no peer means the device is a newly created one;
9230 * create a peer owning data this device share it with */
9231 peer.createObject();
9232 peer->init(mPeer, *it, true /* aReshare */);
9233 }
9234 else
9235 {
9236 /* remove peer from the old list */
9237 mPeer->mStorageControllers->remove(peer);
9238 }
9239 /* and add it to the new list */
9240 newList->push_back(peer);
9241
9242 ++it;
9243 }
9244
9245 /* uninit old peer's controllers that are left */
9246 it = mPeer->mStorageControllers->begin();
9247 while (it != mPeer->mStorageControllers->end())
9248 {
9249 (*it)->uninit();
9250 ++it;
9251 }
9252
9253 /* attach new list of controllers to our peer */
9254 mPeer->mStorageControllers.attach(newList);
9255 }
9256 else
9257 {
9258 /* we have no peer (our parent is the newly created machine);
9259 * just commit changes to devices */
9260 commitStorageControllers = true;
9261 }
9262 }
9263 else
9264 {
9265 /* the list of controllers itself is not changed,
9266 * just commit changes to controllers themselves */
9267 commitStorageControllers = true;
9268 }
9269
9270 if (commitStorageControllers)
9271 {
9272 StorageControllerList::const_iterator it = mStorageControllers->begin();
9273 while (it != mStorageControllers->end())
9274 {
9275 (*it)->commit();
9276 ++it;
9277 }
9278 }
9279
9280 if (isSessionMachine())
9281 {
9282 /* attach new data to the primary machine and reshare it */
9283 mPeer->mUserData.attach(mUserData);
9284 mPeer->mHWData.attach(mHWData);
9285 /* mMediaData is reshared by fixupMedia */
9286 // mPeer->mMediaData.attach(mMediaData);
9287 Assert(mPeer->mMediaData.data() == mMediaData.data());
9288 }
9289}
9290
9291/**
9292 * Copies all the hardware data from the given machine.
9293 *
9294 * Currently, only called when the VM is being restored from a snapshot. In
9295 * particular, this implies that the VM is not running during this method's
9296 * call.
9297 *
9298 * @note This method must be called from under this object's lock.
9299 *
9300 * @note This method doesn't call #commit(), so all data remains backed up and
9301 * unsaved.
9302 */
9303void Machine::copyFrom(Machine *aThat)
9304{
9305 AssertReturnVoid(!isSnapshotMachine());
9306 AssertReturnVoid(aThat->isSnapshotMachine());
9307
9308 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9309
9310 mHWData.assignCopy(aThat->mHWData);
9311
9312 // create copies of all shared folders (mHWData after attiching a copy
9313 // contains just references to original objects)
9314 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9315 it != mHWData->mSharedFolders.end();
9316 ++it)
9317 {
9318 ComObjPtr<SharedFolder> folder;
9319 folder.createObject();
9320 HRESULT rc = folder->initCopy(getMachine(), *it);
9321 AssertComRC(rc);
9322 *it = folder;
9323 }
9324
9325 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9326#ifdef VBOX_WITH_VRDP
9327 mVRDPServer->copyFrom(aThat->mVRDPServer);
9328#endif
9329 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9330 mUSBController->copyFrom(aThat->mUSBController);
9331
9332 /* create private copies of all controllers */
9333 mStorageControllers.backup();
9334 mStorageControllers->clear();
9335 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9336 it != aThat->mStorageControllers->end();
9337 ++it)
9338 {
9339 ComObjPtr<StorageController> ctrl;
9340 ctrl.createObject();
9341 ctrl->initCopy(this, *it);
9342 mStorageControllers->push_back(ctrl);
9343 }
9344
9345 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9346 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9347 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9348 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9349 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9350 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9351}
9352
9353#ifdef VBOX_WITH_RESOURCE_USAGE_API
9354
9355void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9356{
9357 AssertReturnVoid(isWriteLockOnCurrentThread());
9358 AssertPtrReturnVoid(aCollector);
9359
9360 pm::CollectorHAL *hal = aCollector->getHAL();
9361 /* Create sub metrics */
9362 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9363 "Percentage of processor time spent in user mode by the VM process.");
9364 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9365 "Percentage of processor time spent in kernel mode by the VM process.");
9366 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9367 "Size of resident portion of VM process in memory.");
9368 /* Create and register base metrics */
9369 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9370 cpuLoadUser, cpuLoadKernel);
9371 aCollector->registerBaseMetric(cpuLoad);
9372 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9373 ramUsageUsed);
9374 aCollector->registerBaseMetric(ramUsage);
9375
9376 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9377 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9378 new pm::AggregateAvg()));
9379 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9380 new pm::AggregateMin()));
9381 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9382 new pm::AggregateMax()));
9383 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9384 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9385 new pm::AggregateAvg()));
9386 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9387 new pm::AggregateMin()));
9388 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9389 new pm::AggregateMax()));
9390
9391 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9392 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9393 new pm::AggregateAvg()));
9394 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9395 new pm::AggregateMin()));
9396 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9397 new pm::AggregateMax()));
9398
9399
9400 /* Guest metrics */
9401 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9402
9403 /* Create sub metrics */
9404 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9405 "Percentage of processor time spent in user mode as seen by the guest.");
9406 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9407 "Percentage of processor time spent in kernel mode as seen by the guest.");
9408 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9409 "Percentage of processor time spent idling as seen by the guest.");
9410
9411 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9412 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9413 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9414 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9415 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9416 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9417
9418 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9419
9420 /* Create and register base metrics */
9421 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9422 aCollector->registerBaseMetric(guestCpuLoad);
9423
9424 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9425 guestMemCache, guestPagedTotal);
9426 aCollector->registerBaseMetric(guestCpuMem);
9427
9428 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9429 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9430 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9431 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9432
9433 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9434 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9435 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9436 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9437
9438 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9439 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9440 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9441 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9442
9443 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9444 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9445 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9446 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9447
9448 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9449 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9450 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9451 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9452
9453 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9454 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9455 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9456 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9457
9458 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9459 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9460 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9461 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9462
9463 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9464 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9465 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9466 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9467
9468 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9469 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9470 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9471 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9472}
9473
9474void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9475{
9476 AssertReturnVoid(isWriteLockOnCurrentThread());
9477
9478 if (aCollector)
9479 {
9480 aCollector->unregisterMetricsFor(aMachine);
9481 aCollector->unregisterBaseMetricsFor(aMachine);
9482 }
9483
9484 if (mGuestHAL)
9485 {
9486 delete mGuestHAL;
9487 mGuestHAL = NULL;
9488 }
9489}
9490
9491#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9492
9493
9494////////////////////////////////////////////////////////////////////////////////
9495
9496DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9497
9498HRESULT SessionMachine::FinalConstruct()
9499{
9500 LogFlowThisFunc(("\n"));
9501
9502#if defined(RT_OS_WINDOWS)
9503 mIPCSem = NULL;
9504#elif defined(RT_OS_OS2)
9505 mIPCSem = NULLHANDLE;
9506#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9507 mIPCSem = -1;
9508#else
9509# error "Port me!"
9510#endif
9511
9512 return S_OK;
9513}
9514
9515void SessionMachine::FinalRelease()
9516{
9517 LogFlowThisFunc(("\n"));
9518
9519 uninit(Uninit::Unexpected);
9520}
9521
9522/**
9523 * @note Must be called only by Machine::openSession() from its own write lock.
9524 */
9525HRESULT SessionMachine::init(Machine *aMachine)
9526{
9527 LogFlowThisFuncEnter();
9528 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9529
9530 AssertReturn(aMachine, E_INVALIDARG);
9531
9532 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9533
9534 /* Enclose the state transition NotReady->InInit->Ready */
9535 AutoInitSpan autoInitSpan(this);
9536 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9537
9538 /* create the interprocess semaphore */
9539#if defined(RT_OS_WINDOWS)
9540 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9541 for (size_t i = 0; i < mIPCSemName.length(); i++)
9542 if (mIPCSemName[i] == '\\')
9543 mIPCSemName[i] = '/';
9544 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName);
9545 ComAssertMsgRet(mIPCSem,
9546 ("Cannot create IPC mutex '%ls', err=%d",
9547 mIPCSemName.raw(), ::GetLastError()),
9548 E_FAIL);
9549#elif defined(RT_OS_OS2)
9550 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9551 aMachine->mData->mUuid.raw());
9552 mIPCSemName = ipcSem;
9553 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.raw(), &mIPCSem, 0, FALSE);
9554 ComAssertMsgRet(arc == NO_ERROR,
9555 ("Cannot create IPC mutex '%s', arc=%ld",
9556 ipcSem.raw(), arc),
9557 E_FAIL);
9558#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9559# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9560# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9561 /** @todo Check that this still works correctly. */
9562 AssertCompileSize(key_t, 8);
9563# else
9564 AssertCompileSize(key_t, 4);
9565# endif
9566 key_t key;
9567 mIPCSem = -1;
9568 mIPCKey = "0";
9569 for (uint32_t i = 0; i < 1 << 24; i++)
9570 {
9571 key = ((uint32_t)'V' << 24) | i;
9572 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9573 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9574 {
9575 mIPCSem = sem;
9576 if (sem >= 0)
9577 mIPCKey = BstrFmt("%u", key);
9578 break;
9579 }
9580 }
9581# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9582 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9583 char *pszSemName = NULL;
9584 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9585 key_t key = ::ftok(pszSemName, 'V');
9586 RTStrFree(pszSemName);
9587
9588 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9589# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9590
9591 int errnoSave = errno;
9592 if (mIPCSem < 0 && errnoSave == ENOSYS)
9593 {
9594 setError(E_FAIL,
9595 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9596 "support for SysV IPC. Check the host kernel configuration for "
9597 "CONFIG_SYSVIPC=y"));
9598 return E_FAIL;
9599 }
9600 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9601 * the IPC semaphores */
9602 if (mIPCSem < 0 && errnoSave == ENOSPC)
9603 {
9604#ifdef RT_OS_LINUX
9605 setError(E_FAIL,
9606 tr("Cannot create IPC semaphore because the system limit for the "
9607 "maximum number of semaphore sets (SEMMNI), or the system wide "
9608 "maximum number of sempahores (SEMMNS) would be exceeded. The "
9609 "current set of SysV IPC semaphores can be determined from "
9610 "the file /proc/sysvipc/sem"));
9611#else
9612 setError(E_FAIL,
9613 tr("Cannot create IPC semaphore because the system-imposed limit "
9614 "on the maximum number of allowed semaphores or semaphore "
9615 "identifiers system-wide would be exceeded"));
9616#endif
9617 return E_FAIL;
9618 }
9619 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9620 E_FAIL);
9621 /* set the initial value to 1 */
9622 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9623 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9624 E_FAIL);
9625#else
9626# error "Port me!"
9627#endif
9628
9629 /* memorize the peer Machine */
9630 unconst(mPeer) = aMachine;
9631 /* share the parent pointer */
9632 unconst(mParent) = aMachine->mParent;
9633
9634 /* take the pointers to data to share */
9635 mData.share(aMachine->mData);
9636 mSSData.share(aMachine->mSSData);
9637
9638 mUserData.share(aMachine->mUserData);
9639 mHWData.share(aMachine->mHWData);
9640 mMediaData.share(aMachine->mMediaData);
9641
9642 mStorageControllers.allocate();
9643 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9644 it != aMachine->mStorageControllers->end();
9645 ++it)
9646 {
9647 ComObjPtr<StorageController> ctl;
9648 ctl.createObject();
9649 ctl->init(this, *it);
9650 mStorageControllers->push_back(ctl);
9651 }
9652
9653 unconst(mBIOSSettings).createObject();
9654 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9655#ifdef VBOX_WITH_VRDP
9656 /* create another VRDPServer object that will be mutable */
9657 unconst(mVRDPServer).createObject();
9658 mVRDPServer->init(this, aMachine->mVRDPServer);
9659#endif
9660 /* create another audio adapter object that will be mutable */
9661 unconst(mAudioAdapter).createObject();
9662 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9663 /* create a list of serial ports that will be mutable */
9664 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9665 {
9666 unconst(mSerialPorts[slot]).createObject();
9667 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9668 }
9669 /* create a list of parallel ports that will be mutable */
9670 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9671 {
9672 unconst(mParallelPorts[slot]).createObject();
9673 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9674 }
9675 /* create another USB controller object that will be mutable */
9676 unconst(mUSBController).createObject();
9677 mUSBController->init(this, aMachine->mUSBController);
9678
9679 /* create a list of network adapters that will be mutable */
9680 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9681 {
9682 unconst(mNetworkAdapters[slot]).createObject();
9683 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9684 }
9685
9686 /* default is to delete saved state on Saved -> PoweredOff transition */
9687 mRemoveSavedState = true;
9688
9689 /* Confirm a successful initialization when it's the case */
9690 autoInitSpan.setSucceeded();
9691
9692 LogFlowThisFuncLeave();
9693 return S_OK;
9694}
9695
9696/**
9697 * Uninitializes this session object. If the reason is other than
9698 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9699 *
9700 * @param aReason uninitialization reason
9701 *
9702 * @note Locks mParent + this object for writing.
9703 */
9704void SessionMachine::uninit(Uninit::Reason aReason)
9705{
9706 LogFlowThisFuncEnter();
9707 LogFlowThisFunc(("reason=%d\n", aReason));
9708
9709 /*
9710 * Strongly reference ourselves to prevent this object deletion after
9711 * mData->mSession.mMachine.setNull() below (which can release the last
9712 * reference and call the destructor). Important: this must be done before
9713 * accessing any members (and before AutoUninitSpan that does it as well).
9714 * This self reference will be released as the very last step on return.
9715 */
9716 ComObjPtr<SessionMachine> selfRef = this;
9717
9718 /* Enclose the state transition Ready->InUninit->NotReady */
9719 AutoUninitSpan autoUninitSpan(this);
9720 if (autoUninitSpan.uninitDone())
9721 {
9722 LogFlowThisFunc(("Already uninitialized\n"));
9723 LogFlowThisFuncLeave();
9724 return;
9725 }
9726
9727 if (autoUninitSpan.initFailed())
9728 {
9729 /* We've been called by init() because it's failed. It's not really
9730 * necessary (nor it's safe) to perform the regular uninit sequense
9731 * below, the following is enough.
9732 */
9733 LogFlowThisFunc(("Initialization failed.\n"));
9734#if defined(RT_OS_WINDOWS)
9735 if (mIPCSem)
9736 ::CloseHandle(mIPCSem);
9737 mIPCSem = NULL;
9738#elif defined(RT_OS_OS2)
9739 if (mIPCSem != NULLHANDLE)
9740 ::DosCloseMutexSem(mIPCSem);
9741 mIPCSem = NULLHANDLE;
9742#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9743 if (mIPCSem >= 0)
9744 ::semctl(mIPCSem, 0, IPC_RMID);
9745 mIPCSem = -1;
9746# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9747 mIPCKey = "0";
9748# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9749#else
9750# error "Port me!"
9751#endif
9752 uninitDataAndChildObjects();
9753 mData.free();
9754 unconst(mParent) = NULL;
9755 unconst(mPeer) = NULL;
9756 LogFlowThisFuncLeave();
9757 return;
9758 }
9759
9760 MachineState_T lastState;
9761 {
9762 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9763 lastState = mData->mMachineState;
9764 }
9765 NOREF(lastState);
9766
9767#ifdef VBOX_WITH_USB
9768 // release all captured USB devices, but do this before requesting the locks below
9769 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9770 {
9771 /* Console::captureUSBDevices() is called in the VM process only after
9772 * setting the machine state to Starting or Restoring.
9773 * Console::detachAllUSBDevices() will be called upon successful
9774 * termination. So, we need to release USB devices only if there was
9775 * an abnormal termination of a running VM.
9776 *
9777 * This is identical to SessionMachine::DetachAllUSBDevices except
9778 * for the aAbnormal argument. */
9779 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9780 AssertComRC(rc);
9781 NOREF(rc);
9782
9783 USBProxyService *service = mParent->host()->usbProxyService();
9784 if (service)
9785 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9786 }
9787#endif /* VBOX_WITH_USB */
9788
9789 // we need to lock this object in uninit() because the lock is shared
9790 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
9791 // and others need mParent lock, and USB needs host lock.
9792 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
9793
9794 // Trigger async cleanup tasks, avoid doing things here which are not
9795 // vital to be done immediately and maybe need more locks. This calls
9796 // Machine::unregisterMetrics().
9797 mParent->onMachineUninit(mPeer);
9798
9799 if (aReason == Uninit::Abnormal)
9800 {
9801 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
9802 Global::IsOnlineOrTransient(lastState)));
9803
9804 /* reset the state to Aborted */
9805 if (mData->mMachineState != MachineState_Aborted)
9806 setMachineState(MachineState_Aborted);
9807 }
9808
9809 // any machine settings modified?
9810 if (mData->flModifications)
9811 {
9812 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
9813 rollback(false /* aNotify */);
9814 }
9815
9816 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
9817 if (!mSnapshotData.mStateFilePath.isEmpty())
9818 {
9819 LogWarningThisFunc(("canceling failed save state request!\n"));
9820 endSavingState(FALSE /* aSuccess */);
9821 }
9822 else if (!mSnapshotData.mSnapshot.isNull())
9823 {
9824 LogWarningThisFunc(("canceling untaken snapshot!\n"));
9825
9826 /* delete all differencing hard disks created (this will also attach
9827 * their parents back by rolling back mMediaData) */
9828 rollbackMedia();
9829 /* delete the saved state file (it might have been already created) */
9830 if (mSnapshotData.mSnapshot->stateFilePath().length())
9831 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
9832
9833 mSnapshotData.mSnapshot->uninit();
9834 }
9835
9836 if (!mData->mSession.mType.isEmpty())
9837 {
9838 /* mType is not null when this machine's process has been started by
9839 * Machine::launchVMProcess(), therefore it is our child. We
9840 * need to queue the PID to reap the process (and avoid zombies on
9841 * Linux). */
9842 Assert(mData->mSession.mPid != NIL_RTPROCESS);
9843 mParent->addProcessToReap(mData->mSession.mPid);
9844 }
9845
9846 mData->mSession.mPid = NIL_RTPROCESS;
9847
9848 if (aReason == Uninit::Unexpected)
9849 {
9850 /* Uninitialization didn't come from #checkForDeath(), so tell the
9851 * client watcher thread to update the set of machines that have open
9852 * sessions. */
9853 mParent->updateClientWatcher();
9854 }
9855
9856 /* uninitialize all remote controls */
9857 if (mData->mSession.mRemoteControls.size())
9858 {
9859 LogFlowThisFunc(("Closing remote sessions (%d):\n",
9860 mData->mSession.mRemoteControls.size()));
9861
9862 Data::Session::RemoteControlList::iterator it =
9863 mData->mSession.mRemoteControls.begin();
9864 while (it != mData->mSession.mRemoteControls.end())
9865 {
9866 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
9867 HRESULT rc = (*it)->Uninitialize();
9868 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
9869 if (FAILED(rc))
9870 LogWarningThisFunc(("Forgot to close the remote session?\n"));
9871 ++it;
9872 }
9873 mData->mSession.mRemoteControls.clear();
9874 }
9875
9876 /*
9877 * An expected uninitialization can come only from #checkForDeath().
9878 * Otherwise it means that something's got really wrong (for examlple,
9879 * the Session implementation has released the VirtualBox reference
9880 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
9881 * etc). However, it's also possible, that the client releases the IPC
9882 * semaphore correctly (i.e. before it releases the VirtualBox reference),
9883 * but the VirtualBox release event comes first to the server process.
9884 * This case is practically possible, so we should not assert on an
9885 * unexpected uninit, just log a warning.
9886 */
9887
9888 if ((aReason == Uninit::Unexpected))
9889 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
9890
9891 if (aReason != Uninit::Normal)
9892 {
9893 mData->mSession.mDirectControl.setNull();
9894 }
9895 else
9896 {
9897 /* this must be null here (see #OnSessionEnd()) */
9898 Assert(mData->mSession.mDirectControl.isNull());
9899 Assert(mData->mSession.mState == SessionState_Unlocking);
9900 Assert(!mData->mSession.mProgress.isNull());
9901 }
9902 if (mData->mSession.mProgress)
9903 {
9904 if (aReason == Uninit::Normal)
9905 mData->mSession.mProgress->notifyComplete(S_OK);
9906 else
9907 mData->mSession.mProgress->notifyComplete(E_FAIL,
9908 COM_IIDOF(ISession),
9909 getComponentName(),
9910 tr("The VM session was aborted"));
9911 mData->mSession.mProgress.setNull();
9912 }
9913
9914 /* remove the association between the peer machine and this session machine */
9915 Assert( (SessionMachine*)mData->mSession.mMachine == this
9916 || aReason == Uninit::Unexpected);
9917
9918 /* reset the rest of session data */
9919 mData->mSession.mMachine.setNull();
9920 mData->mSession.mState = SessionState_Unlocked;
9921 mData->mSession.mType.setNull();
9922
9923 /* close the interprocess semaphore before leaving the exclusive lock */
9924#if defined(RT_OS_WINDOWS)
9925 if (mIPCSem)
9926 ::CloseHandle(mIPCSem);
9927 mIPCSem = NULL;
9928#elif defined(RT_OS_OS2)
9929 if (mIPCSem != NULLHANDLE)
9930 ::DosCloseMutexSem(mIPCSem);
9931 mIPCSem = NULLHANDLE;
9932#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9933 if (mIPCSem >= 0)
9934 ::semctl(mIPCSem, 0, IPC_RMID);
9935 mIPCSem = -1;
9936# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9937 mIPCKey = "0";
9938# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9939#else
9940# error "Port me!"
9941#endif
9942
9943 /* fire an event */
9944 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
9945
9946 uninitDataAndChildObjects();
9947
9948 /* free the essential data structure last */
9949 mData.free();
9950
9951#if 1 /** @todo Please review this change! (bird) */
9952 /* drop the exclusive lock before setting the below two to NULL */
9953 multilock.release();
9954#else
9955 /* leave the exclusive lock before setting the below two to NULL */
9956 multilock.leave();
9957#endif
9958
9959 unconst(mParent) = NULL;
9960 unconst(mPeer) = NULL;
9961
9962 LogFlowThisFuncLeave();
9963}
9964
9965// util::Lockable interface
9966////////////////////////////////////////////////////////////////////////////////
9967
9968/**
9969 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
9970 * with the primary Machine instance (mPeer).
9971 */
9972RWLockHandle *SessionMachine::lockHandle() const
9973{
9974 AssertReturn(mPeer != NULL, NULL);
9975 return mPeer->lockHandle();
9976}
9977
9978// IInternalMachineControl methods
9979////////////////////////////////////////////////////////////////////////////////
9980
9981/**
9982 * @note Locks this object for writing.
9983 */
9984STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
9985{
9986 AutoCaller autoCaller(this);
9987 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9988
9989 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9990
9991 mRemoveSavedState = aRemove;
9992
9993 return S_OK;
9994}
9995
9996/**
9997 * @note Locks the same as #setMachineState() does.
9998 */
9999STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10000{
10001 return setMachineState(aMachineState);
10002}
10003
10004/**
10005 * @note Locks this object for reading.
10006 */
10007STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10008{
10009 AutoCaller autoCaller(this);
10010 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10011
10012 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10013
10014#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10015 mIPCSemName.cloneTo(aId);
10016 return S_OK;
10017#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10018# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10019 mIPCKey.cloneTo(aId);
10020# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10021 mData->m_strConfigFileFull.cloneTo(aId);
10022# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10023 return S_OK;
10024#else
10025# error "Port me!"
10026#endif
10027}
10028
10029/**
10030 * @note Locks this object for writing.
10031 */
10032STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10033{
10034 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10035 AutoCaller autoCaller(this);
10036 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10037
10038 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10039
10040 if (mData->mSession.mState != SessionState_Locked)
10041 return VBOX_E_INVALID_OBJECT_STATE;
10042
10043 if (!mData->mSession.mProgress.isNull())
10044 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10045
10046 LogFlowThisFunc(("returns S_OK.\n"));
10047 return S_OK;
10048}
10049
10050
10051/**
10052 * @note Locks this object for writing.
10053 */
10054STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10055{
10056 AutoCaller autoCaller(this);
10057 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10058
10059 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10060
10061 if (mData->mSession.mState != SessionState_Locked)
10062 return VBOX_E_INVALID_OBJECT_STATE;
10063
10064 /* Finalize the openRemoteSession progress object. */
10065 if (mData->mSession.mProgress)
10066 {
10067 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10068 mData->mSession.mProgress.setNull();
10069
10070 if (SUCCEEDED((HRESULT)iResult))
10071 {
10072#ifdef VBOX_WITH_RESOURCE_USAGE_API
10073 /* The VM has been powered up successfully, so it makes sense
10074 * now to offer the performance metrics for a running machine
10075 * object. Doing it earlier wouldn't be safe. */
10076 registerMetrics(mParent->performanceCollector(), mPeer,
10077 mData->mSession.mPid);
10078#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10079
10080 }
10081 }
10082 return S_OK;
10083}
10084
10085/**
10086 * Goes through the USB filters of the given machine to see if the given
10087 * device matches any filter or not.
10088 *
10089 * @note Locks the same as USBController::hasMatchingFilter() does.
10090 */
10091STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10092 BOOL *aMatched,
10093 ULONG *aMaskedIfs)
10094{
10095 LogFlowThisFunc(("\n"));
10096
10097 CheckComArgNotNull(aUSBDevice);
10098 CheckComArgOutPointerValid(aMatched);
10099
10100 AutoCaller autoCaller(this);
10101 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10102
10103#ifdef VBOX_WITH_USB
10104 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10105#else
10106 NOREF(aUSBDevice);
10107 NOREF(aMaskedIfs);
10108 *aMatched = FALSE;
10109#endif
10110
10111 return S_OK;
10112}
10113
10114/**
10115 * @note Locks the same as Host::captureUSBDevice() does.
10116 */
10117STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10118{
10119 LogFlowThisFunc(("\n"));
10120
10121 AutoCaller autoCaller(this);
10122 AssertComRCReturnRC(autoCaller.rc());
10123
10124#ifdef VBOX_WITH_USB
10125 /* if captureDeviceForVM() fails, it must have set extended error info */
10126 MultiResult rc = mParent->host()->checkUSBProxyService();
10127 if (FAILED(rc)) return rc;
10128
10129 USBProxyService *service = mParent->host()->usbProxyService();
10130 AssertReturn(service, E_FAIL);
10131 return service->captureDeviceForVM(this, Guid(aId));
10132#else
10133 NOREF(aId);
10134 return E_NOTIMPL;
10135#endif
10136}
10137
10138/**
10139 * @note Locks the same as Host::detachUSBDevice() does.
10140 */
10141STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10142{
10143 LogFlowThisFunc(("\n"));
10144
10145 AutoCaller autoCaller(this);
10146 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10147
10148#ifdef VBOX_WITH_USB
10149 USBProxyService *service = mParent->host()->usbProxyService();
10150 AssertReturn(service, E_FAIL);
10151 return service->detachDeviceFromVM(this, Guid(aId), !!aDone);
10152#else
10153 NOREF(aId);
10154 NOREF(aDone);
10155 return E_NOTIMPL;
10156#endif
10157}
10158
10159/**
10160 * Inserts all machine filters to the USB proxy service and then calls
10161 * Host::autoCaptureUSBDevices().
10162 *
10163 * Called by Console from the VM process upon VM startup.
10164 *
10165 * @note Locks what called methods lock.
10166 */
10167STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10168{
10169 LogFlowThisFunc(("\n"));
10170
10171 AutoCaller autoCaller(this);
10172 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10173
10174#ifdef VBOX_WITH_USB
10175 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10176 AssertComRC(rc);
10177 NOREF(rc);
10178
10179 USBProxyService *service = mParent->host()->usbProxyService();
10180 AssertReturn(service, E_FAIL);
10181 return service->autoCaptureDevicesForVM(this);
10182#else
10183 return S_OK;
10184#endif
10185}
10186
10187/**
10188 * Removes all machine filters from the USB proxy service and then calls
10189 * Host::detachAllUSBDevices().
10190 *
10191 * Called by Console from the VM process upon normal VM termination or by
10192 * SessionMachine::uninit() upon abnormal VM termination (from under the
10193 * Machine/SessionMachine lock).
10194 *
10195 * @note Locks what called methods lock.
10196 */
10197STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10198{
10199 LogFlowThisFunc(("\n"));
10200
10201 AutoCaller autoCaller(this);
10202 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10203
10204#ifdef VBOX_WITH_USB
10205 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10206 AssertComRC(rc);
10207 NOREF(rc);
10208
10209 USBProxyService *service = mParent->host()->usbProxyService();
10210 AssertReturn(service, E_FAIL);
10211 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10212#else
10213 NOREF(aDone);
10214 return S_OK;
10215#endif
10216}
10217
10218/**
10219 * @note Locks this object for writing.
10220 */
10221STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10222 IProgress **aProgress)
10223{
10224 LogFlowThisFuncEnter();
10225
10226 AssertReturn(aSession, E_INVALIDARG);
10227 AssertReturn(aProgress, E_INVALIDARG);
10228
10229 AutoCaller autoCaller(this);
10230
10231 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10232 /*
10233 * We don't assert below because it might happen that a non-direct session
10234 * informs us it is closed right after we've been uninitialized -- it's ok.
10235 */
10236 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10237
10238 /* get IInternalSessionControl interface */
10239 ComPtr<IInternalSessionControl> control(aSession);
10240
10241 ComAssertRet(!control.isNull(), E_INVALIDARG);
10242
10243 /* Creating a Progress object requires the VirtualBox lock, and
10244 * thus locking it here is required by the lock order rules. */
10245 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10246
10247 if (control == mData->mSession.mDirectControl)
10248 {
10249 ComAssertRet(aProgress, E_POINTER);
10250
10251 /* The direct session is being normally closed by the client process
10252 * ----------------------------------------------------------------- */
10253
10254 /* go to the closing state (essential for all open*Session() calls and
10255 * for #checkForDeath()) */
10256 Assert(mData->mSession.mState == SessionState_Locked);
10257 mData->mSession.mState = SessionState_Unlocking;
10258
10259 /* set direct control to NULL to release the remote instance */
10260 mData->mSession.mDirectControl.setNull();
10261 LogFlowThisFunc(("Direct control is set to NULL\n"));
10262
10263 if (mData->mSession.mProgress)
10264 {
10265 /* finalize the progress, someone might wait if a frontend
10266 * closes the session before powering on the VM. */
10267 mData->mSession.mProgress->notifyComplete(E_FAIL,
10268 COM_IIDOF(ISession),
10269 getComponentName(),
10270 tr("The VM session was closed before any attempt to power it on"));
10271 mData->mSession.mProgress.setNull();
10272 }
10273
10274 /* Create the progress object the client will use to wait until
10275 * #checkForDeath() is called to uninitialize this session object after
10276 * it releases the IPC semaphore.
10277 * Note! Because we're "reusing" mProgress here, this must be a proxy
10278 * object just like for openRemoteSession. */
10279 Assert(mData->mSession.mProgress.isNull());
10280 ComObjPtr<ProgressProxy> progress;
10281 progress.createObject();
10282 ComPtr<IUnknown> pPeer(mPeer);
10283 progress->init(mParent, pPeer,
10284 Bstr(tr("Closing session")),
10285 FALSE /* aCancelable */);
10286 progress.queryInterfaceTo(aProgress);
10287 mData->mSession.mProgress = progress;
10288 }
10289 else
10290 {
10291 /* the remote session is being normally closed */
10292 Data::Session::RemoteControlList::iterator it =
10293 mData->mSession.mRemoteControls.begin();
10294 while (it != mData->mSession.mRemoteControls.end())
10295 {
10296 if (control == *it)
10297 break;
10298 ++it;
10299 }
10300 BOOL found = it != mData->mSession.mRemoteControls.end();
10301 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10302 E_INVALIDARG);
10303 mData->mSession.mRemoteControls.remove(*it);
10304 }
10305
10306 LogFlowThisFuncLeave();
10307 return S_OK;
10308}
10309
10310/**
10311 * @note Locks this object for writing.
10312 */
10313STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10314{
10315 LogFlowThisFuncEnter();
10316
10317 AssertReturn(aProgress, E_INVALIDARG);
10318 AssertReturn(aStateFilePath, E_POINTER);
10319
10320 AutoCaller autoCaller(this);
10321 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10322
10323 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10324
10325 AssertReturn( mData->mMachineState == MachineState_Paused
10326 && mSnapshotData.mLastState == MachineState_Null
10327 && mSnapshotData.mProgressId.isEmpty()
10328 && mSnapshotData.mStateFilePath.isEmpty(),
10329 E_FAIL);
10330
10331 /* memorize the progress ID and add it to the global collection */
10332 Bstr progressId;
10333 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10334 AssertComRCReturn(rc, rc);
10335 rc = mParent->addProgress(aProgress);
10336 AssertComRCReturn(rc, rc);
10337
10338 Bstr stateFilePath;
10339 /* stateFilePath is null when the machine is not running */
10340 if (mData->mMachineState == MachineState_Paused)
10341 {
10342 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10343 mUserData->m_strSnapshotFolderFull.c_str(),
10344 RTPATH_DELIMITER, mData->mUuid.raw());
10345 }
10346
10347 /* fill in the snapshot data */
10348 mSnapshotData.mLastState = mData->mMachineState;
10349 mSnapshotData.mProgressId = Guid(progressId);
10350 mSnapshotData.mStateFilePath = stateFilePath;
10351
10352 /* set the state to Saving (this is expected by Console::SaveState()) */
10353 setMachineState(MachineState_Saving);
10354
10355 stateFilePath.cloneTo(aStateFilePath);
10356
10357 return S_OK;
10358}
10359
10360/**
10361 * @note Locks mParent + this object for writing.
10362 */
10363STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10364{
10365 LogFlowThisFunc(("\n"));
10366
10367 AutoCaller autoCaller(this);
10368 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10369
10370 /* endSavingState() need mParent lock */
10371 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10372
10373 AssertReturn( mData->mMachineState == MachineState_Saving
10374 && mSnapshotData.mLastState != MachineState_Null
10375 && !mSnapshotData.mProgressId.isEmpty()
10376 && !mSnapshotData.mStateFilePath.isEmpty(),
10377 E_FAIL);
10378
10379 /*
10380 * on success, set the state to Saved;
10381 * on failure, set the state to the state we had when BeginSavingState() was
10382 * called (this is expected by Console::SaveState() and
10383 * Console::saveStateThread())
10384 */
10385 if (aSuccess)
10386 setMachineState(MachineState_Saved);
10387 else
10388 setMachineState(mSnapshotData.mLastState);
10389
10390 return endSavingState(aSuccess);
10391}
10392
10393/**
10394 * @note Locks this object for writing.
10395 */
10396STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10397{
10398 LogFlowThisFunc(("\n"));
10399
10400 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10401
10402 AutoCaller autoCaller(this);
10403 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10404
10405 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10406
10407 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10408 || mData->mMachineState == MachineState_Teleported
10409 || mData->mMachineState == MachineState_Aborted
10410 , E_FAIL); /** @todo setError. */
10411
10412 Utf8Str stateFilePathFull = aSavedStateFile;
10413 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10414 if (RT_FAILURE(vrc))
10415 return setError(VBOX_E_FILE_ERROR,
10416 tr("Invalid saved state file path '%ls' (%Rrc)"),
10417 aSavedStateFile,
10418 vrc);
10419
10420 mSSData->mStateFilePath = stateFilePathFull;
10421
10422 /* The below setMachineState() will detect the state transition and will
10423 * update the settings file */
10424
10425 return setMachineState(MachineState_Saved);
10426}
10427
10428STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10429 ComSafeArrayOut(BSTR, aValues),
10430 ComSafeArrayOut(ULONG64, aTimestamps),
10431 ComSafeArrayOut(BSTR, aFlags))
10432{
10433 LogFlowThisFunc(("\n"));
10434
10435#ifdef VBOX_WITH_GUEST_PROPS
10436 using namespace guestProp;
10437
10438 AutoCaller autoCaller(this);
10439 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10440
10441 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10442
10443 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10444 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10445 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10446 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10447
10448 size_t cEntries = mHWData->mGuestProperties.size();
10449 com::SafeArray<BSTR> names(cEntries);
10450 com::SafeArray<BSTR> values(cEntries);
10451 com::SafeArray<ULONG64> timestamps(cEntries);
10452 com::SafeArray<BSTR> flags(cEntries);
10453 unsigned i = 0;
10454 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10455 it != mHWData->mGuestProperties.end();
10456 ++it)
10457 {
10458 char szFlags[MAX_FLAGS_LEN + 1];
10459 it->strName.cloneTo(&names[i]);
10460 it->strValue.cloneTo(&values[i]);
10461 timestamps[i] = it->mTimestamp;
10462 /* If it is NULL, keep it NULL. */
10463 if (it->mFlags)
10464 {
10465 writeFlags(it->mFlags, szFlags);
10466 Bstr(szFlags).cloneTo(&flags[i]);
10467 }
10468 else
10469 flags[i] = NULL;
10470 ++i;
10471 }
10472 names.detachTo(ComSafeArrayOutArg(aNames));
10473 values.detachTo(ComSafeArrayOutArg(aValues));
10474 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10475 flags.detachTo(ComSafeArrayOutArg(aFlags));
10476 return S_OK;
10477#else
10478 ReturnComNotImplemented();
10479#endif
10480}
10481
10482STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10483 IN_BSTR aValue,
10484 ULONG64 aTimestamp,
10485 IN_BSTR aFlags)
10486{
10487 LogFlowThisFunc(("\n"));
10488
10489#ifdef VBOX_WITH_GUEST_PROPS
10490 using namespace guestProp;
10491
10492 CheckComArgStrNotEmptyOrNull(aName);
10493 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10494 return E_POINTER; /* aValue can be NULL to indicate deletion */
10495
10496 try
10497 {
10498 /*
10499 * Convert input up front.
10500 */
10501 Utf8Str utf8Name(aName);
10502 uint32_t fFlags = NILFLAG;
10503 if (aFlags)
10504 {
10505 Utf8Str utf8Flags(aFlags);
10506 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
10507 AssertRCReturn(vrc, E_INVALIDARG);
10508 }
10509
10510 /*
10511 * Now grab the object lock, validate the state and do the update.
10512 */
10513 AutoCaller autoCaller(this);
10514 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10515
10516 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10517
10518 switch (mData->mMachineState)
10519 {
10520 case MachineState_Paused:
10521 case MachineState_Running:
10522 case MachineState_Teleporting:
10523 case MachineState_TeleportingPausedVM:
10524 case MachineState_LiveSnapshotting:
10525 case MachineState_DeletingSnapshotOnline:
10526 case MachineState_DeletingSnapshotPaused:
10527 case MachineState_Saving:
10528 break;
10529
10530 default:
10531 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10532 VBOX_E_INVALID_VM_STATE);
10533 }
10534
10535 setModified(IsModified_MachineData);
10536 mHWData.backup();
10537
10538 /** @todo r=bird: The careful memory handling doesn't work out here because
10539 * the catch block won't undo any damange we've done. So, if push_back throws
10540 * bad_alloc then you've lost the value.
10541 *
10542 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10543 * since values that changes actually bubbles to the end of the list. Using
10544 * something that has an efficient lookup and can tollerate a bit of updates
10545 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10546 * combination of RTStrCache (for sharing names and getting uniqueness into
10547 * the bargain) and hash/tree is another. */
10548 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10549 iter != mHWData->mGuestProperties.end();
10550 ++iter)
10551 if (utf8Name == iter->strName)
10552 {
10553 mHWData->mGuestProperties.erase(iter);
10554 mData->mGuestPropertiesModified = TRUE;
10555 break;
10556 }
10557 if (aValue != NULL)
10558 {
10559 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10560 mHWData->mGuestProperties.push_back(property);
10561 mData->mGuestPropertiesModified = TRUE;
10562 }
10563
10564 /*
10565 * Send a callback notification if appropriate
10566 */
10567 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10568 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
10569 RTSTR_MAX,
10570 utf8Name.c_str(),
10571 RTSTR_MAX, NULL)
10572 )
10573 {
10574 alock.leave();
10575
10576 mParent->onGuestPropertyChange(mData->mUuid,
10577 aName,
10578 aValue,
10579 aFlags);
10580 }
10581 }
10582 catch (...)
10583 {
10584 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10585 }
10586 return S_OK;
10587#else
10588 ReturnComNotImplemented();
10589#endif
10590}
10591
10592// public methods only for internal purposes
10593/////////////////////////////////////////////////////////////////////////////
10594
10595/**
10596 * Called from the client watcher thread to check for expected or unexpected
10597 * death of the client process that has a direct session to this machine.
10598 *
10599 * On Win32 and on OS/2, this method is called only when we've got the
10600 * mutex (i.e. the client has either died or terminated normally) so it always
10601 * returns @c true (the client is terminated, the session machine is
10602 * uninitialized).
10603 *
10604 * On other platforms, the method returns @c true if the client process has
10605 * terminated normally or abnormally and the session machine was uninitialized,
10606 * and @c false if the client process is still alive.
10607 *
10608 * @note Locks this object for writing.
10609 */
10610bool SessionMachine::checkForDeath()
10611{
10612 Uninit::Reason reason;
10613 bool terminated = false;
10614
10615 /* Enclose autoCaller with a block because calling uninit() from under it
10616 * will deadlock. */
10617 {
10618 AutoCaller autoCaller(this);
10619 if (!autoCaller.isOk())
10620 {
10621 /* return true if not ready, to cause the client watcher to exclude
10622 * the corresponding session from watching */
10623 LogFlowThisFunc(("Already uninitialized!\n"));
10624 return true;
10625 }
10626
10627 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10628
10629 /* Determine the reason of death: if the session state is Closing here,
10630 * everything is fine. Otherwise it means that the client did not call
10631 * OnSessionEnd() before it released the IPC semaphore. This may happen
10632 * either because the client process has abnormally terminated, or
10633 * because it simply forgot to call ISession::Close() before exiting. We
10634 * threat the latter also as an abnormal termination (see
10635 * Session::uninit() for details). */
10636 reason = mData->mSession.mState == SessionState_Unlocking ?
10637 Uninit::Normal :
10638 Uninit::Abnormal;
10639
10640#if defined(RT_OS_WINDOWS)
10641
10642 AssertMsg(mIPCSem, ("semaphore must be created"));
10643
10644 /* release the IPC mutex */
10645 ::ReleaseMutex(mIPCSem);
10646
10647 terminated = true;
10648
10649#elif defined(RT_OS_OS2)
10650
10651 AssertMsg(mIPCSem, ("semaphore must be created"));
10652
10653 /* release the IPC mutex */
10654 ::DosReleaseMutexSem(mIPCSem);
10655
10656 terminated = true;
10657
10658#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10659
10660 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10661
10662 int val = ::semctl(mIPCSem, 0, GETVAL);
10663 if (val > 0)
10664 {
10665 /* the semaphore is signaled, meaning the session is terminated */
10666 terminated = true;
10667 }
10668
10669#else
10670# error "Port me!"
10671#endif
10672
10673 } /* AutoCaller block */
10674
10675 if (terminated)
10676 uninit(reason);
10677
10678 return terminated;
10679}
10680
10681/**
10682 * @note Locks this object for reading.
10683 */
10684HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10685{
10686 LogFlowThisFunc(("\n"));
10687
10688 AutoCaller autoCaller(this);
10689 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10690
10691 ComPtr<IInternalSessionControl> directControl;
10692 {
10693 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10694 directControl = mData->mSession.mDirectControl;
10695 }
10696
10697 /* ignore notifications sent after #OnSessionEnd() is called */
10698 if (!directControl)
10699 return S_OK;
10700
10701 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10702}
10703
10704/**
10705 * @note Locks this object for reading.
10706 */
10707HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10708{
10709 LogFlowThisFunc(("\n"));
10710
10711 AutoCaller autoCaller(this);
10712 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10713
10714 ComPtr<IInternalSessionControl> directControl;
10715 {
10716 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10717 directControl = mData->mSession.mDirectControl;
10718 }
10719
10720 /* ignore notifications sent after #OnSessionEnd() is called */
10721 if (!directControl)
10722 return S_OK;
10723
10724 return directControl->OnSerialPortChange(serialPort);
10725}
10726
10727/**
10728 * @note Locks this object for reading.
10729 */
10730HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10731{
10732 LogFlowThisFunc(("\n"));
10733
10734 AutoCaller autoCaller(this);
10735 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10736
10737 ComPtr<IInternalSessionControl> directControl;
10738 {
10739 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10740 directControl = mData->mSession.mDirectControl;
10741 }
10742
10743 /* ignore notifications sent after #OnSessionEnd() is called */
10744 if (!directControl)
10745 return S_OK;
10746
10747 return directControl->OnParallelPortChange(parallelPort);
10748}
10749
10750/**
10751 * @note Locks this object for reading.
10752 */
10753HRESULT SessionMachine::onStorageControllerChange()
10754{
10755 LogFlowThisFunc(("\n"));
10756
10757 AutoCaller autoCaller(this);
10758 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10759
10760 ComPtr<IInternalSessionControl> directControl;
10761 {
10762 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10763 directControl = mData->mSession.mDirectControl;
10764 }
10765
10766 /* ignore notifications sent after #OnSessionEnd() is called */
10767 if (!directControl)
10768 return S_OK;
10769
10770 return directControl->OnStorageControllerChange();
10771}
10772
10773/**
10774 * @note Locks this object for reading.
10775 */
10776HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10777{
10778 LogFlowThisFunc(("\n"));
10779
10780 AutoCaller autoCaller(this);
10781 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10782
10783 ComPtr<IInternalSessionControl> directControl;
10784 {
10785 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10786 directControl = mData->mSession.mDirectControl;
10787 }
10788
10789 /* ignore notifications sent after #OnSessionEnd() is called */
10790 if (!directControl)
10791 return S_OK;
10792
10793 return directControl->OnMediumChange(aAttachment, aForce);
10794}
10795
10796/**
10797 * @note Locks this object for reading.
10798 */
10799HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
10800{
10801 LogFlowThisFunc(("\n"));
10802
10803 AutoCaller autoCaller(this);
10804 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10805
10806 ComPtr<IInternalSessionControl> directControl;
10807 {
10808 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10809 directControl = mData->mSession.mDirectControl;
10810 }
10811
10812 /* ignore notifications sent after #OnSessionEnd() is called */
10813 if (!directControl)
10814 return S_OK;
10815
10816 return directControl->OnCPUChange(aCPU, aRemove);
10817}
10818
10819HRESULT SessionMachine::onCPUPriorityChange(ULONG aCpuPriority)
10820{
10821 LogFlowThisFunc(("\n"));
10822
10823 AutoCaller autoCaller(this);
10824 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10825
10826 ComPtr<IInternalSessionControl> directControl;
10827 {
10828 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10829 directControl = mData->mSession.mDirectControl;
10830 }
10831
10832 /* ignore notifications sent after #OnSessionEnd() is called */
10833 if (!directControl)
10834 return S_OK;
10835
10836 return directControl->OnCPUPriorityChange(aCpuPriority);
10837}
10838
10839/**
10840 * @note Locks this object for reading.
10841 */
10842HRESULT SessionMachine::onVRDPServerChange(BOOL aRestart)
10843{
10844 LogFlowThisFunc(("\n"));
10845
10846 AutoCaller autoCaller(this);
10847 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10848
10849 ComPtr<IInternalSessionControl> directControl;
10850 {
10851 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10852 directControl = mData->mSession.mDirectControl;
10853 }
10854
10855 /* ignore notifications sent after #OnSessionEnd() is called */
10856 if (!directControl)
10857 return S_OK;
10858
10859 return directControl->OnVRDPServerChange(aRestart);
10860}
10861
10862/**
10863 * @note Locks this object for reading.
10864 */
10865HRESULT SessionMachine::onUSBControllerChange()
10866{
10867 LogFlowThisFunc(("\n"));
10868
10869 AutoCaller autoCaller(this);
10870 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10871
10872 ComPtr<IInternalSessionControl> directControl;
10873 {
10874 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10875 directControl = mData->mSession.mDirectControl;
10876 }
10877
10878 /* ignore notifications sent after #OnSessionEnd() is called */
10879 if (!directControl)
10880 return S_OK;
10881
10882 return directControl->OnUSBControllerChange();
10883}
10884
10885/**
10886 * @note Locks this object for reading.
10887 */
10888HRESULT SessionMachine::onSharedFolderChange()
10889{
10890 LogFlowThisFunc(("\n"));
10891
10892 AutoCaller autoCaller(this);
10893 AssertComRCReturnRC(autoCaller.rc());
10894
10895 ComPtr<IInternalSessionControl> directControl;
10896 {
10897 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10898 directControl = mData->mSession.mDirectControl;
10899 }
10900
10901 /* ignore notifications sent after #OnSessionEnd() is called */
10902 if (!directControl)
10903 return S_OK;
10904
10905 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
10906}
10907
10908/**
10909 * Returns @c true if this machine's USB controller reports it has a matching
10910 * filter for the given USB device and @c false otherwise.
10911 *
10912 * @note Caller must have requested machine read lock.
10913 */
10914bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
10915{
10916 AutoCaller autoCaller(this);
10917 /* silently return if not ready -- this method may be called after the
10918 * direct machine session has been called */
10919 if (!autoCaller.isOk())
10920 return false;
10921
10922
10923#ifdef VBOX_WITH_USB
10924 switch (mData->mMachineState)
10925 {
10926 case MachineState_Starting:
10927 case MachineState_Restoring:
10928 case MachineState_TeleportingIn:
10929 case MachineState_Paused:
10930 case MachineState_Running:
10931 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
10932 * elsewhere... */
10933 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
10934 default: break;
10935 }
10936#else
10937 NOREF(aDevice);
10938 NOREF(aMaskedIfs);
10939#endif
10940 return false;
10941}
10942
10943/**
10944 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10945 */
10946HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
10947 IVirtualBoxErrorInfo *aError,
10948 ULONG aMaskedIfs)
10949{
10950 LogFlowThisFunc(("\n"));
10951
10952 AutoCaller autoCaller(this);
10953
10954 /* This notification may happen after the machine object has been
10955 * uninitialized (the session was closed), so don't assert. */
10956 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10957
10958 ComPtr<IInternalSessionControl> directControl;
10959 {
10960 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10961 directControl = mData->mSession.mDirectControl;
10962 }
10963
10964 /* fail on notifications sent after #OnSessionEnd() is called, it is
10965 * expected by the caller */
10966 if (!directControl)
10967 return E_FAIL;
10968
10969 /* No locks should be held at this point. */
10970 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10971 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10972
10973 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
10974}
10975
10976/**
10977 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10978 */
10979HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
10980 IVirtualBoxErrorInfo *aError)
10981{
10982 LogFlowThisFunc(("\n"));
10983
10984 AutoCaller autoCaller(this);
10985
10986 /* This notification may happen after the machine object has been
10987 * uninitialized (the session was closed), so don't assert. */
10988 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10989
10990 ComPtr<IInternalSessionControl> directControl;
10991 {
10992 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10993 directControl = mData->mSession.mDirectControl;
10994 }
10995
10996 /* fail on notifications sent after #OnSessionEnd() is called, it is
10997 * expected by the caller */
10998 if (!directControl)
10999 return E_FAIL;
11000
11001 /* No locks should be held at this point. */
11002 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11003 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11004
11005 return directControl->OnUSBDeviceDetach(aId, aError);
11006}
11007
11008// protected methods
11009/////////////////////////////////////////////////////////////////////////////
11010
11011/**
11012 * Helper method to finalize saving the state.
11013 *
11014 * @note Must be called from under this object's lock.
11015 *
11016 * @param aSuccess TRUE if the snapshot has been taken successfully
11017 *
11018 * @note Locks mParent + this objects for writing.
11019 */
11020HRESULT SessionMachine::endSavingState(BOOL aSuccess)
11021{
11022 LogFlowThisFuncEnter();
11023
11024 AutoCaller autoCaller(this);
11025 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11026
11027 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11028
11029 HRESULT rc = S_OK;
11030
11031 if (aSuccess)
11032 {
11033 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11034
11035 /* save all VM settings */
11036 rc = saveSettings(NULL);
11037 // no need to check whether VirtualBox.xml needs saving also since
11038 // we can't have a name change pending at this point
11039 }
11040 else
11041 {
11042 /* delete the saved state file (it might have been already created) */
11043 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11044 }
11045
11046 /* remove the completed progress object */
11047 mParent->removeProgress(mSnapshotData.mProgressId);
11048
11049 /* clear out the temporary saved state data */
11050 mSnapshotData.mLastState = MachineState_Null;
11051 mSnapshotData.mProgressId.clear();
11052 mSnapshotData.mStateFilePath.setNull();
11053
11054 LogFlowThisFuncLeave();
11055 return rc;
11056}
11057
11058/**
11059 * Locks the attached media.
11060 *
11061 * All attached hard disks are locked for writing and DVD/floppy are locked for
11062 * reading. Parents of attached hard disks (if any) are locked for reading.
11063 *
11064 * This method also performs accessibility check of all media it locks: if some
11065 * media is inaccessible, the method will return a failure and a bunch of
11066 * extended error info objects per each inaccessible medium.
11067 *
11068 * Note that this method is atomic: if it returns a success, all media are
11069 * locked as described above; on failure no media is locked at all (all
11070 * succeeded individual locks will be undone).
11071 *
11072 * This method is intended to be called when the machine is in Starting or
11073 * Restoring state and asserts otherwise.
11074 *
11075 * The locks made by this method must be undone by calling #unlockMedia() when
11076 * no more needed.
11077 */
11078HRESULT SessionMachine::lockMedia()
11079{
11080 AutoCaller autoCaller(this);
11081 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11082
11083 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11084
11085 AssertReturn( mData->mMachineState == MachineState_Starting
11086 || mData->mMachineState == MachineState_Restoring
11087 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11088 /* bail out if trying to lock things with already set up locking */
11089 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11090
11091 MultiResult mrc(S_OK);
11092
11093 /* Collect locking information for all medium objects attached to the VM. */
11094 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11095 it != mMediaData->mAttachments.end();
11096 ++it)
11097 {
11098 MediumAttachment* pAtt = *it;
11099 DeviceType_T devType = pAtt->getType();
11100 Medium *pMedium = pAtt->getMedium();
11101
11102 MediumLockList *pMediumLockList(new MediumLockList());
11103 // There can be attachments without a medium (floppy/dvd), and thus
11104 // it's impossible to create a medium lock list. It still makes sense
11105 // to have the empty medium lock list in the map in case a medium is
11106 // attached later.
11107 if (pMedium != NULL)
11108 {
11109 MediumType_T mediumType = pMedium->getType();
11110 bool fIsReadOnlyImage = devType == DeviceType_DVD
11111 || mediumType == MediumType_Shareable;
11112 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11113
11114 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11115 !fIsReadOnlyImage /* fMediumLockWrite */,
11116 NULL,
11117 *pMediumLockList);
11118 if (FAILED(mrc))
11119 {
11120 delete pMediumLockList;
11121 mData->mSession.mLockedMedia.Clear();
11122 break;
11123 }
11124 }
11125
11126 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11127 if (FAILED(rc))
11128 {
11129 mData->mSession.mLockedMedia.Clear();
11130 mrc = setError(rc,
11131 tr("Collecting locking information for all attached media failed"));
11132 break;
11133 }
11134 }
11135
11136 if (SUCCEEDED(mrc))
11137 {
11138 /* Now lock all media. If this fails, nothing is locked. */
11139 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11140 if (FAILED(rc))
11141 {
11142 mrc = setError(rc,
11143 tr("Locking of attached media failed"));
11144 }
11145 }
11146
11147 return mrc;
11148}
11149
11150/**
11151 * Undoes the locks made by by #lockMedia().
11152 */
11153void SessionMachine::unlockMedia()
11154{
11155 AutoCaller autoCaller(this);
11156 AssertComRCReturnVoid(autoCaller.rc());
11157
11158 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11159
11160 /* we may be holding important error info on the current thread;
11161 * preserve it */
11162 ErrorInfoKeeper eik;
11163
11164 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11165 AssertComRC(rc);
11166}
11167
11168/**
11169 * Helper to change the machine state (reimplementation).
11170 *
11171 * @note Locks this object for writing.
11172 */
11173HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11174{
11175 LogFlowThisFuncEnter();
11176 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11177
11178 AutoCaller autoCaller(this);
11179 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11180
11181 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11182
11183 MachineState_T oldMachineState = mData->mMachineState;
11184
11185 AssertMsgReturn(oldMachineState != aMachineState,
11186 ("oldMachineState=%s, aMachineState=%s\n",
11187 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11188 E_FAIL);
11189
11190 HRESULT rc = S_OK;
11191
11192 int stsFlags = 0;
11193 bool deleteSavedState = false;
11194
11195 /* detect some state transitions */
11196
11197 if ( ( oldMachineState == MachineState_Saved
11198 && aMachineState == MachineState_Restoring)
11199 || ( ( oldMachineState == MachineState_PoweredOff
11200 || oldMachineState == MachineState_Teleported
11201 || oldMachineState == MachineState_Aborted
11202 )
11203 && ( aMachineState == MachineState_TeleportingIn
11204 || aMachineState == MachineState_Starting
11205 )
11206 )
11207 )
11208 {
11209 /* The EMT thread is about to start */
11210
11211 /* Nothing to do here for now... */
11212
11213 /// @todo NEWMEDIA don't let mDVDDrive and other children
11214 /// change anything when in the Starting/Restoring state
11215 }
11216 else if ( ( oldMachineState == MachineState_Running
11217 || oldMachineState == MachineState_Paused
11218 || oldMachineState == MachineState_Teleporting
11219 || oldMachineState == MachineState_LiveSnapshotting
11220 || oldMachineState == MachineState_Stuck
11221 || oldMachineState == MachineState_Starting
11222 || oldMachineState == MachineState_Stopping
11223 || oldMachineState == MachineState_Saving
11224 || oldMachineState == MachineState_Restoring
11225 || oldMachineState == MachineState_TeleportingPausedVM
11226 || oldMachineState == MachineState_TeleportingIn
11227 )
11228 && ( aMachineState == MachineState_PoweredOff
11229 || aMachineState == MachineState_Saved
11230 || aMachineState == MachineState_Teleported
11231 || aMachineState == MachineState_Aborted
11232 )
11233 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11234 * snapshot */
11235 && ( mSnapshotData.mSnapshot.isNull()
11236 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11237 )
11238 )
11239 {
11240 /* The EMT thread has just stopped, unlock attached media. Note that as
11241 * opposed to locking that is done from Console, we do unlocking here
11242 * because the VM process may have aborted before having a chance to
11243 * properly unlock all media it locked. */
11244
11245 unlockMedia();
11246 }
11247
11248 if (oldMachineState == MachineState_Restoring)
11249 {
11250 if (aMachineState != MachineState_Saved)
11251 {
11252 /*
11253 * delete the saved state file once the machine has finished
11254 * restoring from it (note that Console sets the state from
11255 * Restoring to Saved if the VM couldn't restore successfully,
11256 * to give the user an ability to fix an error and retry --
11257 * we keep the saved state file in this case)
11258 */
11259 deleteSavedState = true;
11260 }
11261 }
11262 else if ( oldMachineState == MachineState_Saved
11263 && ( aMachineState == MachineState_PoweredOff
11264 || aMachineState == MachineState_Aborted
11265 || aMachineState == MachineState_Teleported
11266 )
11267 )
11268 {
11269 /*
11270 * delete the saved state after Console::ForgetSavedState() is called
11271 * or if the VM process (owning a direct VM session) crashed while the
11272 * VM was Saved
11273 */
11274
11275 /// @todo (dmik)
11276 // Not sure that deleting the saved state file just because of the
11277 // client death before it attempted to restore the VM is a good
11278 // thing. But when it crashes we need to go to the Aborted state
11279 // which cannot have the saved state file associated... The only
11280 // way to fix this is to make the Aborted condition not a VM state
11281 // but a bool flag: i.e., when a crash occurs, set it to true and
11282 // change the state to PoweredOff or Saved depending on the
11283 // saved state presence.
11284
11285 deleteSavedState = true;
11286 mData->mCurrentStateModified = TRUE;
11287 stsFlags |= SaveSTS_CurStateModified;
11288 }
11289
11290 if ( aMachineState == MachineState_Starting
11291 || aMachineState == MachineState_Restoring
11292 || aMachineState == MachineState_TeleportingIn
11293 )
11294 {
11295 /* set the current state modified flag to indicate that the current
11296 * state is no more identical to the state in the
11297 * current snapshot */
11298 if (!mData->mCurrentSnapshot.isNull())
11299 {
11300 mData->mCurrentStateModified = TRUE;
11301 stsFlags |= SaveSTS_CurStateModified;
11302 }
11303 }
11304
11305 if (deleteSavedState)
11306 {
11307 if (mRemoveSavedState)
11308 {
11309 Assert(!mSSData->mStateFilePath.isEmpty());
11310 RTFileDelete(mSSData->mStateFilePath.c_str());
11311 }
11312 mSSData->mStateFilePath.setNull();
11313 stsFlags |= SaveSTS_StateFilePath;
11314 }
11315
11316 /* redirect to the underlying peer machine */
11317 mPeer->setMachineState(aMachineState);
11318
11319 if ( aMachineState == MachineState_PoweredOff
11320 || aMachineState == MachineState_Teleported
11321 || aMachineState == MachineState_Aborted
11322 || aMachineState == MachineState_Saved)
11323 {
11324 /* the machine has stopped execution
11325 * (or the saved state file was adopted) */
11326 stsFlags |= SaveSTS_StateTimeStamp;
11327 }
11328
11329 if ( ( oldMachineState == MachineState_PoweredOff
11330 || oldMachineState == MachineState_Aborted
11331 || oldMachineState == MachineState_Teleported
11332 )
11333 && aMachineState == MachineState_Saved)
11334 {
11335 /* the saved state file was adopted */
11336 Assert(!mSSData->mStateFilePath.isEmpty());
11337 stsFlags |= SaveSTS_StateFilePath;
11338 }
11339
11340 if ( aMachineState == MachineState_PoweredOff
11341 || aMachineState == MachineState_Aborted
11342 || aMachineState == MachineState_Teleported)
11343 {
11344 /* Make sure any transient guest properties get removed from the
11345 * property store on shutdown. */
11346
11347 HWData::GuestPropertyList::iterator it;
11348 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11349 if (!fNeedsSaving)
11350 for (it = mHWData->mGuestProperties.begin();
11351 it != mHWData->mGuestProperties.end(); ++it)
11352 if (it->mFlags & guestProp::TRANSIENT)
11353 {
11354 fNeedsSaving = true;
11355 break;
11356 }
11357 if (fNeedsSaving)
11358 {
11359 mData->mCurrentStateModified = TRUE;
11360 stsFlags |= SaveSTS_CurStateModified;
11361 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11362 }
11363 }
11364
11365 rc = saveStateSettings(stsFlags);
11366
11367 if ( ( oldMachineState != MachineState_PoweredOff
11368 && oldMachineState != MachineState_Aborted
11369 && oldMachineState != MachineState_Teleported
11370 )
11371 && ( aMachineState == MachineState_PoweredOff
11372 || aMachineState == MachineState_Aborted
11373 || aMachineState == MachineState_Teleported
11374 )
11375 )
11376 {
11377 /* we've been shut down for any reason */
11378 /* no special action so far */
11379 }
11380
11381 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11382 LogFlowThisFuncLeave();
11383 return rc;
11384}
11385
11386/**
11387 * Sends the current machine state value to the VM process.
11388 *
11389 * @note Locks this object for reading, then calls a client process.
11390 */
11391HRESULT SessionMachine::updateMachineStateOnClient()
11392{
11393 AutoCaller autoCaller(this);
11394 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11395
11396 ComPtr<IInternalSessionControl> directControl;
11397 {
11398 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11399 AssertReturn(!!mData, E_FAIL);
11400 directControl = mData->mSession.mDirectControl;
11401
11402 /* directControl may be already set to NULL here in #OnSessionEnd()
11403 * called too early by the direct session process while there is still
11404 * some operation (like deleting the snapshot) in progress. The client
11405 * process in this case is waiting inside Session::close() for the
11406 * "end session" process object to complete, while #uninit() called by
11407 * #checkForDeath() on the Watcher thread is waiting for the pending
11408 * operation to complete. For now, we accept this inconsitent behavior
11409 * and simply do nothing here. */
11410
11411 if (mData->mSession.mState == SessionState_Unlocking)
11412 return S_OK;
11413
11414 AssertReturn(!directControl.isNull(), E_FAIL);
11415 }
11416
11417 return directControl->UpdateMachineState(mData->mMachineState);
11418}
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