VirtualBox

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

Last change on this file since 33708 was 33708, checked in by vboxsync, 15 years ago

Main: Eliminate the last bits of VirtualBoxBaseWithChildrenNEXT. It won't be missed.

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

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