VirtualBox

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

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

Main: Change the 'default default' machine folder to '/home/umoeller/VirtualBox VMs'

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 382.0 KB
Line 
1/* $Id: MachineImpl.cpp 33596 2010-10-29 10:47:07Z vboxsync $ */
2/** @file
3 * Implementation of IMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/* Make sure all the stdint.h macros are included - must come first! */
19#ifndef __STDC_LIMIT_MACROS
20# define __STDC_LIMIT_MACROS
21#endif
22#ifndef __STDC_CONSTANT_MACROS
23# define __STDC_CONSTANT_MACROS
24#endif
25
26#ifdef VBOX_WITH_SYS_V_IPC_SESSION_WATCHER
27# include <errno.h>
28# include <sys/types.h>
29# include <sys/stat.h>
30# include <sys/ipc.h>
31# include <sys/sem.h>
32#endif
33
34#include "Logging.h"
35#include "VirtualBoxImpl.h"
36#include "MachineImpl.h"
37#include "ProgressImpl.h"
38#include "ProgressProxyImpl.h"
39#include "MediumAttachmentImpl.h"
40#include "MediumImpl.h"
41#include "MediumLock.h"
42#include "USBControllerImpl.h"
43#include "HostImpl.h"
44#include "SharedFolderImpl.h"
45#include "GuestOSTypeImpl.h"
46#include "VirtualBoxErrorInfoImpl.h"
47#include "GuestImpl.h"
48#include "StorageControllerImpl.h"
49#include "DisplayImpl.h"
50#include "DisplayUtils.h"
51
52#ifdef VBOX_WITH_USB
53# include "USBProxyService.h"
54#endif
55
56#include "AutoCaller.h"
57#include "Performance.h"
58
59#include <iprt/asm.h>
60#include <iprt/path.h>
61#include <iprt/dir.h>
62#include <iprt/env.h>
63#include <iprt/lockvalidator.h>
64#include <iprt/process.h>
65#include <iprt/cpp/utils.h>
66#include <iprt/cpp/xml.h> /* xml::XmlFileWriter::s_psz*Suff. */
67#include <iprt/string.h>
68
69#include <VBox/com/array.h>
70
71#include <VBox/err.h>
72#include <VBox/param.h>
73#include <VBox/settings.h>
74#include <VBox/ssm.h>
75
76#ifdef VBOX_WITH_GUEST_PROPS
77# include <VBox/HostServices/GuestPropertySvc.h>
78# include <VBox/com/array.h>
79#endif
80
81#include "VBox/com/MultiResult.h"
82
83#include <algorithm>
84
85#include <typeinfo>
86
87#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
88# define HOSTSUFF_EXE ".exe"
89#else /* !RT_OS_WINDOWS */
90# define HOSTSUFF_EXE ""
91#endif /* !RT_OS_WINDOWS */
92
93// defines / prototypes
94/////////////////////////////////////////////////////////////////////////////
95
96/////////////////////////////////////////////////////////////////////////////
97// Machine::Data structure
98/////////////////////////////////////////////////////////////////////////////
99
100Machine::Data::Data()
101{
102 mRegistered = FALSE;
103 pMachineConfigFile = NULL;
104 flModifications = 0;
105 mAccessible = FALSE;
106 /* mUuid is initialized in Machine::init() */
107
108 mMachineState = MachineState_PoweredOff;
109 RTTimeNow(&mLastStateChange);
110
111 mMachineStateDeps = 0;
112 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
113 mMachineStateChangePending = 0;
114
115 mCurrentStateModified = TRUE;
116 mGuestPropertiesModified = FALSE;
117
118 mSession.mPid = NIL_RTPROCESS;
119 mSession.mState = SessionState_Unlocked;
120}
121
122Machine::Data::~Data()
123{
124 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
125 {
126 RTSemEventMultiDestroy(mMachineStateDepsSem);
127 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
128 }
129 if (pMachineConfigFile)
130 {
131 delete pMachineConfigFile;
132 pMachineConfigFile = NULL;
133 }
134}
135
136/////////////////////////////////////////////////////////////////////////////
137// Machine::HWData structure
138/////////////////////////////////////////////////////////////////////////////
139
140Machine::HWData::HWData()
141{
142 /* default values for a newly created machine */
143 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
144 mMemorySize = 128;
145 mCPUCount = 1;
146 mCPUHotPlugEnabled = false;
147 mMemoryBalloonSize = 0;
148 mPageFusionEnabled = false;
149 mVRAMSize = 8;
150 mAccelerate3DEnabled = false;
151 mAccelerate2DVideoEnabled = false;
152 mMonitorCount = 1;
153 mHWVirtExEnabled = true;
154 mHWVirtExNestedPagingEnabled = true;
155#if HC_ARCH_BITS == 64
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 /* uninit all children using addDependentChild()/removeDependentChild()
6582 * in their init()/uninit() methods */
6583 uninitDependentChildren();
6584
6585 /* tell all our other child objects we've been uninitialized */
6586
6587 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6588 {
6589 if (mNetworkAdapters[slot])
6590 {
6591 mNetworkAdapters[slot]->uninit();
6592 unconst(mNetworkAdapters[slot]).setNull();
6593 }
6594 }
6595
6596 if (mUSBController)
6597 {
6598 mUSBController->uninit();
6599 unconst(mUSBController).setNull();
6600 }
6601
6602 if (mAudioAdapter)
6603 {
6604 mAudioAdapter->uninit();
6605 unconst(mAudioAdapter).setNull();
6606 }
6607
6608 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6609 {
6610 if (mParallelPorts[slot])
6611 {
6612 mParallelPorts[slot]->uninit();
6613 unconst(mParallelPorts[slot]).setNull();
6614 }
6615 }
6616
6617 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6618 {
6619 if (mSerialPorts[slot])
6620 {
6621 mSerialPorts[slot]->uninit();
6622 unconst(mSerialPorts[slot]).setNull();
6623 }
6624 }
6625
6626 if (mVRDEServer)
6627 {
6628 mVRDEServer->uninit();
6629 unconst(mVRDEServer).setNull();
6630 }
6631
6632 if (mBIOSSettings)
6633 {
6634 mBIOSSettings->uninit();
6635 unconst(mBIOSSettings).setNull();
6636 }
6637
6638 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6639 * instance is uninitialized; SessionMachine instances refer to real
6640 * Machine hard disks). This is necessary for a clean re-initialization of
6641 * the VM after successfully re-checking the accessibility state. Note
6642 * that in case of normal Machine or SnapshotMachine uninitialization (as
6643 * a result of unregistering or deleting the snapshot), outdated hard
6644 * disk attachments will already be uninitialized and deleted, so this
6645 * code will not affect them. */
6646 if ( !!mMediaData
6647 && (!isSessionMachine())
6648 )
6649 {
6650 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6651 it != mMediaData->mAttachments.end();
6652 ++it)
6653 {
6654 ComObjPtr<Medium> hd = (*it)->getMedium();
6655 if (hd.isNull())
6656 continue;
6657 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6658 AssertComRC(rc);
6659 }
6660 }
6661
6662 if (!isSessionMachine() && !isSnapshotMachine())
6663 {
6664 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6665 if (mData->mFirstSnapshot)
6666 {
6667 // snapshots tree is protected by media write lock; strictly
6668 // this isn't necessary here since we're deleting the entire
6669 // machine, but otherwise we assert in Snapshot::uninit()
6670 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6671 mData->mFirstSnapshot->uninit();
6672 mData->mFirstSnapshot.setNull();
6673 }
6674
6675 mData->mCurrentSnapshot.setNull();
6676 }
6677
6678 /* free data structures (the essential mData structure is not freed here
6679 * since it may be still in use) */
6680 mMediaData.free();
6681 mStorageControllers.free();
6682 mHWData.free();
6683 mUserData.free();
6684 mSSData.free();
6685}
6686
6687/**
6688 * Returns a pointer to the Machine object for this machine that acts like a
6689 * parent for complex machine data objects such as shared folders, etc.
6690 *
6691 * For primary Machine objects and for SnapshotMachine objects, returns this
6692 * object's pointer itself. For SessionMachine objects, returns the peer
6693 * (primary) machine pointer.
6694 */
6695Machine* Machine::getMachine()
6696{
6697 if (isSessionMachine())
6698 return (Machine*)mPeer;
6699 return this;
6700}
6701
6702/**
6703 * Makes sure that there are no machine state dependents. If necessary, waits
6704 * for the number of dependents to drop to zero.
6705 *
6706 * Make sure this method is called from under this object's write lock to
6707 * guarantee that no new dependents may be added when this method returns
6708 * control to the caller.
6709 *
6710 * @note Locks this object for writing. The lock will be released while waiting
6711 * (if necessary).
6712 *
6713 * @warning To be used only in methods that change the machine state!
6714 */
6715void Machine::ensureNoStateDependencies()
6716{
6717 AssertReturnVoid(isWriteLockOnCurrentThread());
6718
6719 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6720
6721 /* Wait for all state dependents if necessary */
6722 if (mData->mMachineStateDeps != 0)
6723 {
6724 /* lazy semaphore creation */
6725 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6726 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6727
6728 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6729 mData->mMachineStateDeps));
6730
6731 ++mData->mMachineStateChangePending;
6732
6733 /* reset the semaphore before waiting, the last dependent will signal
6734 * it */
6735 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6736
6737 alock.leave();
6738
6739 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6740
6741 alock.enter();
6742
6743 -- mData->mMachineStateChangePending;
6744 }
6745}
6746
6747/**
6748 * Changes the machine state and informs callbacks.
6749 *
6750 * This method is not intended to fail so it either returns S_OK or asserts (and
6751 * returns a failure).
6752 *
6753 * @note Locks this object for writing.
6754 */
6755HRESULT Machine::setMachineState(MachineState_T aMachineState)
6756{
6757 LogFlowThisFuncEnter();
6758 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6759
6760 AutoCaller autoCaller(this);
6761 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6762
6763 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6764
6765 /* wait for state dependents to drop to zero */
6766 ensureNoStateDependencies();
6767
6768 if (mData->mMachineState != aMachineState)
6769 {
6770 mData->mMachineState = aMachineState;
6771
6772 RTTimeNow(&mData->mLastStateChange);
6773
6774 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6775 }
6776
6777 LogFlowThisFuncLeave();
6778 return S_OK;
6779}
6780
6781/**
6782 * Searches for a shared folder with the given logical name
6783 * in the collection of shared folders.
6784 *
6785 * @param aName logical name of the shared folder
6786 * @param aSharedFolder where to return the found object
6787 * @param aSetError whether to set the error info if the folder is
6788 * not found
6789 * @return
6790 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6791 *
6792 * @note
6793 * must be called from under the object's lock!
6794 */
6795HRESULT Machine::findSharedFolder(CBSTR aName,
6796 ComObjPtr<SharedFolder> &aSharedFolder,
6797 bool aSetError /* = false */)
6798{
6799 bool found = false;
6800 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6801 !found && it != mHWData->mSharedFolders.end();
6802 ++it)
6803 {
6804 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6805 found = (*it)->getName() == aName;
6806 if (found)
6807 aSharedFolder = *it;
6808 }
6809
6810 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6811
6812 if (aSetError && !found)
6813 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6814
6815 return rc;
6816}
6817
6818/**
6819 * Initializes all machine instance data from the given settings structures
6820 * from XML. The exception is the machine UUID which needs special handling
6821 * depending on the caller's use case, so the caller needs to set that herself.
6822 *
6823 * This gets called in several contexts during machine initialization:
6824 *
6825 * -- When machine XML exists on disk already and needs to be loaded into memory,
6826 * for example, from registeredInit() to load all registered machines on
6827 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
6828 * attached to the machine should be part of some media registry already.
6829 *
6830 * -- During OVF import, when a machine config has been constructed from an
6831 * OVF file. In this case, puuidRegistry is set to the machine UUID to
6832 * ensure that the media listed as attachments in the config (which have
6833 * been imported from the OVF) receive the correct registry ID.
6834 *
6835 * @param config Machine settings from XML.
6836 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
6837 * @return
6838 */
6839HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
6840 const Guid *puuidRegistry)
6841{
6842 // copy name, description, OS type, teleporter, UTC etc.
6843 mUserData->s = config.machineUserData;
6844
6845 // look up the object by Id to check it is valid
6846 ComPtr<IGuestOSType> guestOSType;
6847 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
6848 guestOSType.asOutParam());
6849 if (FAILED(rc)) return rc;
6850
6851 // stateFile (optional)
6852 if (config.strStateFile.isEmpty())
6853 mSSData->mStateFilePath.setNull();
6854 else
6855 {
6856 Utf8Str stateFilePathFull(config.strStateFile);
6857 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6858 if (RT_FAILURE(vrc))
6859 return setError(E_FAIL,
6860 tr("Invalid saved state file path '%s' (%Rrc)"),
6861 config.strStateFile.c_str(),
6862 vrc);
6863 mSSData->mStateFilePath = stateFilePathFull;
6864 }
6865
6866 // snapshot folder needs special processing so set it again
6867 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
6868 if (FAILED(rc)) return rc;
6869
6870 /* currentStateModified (optional, default is true) */
6871 mData->mCurrentStateModified = config.fCurrentStateModified;
6872
6873 mData->mLastStateChange = config.timeLastStateChange;
6874
6875 /*
6876 * note: all mUserData members must be assigned prior this point because
6877 * we need to commit changes in order to let mUserData be shared by all
6878 * snapshot machine instances.
6879 */
6880 mUserData.commitCopy();
6881
6882 // machine registry, if present (must be loaded before snapshots)
6883 if (config.canHaveOwnMediaRegistry())
6884 {
6885 // determine machine folder
6886 Utf8Str strMachineFolder = getSettingsFileFull();
6887 strMachineFolder.stripFilename();
6888 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
6889 config.mediaRegistry,
6890 strMachineFolder);
6891 if (FAILED(rc)) return rc;
6892 }
6893
6894 /* Snapshot node (optional) */
6895 size_t cRootSnapshots;
6896 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6897 {
6898 // there must be only one root snapshot
6899 Assert(cRootSnapshots == 1);
6900
6901 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6902
6903 rc = loadSnapshot(snap,
6904 config.uuidCurrentSnapshot,
6905 NULL); // no parent == first snapshot
6906 if (FAILED(rc)) return rc;
6907 }
6908
6909 // hardware data
6910 rc = loadHardware(config.hardwareMachine);
6911 if (FAILED(rc)) return rc;
6912
6913 // load storage controllers
6914 rc = loadStorageControllers(config.storageMachine,
6915 puuidRegistry,
6916 NULL /* puuidSnapshot */);
6917 if (FAILED(rc)) return rc;
6918
6919 /*
6920 * NOTE: the assignment below must be the last thing to do,
6921 * otherwise it will be not possible to change the settings
6922 * somewhere in the code above because all setters will be
6923 * blocked by checkStateDependency(MutableStateDep).
6924 */
6925
6926 /* set the machine state to Aborted or Saved when appropriate */
6927 if (config.fAborted)
6928 {
6929 Assert(!mSSData->mStateFilePath.isEmpty());
6930 mSSData->mStateFilePath.setNull();
6931
6932 /* no need to use setMachineState() during init() */
6933 mData->mMachineState = MachineState_Aborted;
6934 }
6935 else if (!mSSData->mStateFilePath.isEmpty())
6936 {
6937 /* no need to use setMachineState() during init() */
6938 mData->mMachineState = MachineState_Saved;
6939 }
6940
6941 // after loading settings, we are no longer different from the XML on disk
6942 mData->flModifications = 0;
6943
6944 return S_OK;
6945}
6946
6947/**
6948 * Recursively loads all snapshots starting from the given.
6949 *
6950 * @param aNode <Snapshot> node.
6951 * @param aCurSnapshotId Current snapshot ID from the settings file.
6952 * @param aParentSnapshot Parent snapshot.
6953 */
6954HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6955 const Guid &aCurSnapshotId,
6956 Snapshot *aParentSnapshot)
6957{
6958 AssertReturn(!isSnapshotMachine(), E_FAIL);
6959 AssertReturn(!isSessionMachine(), E_FAIL);
6960
6961 HRESULT rc = S_OK;
6962
6963 Utf8Str strStateFile;
6964 if (!data.strStateFile.isEmpty())
6965 {
6966 /* optional */
6967 strStateFile = data.strStateFile;
6968 int vrc = calculateFullPath(strStateFile, strStateFile);
6969 if (RT_FAILURE(vrc))
6970 return setError(E_FAIL,
6971 tr("Invalid saved state file path '%s' (%Rrc)"),
6972 strStateFile.c_str(),
6973 vrc);
6974 }
6975
6976 /* create a snapshot machine object */
6977 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6978 pSnapshotMachine.createObject();
6979 rc = pSnapshotMachine->init(this,
6980 data.hardware,
6981 data.storage,
6982 data.uuid.ref(),
6983 strStateFile);
6984 if (FAILED(rc)) return rc;
6985
6986 /* create a snapshot object */
6987 ComObjPtr<Snapshot> pSnapshot;
6988 pSnapshot.createObject();
6989 /* initialize the snapshot */
6990 rc = pSnapshot->init(mParent, // VirtualBox object
6991 data.uuid,
6992 data.strName,
6993 data.strDescription,
6994 data.timestamp,
6995 pSnapshotMachine,
6996 aParentSnapshot);
6997 if (FAILED(rc)) return rc;
6998
6999 /* memorize the first snapshot if necessary */
7000 if (!mData->mFirstSnapshot)
7001 mData->mFirstSnapshot = pSnapshot;
7002
7003 /* memorize the current snapshot when appropriate */
7004 if ( !mData->mCurrentSnapshot
7005 && pSnapshot->getId() == aCurSnapshotId
7006 )
7007 mData->mCurrentSnapshot = pSnapshot;
7008
7009 // now create the children
7010 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7011 it != data.llChildSnapshots.end();
7012 ++it)
7013 {
7014 const settings::Snapshot &childData = *it;
7015 // recurse
7016 rc = loadSnapshot(childData,
7017 aCurSnapshotId,
7018 pSnapshot); // parent = the one we created above
7019 if (FAILED(rc)) return rc;
7020 }
7021
7022 return rc;
7023}
7024
7025/**
7026 * @param aNode <Hardware> node.
7027 */
7028HRESULT Machine::loadHardware(const settings::Hardware &data)
7029{
7030 AssertReturn(!isSessionMachine(), E_FAIL);
7031
7032 HRESULT rc = S_OK;
7033
7034 try
7035 {
7036 /* The hardware version attribute (optional). */
7037 mHWData->mHWVersion = data.strVersion;
7038 mHWData->mHardwareUUID = data.uuid;
7039
7040 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7041 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7042 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7043 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7044 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7045 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7046 mHWData->mPAEEnabled = data.fPAE;
7047 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7048
7049 mHWData->mCPUCount = data.cCPUs;
7050 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7051 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7052
7053 // cpu
7054 if (mHWData->mCPUHotPlugEnabled)
7055 {
7056 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7057 it != data.llCpus.end();
7058 ++it)
7059 {
7060 const settings::Cpu &cpu = *it;
7061
7062 mHWData->mCPUAttached[cpu.ulId] = true;
7063 }
7064 }
7065
7066 // cpuid leafs
7067 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7068 it != data.llCpuIdLeafs.end();
7069 ++it)
7070 {
7071 const settings::CpuIdLeaf &leaf = *it;
7072
7073 switch (leaf.ulId)
7074 {
7075 case 0x0:
7076 case 0x1:
7077 case 0x2:
7078 case 0x3:
7079 case 0x4:
7080 case 0x5:
7081 case 0x6:
7082 case 0x7:
7083 case 0x8:
7084 case 0x9:
7085 case 0xA:
7086 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7087 break;
7088
7089 case 0x80000000:
7090 case 0x80000001:
7091 case 0x80000002:
7092 case 0x80000003:
7093 case 0x80000004:
7094 case 0x80000005:
7095 case 0x80000006:
7096 case 0x80000007:
7097 case 0x80000008:
7098 case 0x80000009:
7099 case 0x8000000A:
7100 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7101 break;
7102
7103 default:
7104 /* just ignore */
7105 break;
7106 }
7107 }
7108
7109 mHWData->mMemorySize = data.ulMemorySizeMB;
7110 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7111
7112 // boot order
7113 for (size_t i = 0;
7114 i < RT_ELEMENTS(mHWData->mBootOrder);
7115 i++)
7116 {
7117 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7118 if (it == data.mapBootOrder.end())
7119 mHWData->mBootOrder[i] = DeviceType_Null;
7120 else
7121 mHWData->mBootOrder[i] = it->second;
7122 }
7123
7124 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7125 mHWData->mMonitorCount = data.cMonitors;
7126 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7127 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7128 mHWData->mFirmwareType = data.firmwareType;
7129 mHWData->mPointingHidType = data.pointingHidType;
7130 mHWData->mKeyboardHidType = data.keyboardHidType;
7131 mHWData->mChipsetType = data.chipsetType;
7132 mHWData->mHpetEnabled = data.fHpetEnabled;
7133
7134 /* VRDEServer */
7135 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7136 if (FAILED(rc)) return rc;
7137
7138 /* BIOS */
7139 rc = mBIOSSettings->loadSettings(data.biosSettings);
7140 if (FAILED(rc)) return rc;
7141
7142 /* USB Controller */
7143 rc = mUSBController->loadSettings(data.usbController);
7144 if (FAILED(rc)) return rc;
7145
7146 // network adapters
7147 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7148 it != data.llNetworkAdapters.end();
7149 ++it)
7150 {
7151 const settings::NetworkAdapter &nic = *it;
7152
7153 /* slot unicity is guaranteed by XML Schema */
7154 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7155 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
7156 if (FAILED(rc)) return rc;
7157 }
7158
7159 // serial ports
7160 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7161 it != data.llSerialPorts.end();
7162 ++it)
7163 {
7164 const settings::SerialPort &s = *it;
7165
7166 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7167 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7168 if (FAILED(rc)) return rc;
7169 }
7170
7171 // parallel ports (optional)
7172 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7173 it != data.llParallelPorts.end();
7174 ++it)
7175 {
7176 const settings::ParallelPort &p = *it;
7177
7178 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7179 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7180 if (FAILED(rc)) return rc;
7181 }
7182
7183 /* AudioAdapter */
7184 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7185 if (FAILED(rc)) return rc;
7186
7187 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7188 it != data.llSharedFolders.end();
7189 ++it)
7190 {
7191 const settings::SharedFolder &sf = *it;
7192 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7193 Bstr(sf.strHostPath).raw(),
7194 sf.fWritable, sf.fAutoMount);
7195 if (FAILED(rc)) return rc;
7196 }
7197
7198 // Clipboard
7199 mHWData->mClipboardMode = data.clipboardMode;
7200
7201 // guest settings
7202 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7203
7204 // IO settings
7205 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7206 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7207
7208#ifdef VBOX_WITH_GUEST_PROPS
7209 /* Guest properties (optional) */
7210 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7211 it != data.llGuestProperties.end();
7212 ++it)
7213 {
7214 const settings::GuestProperty &prop = *it;
7215 uint32_t fFlags = guestProp::NILFLAG;
7216 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7217 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7218 mHWData->mGuestProperties.push_back(property);
7219 }
7220
7221 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7222#endif /* VBOX_WITH_GUEST_PROPS defined */
7223 }
7224 catch(std::bad_alloc &)
7225 {
7226 return E_OUTOFMEMORY;
7227 }
7228
7229 AssertComRC(rc);
7230 return rc;
7231}
7232
7233/**
7234 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7235 *
7236 * @param data
7237 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7238 * @param puuidSnapshot
7239 * @return
7240 */
7241HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7242 const Guid *puuidRegistry,
7243 const Guid *puuidSnapshot)
7244{
7245 AssertReturn(!isSessionMachine(), E_FAIL);
7246
7247 HRESULT rc = S_OK;
7248
7249 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7250 it != data.llStorageControllers.end();
7251 ++it)
7252 {
7253 const settings::StorageController &ctlData = *it;
7254
7255 ComObjPtr<StorageController> pCtl;
7256 /* Try to find one with the name first. */
7257 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7258 if (SUCCEEDED(rc))
7259 return setError(VBOX_E_OBJECT_IN_USE,
7260 tr("Storage controller named '%s' already exists"),
7261 ctlData.strName.c_str());
7262
7263 pCtl.createObject();
7264 rc = pCtl->init(this,
7265 ctlData.strName,
7266 ctlData.storageBus,
7267 ctlData.ulInstance);
7268 if (FAILED(rc)) return rc;
7269
7270 mStorageControllers->push_back(pCtl);
7271
7272 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7273 if (FAILED(rc)) return rc;
7274
7275 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7276 if (FAILED(rc)) return rc;
7277
7278 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7279 if (FAILED(rc)) return rc;
7280
7281 /* Set IDE emulation settings (only for AHCI controller). */
7282 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7283 {
7284 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7285 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7286 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7287 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7288 )
7289 return rc;
7290 }
7291
7292 /* Load the attached devices now. */
7293 rc = loadStorageDevices(pCtl,
7294 ctlData,
7295 puuidRegistry,
7296 puuidSnapshot);
7297 if (FAILED(rc)) return rc;
7298 }
7299
7300 return S_OK;
7301}
7302
7303/**
7304 * Called from loadStorageControllers for a controller's devices.
7305 *
7306 * @param aStorageController
7307 * @param data
7308 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7309 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7310 * @return
7311 */
7312HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7313 const settings::StorageController &data,
7314 const Guid *puuidRegistry,
7315 const Guid *puuidSnapshot)
7316{
7317 HRESULT rc = S_OK;
7318
7319 /* paranoia: detect duplicate attachments */
7320 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7321 it != data.llAttachedDevices.end();
7322 ++it)
7323 {
7324 const settings::AttachedDevice &ad = *it;
7325
7326 for (settings::AttachedDevicesList::const_iterator it2 = it;
7327 it2 != data.llAttachedDevices.end();
7328 ++it2)
7329 {
7330 if (it == it2)
7331 continue;
7332
7333 const settings::AttachedDevice &ad2 = *it2;
7334
7335 if ( ad.lPort == ad2.lPort
7336 && ad.lDevice == ad2.lDevice)
7337 {
7338 return setError(E_FAIL,
7339 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7340 aStorageController->getName().c_str(),
7341 ad.lPort,
7342 ad.lDevice,
7343 mUserData->s.strName.c_str());
7344 }
7345 }
7346 }
7347
7348 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7349 it != data.llAttachedDevices.end();
7350 ++it)
7351 {
7352 const settings::AttachedDevice &dev = *it;
7353 ComObjPtr<Medium> medium;
7354
7355 switch (dev.deviceType)
7356 {
7357 case DeviceType_Floppy:
7358 case DeviceType_DVD:
7359 rc = mParent->findRemoveableMedium(dev.deviceType, dev.uuid, false /* fRefresh */, medium);
7360 if (FAILED(rc))
7361 return rc;
7362 break;
7363
7364 case DeviceType_HardDisk:
7365 {
7366 /* find a hard disk by UUID */
7367 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7368 if (FAILED(rc))
7369 {
7370 if (isSnapshotMachine())
7371 {
7372 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7373 // so the user knows that the bad disk is in a snapshot somewhere
7374 com::ErrorInfo info;
7375 return setError(E_FAIL,
7376 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7377 puuidSnapshot->raw(),
7378 info.getText().raw());
7379 }
7380 else
7381 return rc;
7382 }
7383
7384 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7385
7386 if (medium->getType() == MediumType_Immutable)
7387 {
7388 if (isSnapshotMachine())
7389 return setError(E_FAIL,
7390 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7391 "of the virtual machine '%s' ('%s')"),
7392 medium->getLocationFull().c_str(),
7393 dev.uuid.raw(),
7394 puuidSnapshot->raw(),
7395 mUserData->s.strName.c_str(),
7396 mData->m_strConfigFileFull.c_str());
7397
7398 return setError(E_FAIL,
7399 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7400 medium->getLocationFull().c_str(),
7401 dev.uuid.raw(),
7402 mUserData->s.strName.c_str(),
7403 mData->m_strConfigFileFull.c_str());
7404 }
7405
7406 if ( !isSnapshotMachine()
7407 && medium->getChildren().size() != 0
7408 )
7409 return setError(E_FAIL,
7410 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7411 "because it has %d differencing child hard disks"),
7412 medium->getLocationFull().c_str(),
7413 dev.uuid.raw(),
7414 mUserData->s.strName.c_str(),
7415 mData->m_strConfigFileFull.c_str(),
7416 medium->getChildren().size());
7417
7418 if (findAttachment(mMediaData->mAttachments,
7419 medium))
7420 return setError(E_FAIL,
7421 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7422 medium->getLocationFull().c_str(),
7423 dev.uuid.raw(),
7424 mUserData->s.strName.c_str(),
7425 mData->m_strConfigFileFull.c_str());
7426
7427 break;
7428 }
7429
7430 default:
7431 return setError(E_FAIL,
7432 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7433 medium->getLocationFull().c_str(),
7434 mUserData->s.strName.c_str(),
7435 mData->m_strConfigFileFull.c_str());
7436 }
7437
7438 if (FAILED(rc))
7439 break;
7440
7441 const Bstr controllerName = aStorageController->getName();
7442 ComObjPtr<MediumAttachment> pAttachment;
7443 pAttachment.createObject();
7444 rc = pAttachment->init(this,
7445 medium,
7446 controllerName,
7447 dev.lPort,
7448 dev.lDevice,
7449 dev.deviceType,
7450 dev.fPassThrough,
7451 dev.ulBandwidthLimit);
7452 if (FAILED(rc)) break;
7453
7454 /* associate the medium with this machine and snapshot */
7455 if (!medium.isNull())
7456 {
7457 if (isSnapshotMachine())
7458 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7459 else
7460 rc = medium->addBackReference(mData->mUuid);
7461
7462 if (puuidRegistry)
7463 // caller wants registry ID to be set on all attached media (OVF import case)
7464 medium->addRegistry(*puuidRegistry,
7465 NULL /* pfNeedsSaveSettings */);
7466 }
7467
7468 if (FAILED(rc))
7469 break;
7470
7471 /* back up mMediaData to let registeredInit() properly rollback on failure
7472 * (= limited accessibility) */
7473 setModified(IsModified_Storage);
7474 mMediaData.backup();
7475 mMediaData->mAttachments.push_back(pAttachment);
7476 }
7477
7478 return rc;
7479}
7480
7481/**
7482 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7483 *
7484 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7485 * @param aSnapshot where to return the found snapshot
7486 * @param aSetError true to set extended error info on failure
7487 */
7488HRESULT Machine::findSnapshotById(const Guid &aId,
7489 ComObjPtr<Snapshot> &aSnapshot,
7490 bool aSetError /* = false */)
7491{
7492 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7493
7494 if (!mData->mFirstSnapshot)
7495 {
7496 if (aSetError)
7497 return setError(E_FAIL, tr("This machine does not have any snapshots"));
7498 return E_FAIL;
7499 }
7500
7501 if (aId.isEmpty())
7502 aSnapshot = mData->mFirstSnapshot;
7503 else
7504 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
7505
7506 if (!aSnapshot)
7507 {
7508 if (aSetError)
7509 return setError(E_FAIL,
7510 tr("Could not find a snapshot with UUID {%s}"),
7511 aId.toString().c_str());
7512 return E_FAIL;
7513 }
7514
7515 return S_OK;
7516}
7517
7518/**
7519 * Returns the snapshot with the given name or fails of no such snapshot.
7520 *
7521 * @param aName snapshot name to find
7522 * @param aSnapshot where to return the found snapshot
7523 * @param aSetError true to set extended error info on failure
7524 */
7525HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
7526 ComObjPtr<Snapshot> &aSnapshot,
7527 bool aSetError /* = false */)
7528{
7529 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
7530
7531 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7532
7533 if (!mData->mFirstSnapshot)
7534 {
7535 if (aSetError)
7536 return setError(VBOX_E_OBJECT_NOT_FOUND,
7537 tr("This machine does not have any snapshots"));
7538 return VBOX_E_OBJECT_NOT_FOUND;
7539 }
7540
7541 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
7542
7543 if (!aSnapshot)
7544 {
7545 if (aSetError)
7546 return setError(VBOX_E_OBJECT_NOT_FOUND,
7547 tr("Could not find a snapshot named '%s'"), strName.c_str());
7548 return VBOX_E_OBJECT_NOT_FOUND;
7549 }
7550
7551 return S_OK;
7552}
7553
7554/**
7555 * Returns a storage controller object with the given name.
7556 *
7557 * @param aName storage controller name to find
7558 * @param aStorageController where to return the found storage controller
7559 * @param aSetError true to set extended error info on failure
7560 */
7561HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7562 ComObjPtr<StorageController> &aStorageController,
7563 bool aSetError /* = false */)
7564{
7565 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7566
7567 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7568 it != mStorageControllers->end();
7569 ++it)
7570 {
7571 if ((*it)->getName() == aName)
7572 {
7573 aStorageController = (*it);
7574 return S_OK;
7575 }
7576 }
7577
7578 if (aSetError)
7579 return setError(VBOX_E_OBJECT_NOT_FOUND,
7580 tr("Could not find a storage controller named '%s'"),
7581 aName.c_str());
7582 return VBOX_E_OBJECT_NOT_FOUND;
7583}
7584
7585HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7586 MediaData::AttachmentList &atts)
7587{
7588 AutoCaller autoCaller(this);
7589 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7590
7591 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7592
7593 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7594 it != mMediaData->mAttachments.end();
7595 ++it)
7596 {
7597 const ComObjPtr<MediumAttachment> &pAtt = *it;
7598
7599 // should never happen, but deal with NULL pointers in the list.
7600 AssertStmt(!pAtt.isNull(), continue);
7601
7602 // getControllerName() needs caller+read lock
7603 AutoCaller autoAttCaller(pAtt);
7604 if (FAILED(autoAttCaller.rc()))
7605 {
7606 atts.clear();
7607 return autoAttCaller.rc();
7608 }
7609 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7610
7611 if (pAtt->getControllerName() == aName)
7612 atts.push_back(pAtt);
7613 }
7614
7615 return S_OK;
7616}
7617
7618/**
7619 * Helper for #saveSettings. Cares about renaming the settings directory and
7620 * file if the machine name was changed and about creating a new settings file
7621 * if this is a new machine.
7622 *
7623 * @note Must be never called directly but only from #saveSettings().
7624 */
7625HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7626{
7627 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7628
7629 HRESULT rc = S_OK;
7630
7631 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7632
7633 /* attempt to rename the settings file if machine name is changed */
7634 if ( mUserData->s.fNameSync
7635 && mUserData.isBackedUp()
7636 && mUserData.backedUpData()->s.strName != mUserData->s.strName
7637 )
7638 {
7639 bool dirRenamed = false;
7640 bool fileRenamed = false;
7641
7642 Utf8Str configFile, newConfigFile;
7643 Utf8Str configDir, newConfigDir;
7644
7645 do
7646 {
7647 int vrc = VINF_SUCCESS;
7648
7649 Utf8Str name = mUserData.backedUpData()->s.strName;
7650 Utf8Str newName = mUserData->s.strName;
7651
7652 configFile = mData->m_strConfigFileFull;
7653
7654 /* first, rename the directory if it matches the machine name */
7655 configDir = configFile;
7656 configDir.stripFilename();
7657 newConfigDir = configDir;
7658 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7659 {
7660 newConfigDir.stripFilename();
7661 newConfigDir.append(RTPATH_DELIMITER);
7662 newConfigDir.append(newName);
7663 /* new dir and old dir cannot be equal here because of 'if'
7664 * above and because name != newName */
7665 Assert(configDir != newConfigDir);
7666 if (!fSettingsFileIsNew)
7667 {
7668 /* perform real rename only if the machine is not new */
7669 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
7670 if (RT_FAILURE(vrc))
7671 {
7672 rc = setError(E_FAIL,
7673 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7674 configDir.c_str(),
7675 newConfigDir.c_str(),
7676 vrc);
7677 break;
7678 }
7679 dirRenamed = true;
7680 }
7681 }
7682
7683 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
7684 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
7685
7686 /* then try to rename the settings file itself */
7687 if (newConfigFile != configFile)
7688 {
7689 /* get the path to old settings file in renamed directory */
7690 configFile = Utf8StrFmt("%s%c%s",
7691 newConfigDir.c_str(),
7692 RTPATH_DELIMITER,
7693 RTPathFilename(configFile.c_str()));
7694 if (!fSettingsFileIsNew)
7695 {
7696 /* perform real rename only if the machine is not new */
7697 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
7698 if (RT_FAILURE(vrc))
7699 {
7700 rc = setError(E_FAIL,
7701 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7702 configFile.c_str(),
7703 newConfigFile.c_str(),
7704 vrc);
7705 break;
7706 }
7707 fileRenamed = true;
7708 }
7709 }
7710
7711 /* update m_strConfigFileFull amd mConfigFile */
7712 mData->m_strConfigFileFull = newConfigFile;
7713 // compute the relative path too
7714 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7715
7716 // store the old and new so that VirtualBox::saveSettings() can update
7717 // the media registry
7718 if ( mData->mRegistered
7719 && configDir != newConfigDir)
7720 {
7721 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7722
7723 if (pfNeedsGlobalSaveSettings)
7724 *pfNeedsGlobalSaveSettings = true;
7725 }
7726
7727 /* update the snapshot folder */
7728 if (RTPathStartsWith(mUserData->m_strSnapshotFolderFull.c_str(),
7729 configDir.c_str()))
7730 {
7731 mUserData->m_strSnapshotFolderFull = Utf8StrFmt("%s%s",
7732 newConfigDir.c_str(),
7733 mUserData->m_strSnapshotFolderFull.c_str() + configDir.length());
7734 copyPathRelativeToMachine(mUserData->m_strSnapshotFolderFull,
7735 mUserData->s.strSnapshotFolder);
7736 }
7737
7738 /* update the saved state file path */
7739 Utf8Str path = mSSData->mStateFilePath;
7740 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7741 mSSData->mStateFilePath = Utf8StrFmt("%s%s",
7742 newConfigDir.c_str(),
7743 path.c_str() + configDir.length());
7744
7745 /* Update saved state file paths of all online snapshots.
7746 * Note that saveSettings() will recognize name change
7747 * and will save all snapshots in this case. */
7748 if (mData->mFirstSnapshot)
7749 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7750 newConfigDir.c_str());
7751 }
7752 while (0);
7753
7754 if (FAILED(rc))
7755 {
7756 /* silently try to rename everything back */
7757 if (fileRenamed)
7758 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
7759 if (dirRenamed)
7760 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
7761 }
7762
7763 if (FAILED(rc)) return rc;
7764 }
7765
7766 if (fSettingsFileIsNew)
7767 {
7768 /* create a virgin config file */
7769 int vrc = VINF_SUCCESS;
7770
7771 /* ensure the settings directory exists */
7772 Utf8Str path(mData->m_strConfigFileFull);
7773 path.stripFilename();
7774 if (!RTDirExists(path.c_str()))
7775 {
7776 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7777 if (RT_FAILURE(vrc))
7778 {
7779 return setError(E_FAIL,
7780 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7781 path.c_str(),
7782 vrc);
7783 }
7784 }
7785
7786 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7787 path = Utf8Str(mData->m_strConfigFileFull);
7788 RTFILE f = NIL_RTFILE;
7789 vrc = RTFileOpen(&f, path.c_str(),
7790 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7791 if (RT_FAILURE(vrc))
7792 return setError(E_FAIL,
7793 tr("Could not create the settings file '%s' (%Rrc)"),
7794 path.c_str(),
7795 vrc);
7796 RTFileClose(f);
7797 }
7798
7799 return rc;
7800}
7801
7802/**
7803 * Saves and commits machine data, user data and hardware data.
7804 *
7805 * Note that on failure, the data remains uncommitted.
7806 *
7807 * @a aFlags may combine the following flags:
7808 *
7809 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7810 * Used when saving settings after an operation that makes them 100%
7811 * correspond to the settings from the current snapshot.
7812 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7813 * #isReallyModified() returns false. This is necessary for cases when we
7814 * change machine data directly, not through the backup()/commit() mechanism.
7815 * - SaveS_Force: settings will be saved without doing a deep compare of the
7816 * settings structures. This is used when this is called because snapshots
7817 * have changed to avoid the overhead of the deep compare.
7818 *
7819 * @note Must be called from under this object's write lock. Locks children for
7820 * writing.
7821 *
7822 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7823 * initialized to false and that will be set to true by this function if
7824 * the caller must invoke VirtualBox::saveSettings() because the global
7825 * settings have changed. This will happen if a machine rename has been
7826 * saved and the global machine and media registries will therefore need
7827 * updating.
7828 */
7829HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7830 int aFlags /*= 0*/)
7831{
7832 LogFlowThisFuncEnter();
7833
7834 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7835
7836 /* make sure child objects are unable to modify the settings while we are
7837 * saving them */
7838 ensureNoStateDependencies();
7839
7840 AssertReturn(!isSnapshotMachine(),
7841 E_FAIL);
7842
7843 HRESULT rc = S_OK;
7844 bool fNeedsWrite = false;
7845
7846 /* First, prepare to save settings. It will care about renaming the
7847 * settings directory and file if the machine name was changed and about
7848 * creating a new settings file if this is a new machine. */
7849 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7850 if (FAILED(rc)) return rc;
7851
7852 // keep a pointer to the current settings structures
7853 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7854 settings::MachineConfigFile *pNewConfig = NULL;
7855
7856 try
7857 {
7858 // make a fresh one to have everyone write stuff into
7859 pNewConfig = new settings::MachineConfigFile(NULL);
7860 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7861
7862 // now go and copy all the settings data from COM to the settings structures
7863 // (this calles saveSettings() on all the COM objects in the machine)
7864 copyMachineDataToSettings(*pNewConfig);
7865
7866 if (aFlags & SaveS_ResetCurStateModified)
7867 {
7868 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7869 mData->mCurrentStateModified = FALSE;
7870 fNeedsWrite = true; // always, no need to compare
7871 }
7872 else if (aFlags & SaveS_Force)
7873 {
7874 fNeedsWrite = true; // always, no need to compare
7875 }
7876 else
7877 {
7878 if (!mData->mCurrentStateModified)
7879 {
7880 // do a deep compare of the settings that we just saved with the settings
7881 // previously stored in the config file; this invokes MachineConfigFile::operator==
7882 // which does a deep compare of all the settings, which is expensive but less expensive
7883 // than writing out XML in vain
7884 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7885
7886 // could still be modified if any settings changed
7887 mData->mCurrentStateModified = fAnySettingsChanged;
7888
7889 fNeedsWrite = fAnySettingsChanged;
7890 }
7891 else
7892 fNeedsWrite = true;
7893 }
7894
7895 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7896
7897 if (fNeedsWrite)
7898 // now spit it all out!
7899 pNewConfig->write(mData->m_strConfigFileFull);
7900
7901 mData->pMachineConfigFile = pNewConfig;
7902 delete pOldConfig;
7903 commit();
7904
7905 // after saving settings, we are no longer different from the XML on disk
7906 mData->flModifications = 0;
7907 }
7908 catch (HRESULT err)
7909 {
7910 // we assume that error info is set by the thrower
7911 rc = err;
7912
7913 // restore old config
7914 delete pNewConfig;
7915 mData->pMachineConfigFile = pOldConfig;
7916 }
7917 catch (...)
7918 {
7919 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7920 }
7921
7922 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7923 {
7924 /* Fire the data change event, even on failure (since we've already
7925 * committed all data). This is done only for SessionMachines because
7926 * mutable Machine instances are always not registered (i.e. private
7927 * to the client process that creates them) and thus don't need to
7928 * inform callbacks. */
7929 if (isSessionMachine())
7930 mParent->onMachineDataChange(mData->mUuid);
7931 }
7932
7933 LogFlowThisFunc(("rc=%08X\n", rc));
7934 LogFlowThisFuncLeave();
7935 return rc;
7936}
7937
7938/**
7939 * Implementation for saving the machine settings into the given
7940 * settings::MachineConfigFile instance. This copies machine extradata
7941 * from the previous machine config file in the instance data, if any.
7942 *
7943 * This gets called from two locations:
7944 *
7945 * -- Machine::saveSettings(), during the regular XML writing;
7946 *
7947 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7948 * exported to OVF and we write the VirtualBox proprietary XML
7949 * into a <vbox:Machine> tag.
7950 *
7951 * This routine fills all the fields in there, including snapshots, *except*
7952 * for the following:
7953 *
7954 * -- fCurrentStateModified. There is some special logic associated with that.
7955 *
7956 * The caller can then call MachineConfigFile::write() or do something else
7957 * with it.
7958 *
7959 * Caller must hold the machine lock!
7960 *
7961 * This throws XML errors and HRESULT, so the caller must have a catch block!
7962 */
7963void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7964{
7965 // deep copy extradata
7966 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7967
7968 config.uuid = mData->mUuid;
7969
7970 // copy name, description, OS type, teleport, UTC etc.
7971 config.machineUserData = mUserData->s;
7972
7973 if ( mData->mMachineState == MachineState_Saved
7974 || mData->mMachineState == MachineState_Restoring
7975 // when deleting a snapshot we may or may not have a saved state in the current state,
7976 // so let's not assert here please
7977 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7978 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7979 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7980 && (!mSSData->mStateFilePath.isEmpty())
7981 )
7982 )
7983 {
7984 Assert(!mSSData->mStateFilePath.isEmpty());
7985 /* try to make the file name relative to the settings file dir */
7986 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
7987 }
7988 else
7989 {
7990 Assert(mSSData->mStateFilePath.isEmpty());
7991 config.strStateFile.setNull();
7992 }
7993
7994 if (mData->mCurrentSnapshot)
7995 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7996 else
7997 config.uuidCurrentSnapshot.clear();
7998
7999 config.timeLastStateChange = mData->mLastStateChange;
8000 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8001 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8002
8003 HRESULT rc = saveHardware(config.hardwareMachine);
8004 if (FAILED(rc)) throw rc;
8005
8006 rc = saveStorageControllers(config.storageMachine);
8007 if (FAILED(rc)) throw rc;
8008
8009 // save machine's media registry if this is VirtualBox 4.0 or later
8010 if (config.canHaveOwnMediaRegistry())
8011 {
8012 // determine machine folder
8013 Utf8Str strMachineFolder = getSettingsFileFull();
8014 strMachineFolder.stripFilename();
8015 mParent->saveMediaRegistry(config.mediaRegistry,
8016 getId(), // only media with registry ID == machine UUID
8017 strMachineFolder);
8018 // this throws HRESULT
8019 }
8020
8021 // save snapshots
8022 rc = saveAllSnapshots(config);
8023 if (FAILED(rc)) throw rc;
8024}
8025
8026/**
8027 * Saves all snapshots of the machine into the given machine config file. Called
8028 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8029 * @param config
8030 * @return
8031 */
8032HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8033{
8034 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8035
8036 HRESULT rc = S_OK;
8037
8038 try
8039 {
8040 config.llFirstSnapshot.clear();
8041
8042 if (mData->mFirstSnapshot)
8043 {
8044 settings::Snapshot snapNew;
8045 config.llFirstSnapshot.push_back(snapNew);
8046
8047 // get reference to the fresh copy of the snapshot on the list and
8048 // work on that copy directly to avoid excessive copying later
8049 settings::Snapshot &snap = config.llFirstSnapshot.front();
8050
8051 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8052 if (FAILED(rc)) throw rc;
8053 }
8054
8055// if (mType == IsSessionMachine)
8056// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8057
8058 }
8059 catch (HRESULT err)
8060 {
8061 /* we assume that error info is set by the thrower */
8062 rc = err;
8063 }
8064 catch (...)
8065 {
8066 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8067 }
8068
8069 return rc;
8070}
8071
8072/**
8073 * Saves the VM hardware configuration. It is assumed that the
8074 * given node is empty.
8075 *
8076 * @param aNode <Hardware> node to save the VM hardware configuration to.
8077 */
8078HRESULT Machine::saveHardware(settings::Hardware &data)
8079{
8080 HRESULT rc = S_OK;
8081
8082 try
8083 {
8084 /* The hardware version attribute (optional).
8085 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8086 if ( mHWData->mHWVersion == "1"
8087 && mSSData->mStateFilePath.isEmpty()
8088 )
8089 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. */
8090
8091 data.strVersion = mHWData->mHWVersion;
8092 data.uuid = mHWData->mHardwareUUID;
8093
8094 // CPU
8095 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8096 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8097 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8098 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8099 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8100 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8101 data.fPAE = !!mHWData->mPAEEnabled;
8102 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8103
8104 /* Standard and Extended CPUID leafs. */
8105 data.llCpuIdLeafs.clear();
8106 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8107 {
8108 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8109 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8110 }
8111 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8112 {
8113 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8114 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8115 }
8116
8117 data.cCPUs = mHWData->mCPUCount;
8118 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8119 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8120
8121 data.llCpus.clear();
8122 if (data.fCpuHotPlug)
8123 {
8124 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8125 {
8126 if (mHWData->mCPUAttached[idx])
8127 {
8128 settings::Cpu cpu;
8129 cpu.ulId = idx;
8130 data.llCpus.push_back(cpu);
8131 }
8132 }
8133 }
8134
8135 // memory
8136 data.ulMemorySizeMB = mHWData->mMemorySize;
8137 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8138
8139 // firmware
8140 data.firmwareType = mHWData->mFirmwareType;
8141
8142 // HID
8143 data.pointingHidType = mHWData->mPointingHidType;
8144 data.keyboardHidType = mHWData->mKeyboardHidType;
8145
8146 // chipset
8147 data.chipsetType = mHWData->mChipsetType;
8148
8149 // HPET
8150 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8151
8152 // boot order
8153 data.mapBootOrder.clear();
8154 for (size_t i = 0;
8155 i < RT_ELEMENTS(mHWData->mBootOrder);
8156 ++i)
8157 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8158
8159 // display
8160 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8161 data.cMonitors = mHWData->mMonitorCount;
8162 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8163 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8164
8165 /* VRDEServer settings (optional) */
8166 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8167 if (FAILED(rc)) throw rc;
8168
8169 /* BIOS (required) */
8170 rc = mBIOSSettings->saveSettings(data.biosSettings);
8171 if (FAILED(rc)) throw rc;
8172
8173 /* USB Controller (required) */
8174 rc = mUSBController->saveSettings(data.usbController);
8175 if (FAILED(rc)) throw rc;
8176
8177 /* Network adapters (required) */
8178 data.llNetworkAdapters.clear();
8179 for (ULONG slot = 0;
8180 slot < RT_ELEMENTS(mNetworkAdapters);
8181 ++slot)
8182 {
8183 settings::NetworkAdapter nic;
8184 nic.ulSlot = slot;
8185 rc = mNetworkAdapters[slot]->saveSettings(nic);
8186 if (FAILED(rc)) throw rc;
8187
8188 data.llNetworkAdapters.push_back(nic);
8189 }
8190
8191 /* Serial ports */
8192 data.llSerialPorts.clear();
8193 for (ULONG slot = 0;
8194 slot < RT_ELEMENTS(mSerialPorts);
8195 ++slot)
8196 {
8197 settings::SerialPort s;
8198 s.ulSlot = slot;
8199 rc = mSerialPorts[slot]->saveSettings(s);
8200 if (FAILED(rc)) return rc;
8201
8202 data.llSerialPorts.push_back(s);
8203 }
8204
8205 /* Parallel ports */
8206 data.llParallelPorts.clear();
8207 for (ULONG slot = 0;
8208 slot < RT_ELEMENTS(mParallelPorts);
8209 ++slot)
8210 {
8211 settings::ParallelPort p;
8212 p.ulSlot = slot;
8213 rc = mParallelPorts[slot]->saveSettings(p);
8214 if (FAILED(rc)) return rc;
8215
8216 data.llParallelPorts.push_back(p);
8217 }
8218
8219 /* Audio adapter */
8220 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8221 if (FAILED(rc)) return rc;
8222
8223 /* Shared folders */
8224 data.llSharedFolders.clear();
8225 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8226 it != mHWData->mSharedFolders.end();
8227 ++it)
8228 {
8229 ComObjPtr<SharedFolder> pFolder = *it;
8230 settings::SharedFolder sf;
8231 sf.strName = pFolder->getName();
8232 sf.strHostPath = pFolder->getHostPath();
8233 sf.fWritable = !!pFolder->isWritable();
8234 sf.fAutoMount = !!pFolder->isAutoMounted();
8235
8236 data.llSharedFolders.push_back(sf);
8237 }
8238
8239 // clipboard
8240 data.clipboardMode = mHWData->mClipboardMode;
8241
8242 /* Guest */
8243 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8244
8245 // IO settings
8246 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8247 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8248
8249 // guest properties
8250 data.llGuestProperties.clear();
8251#ifdef VBOX_WITH_GUEST_PROPS
8252 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8253 it != mHWData->mGuestProperties.end();
8254 ++it)
8255 {
8256 HWData::GuestProperty property = *it;
8257
8258 /* Remove transient guest properties at shutdown unless we
8259 * are saving state */
8260 if ( ( mData->mMachineState == MachineState_PoweredOff
8261 || mData->mMachineState == MachineState_Aborted
8262 || mData->mMachineState == MachineState_Teleported)
8263 && property.mFlags & guestProp::TRANSIENT)
8264 continue;
8265 settings::GuestProperty prop;
8266 prop.strName = property.strName;
8267 prop.strValue = property.strValue;
8268 prop.timestamp = property.mTimestamp;
8269 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8270 guestProp::writeFlags(property.mFlags, szFlags);
8271 prop.strFlags = szFlags;
8272
8273 data.llGuestProperties.push_back(prop);
8274 }
8275
8276 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8277 /* I presume this doesn't require a backup(). */
8278 mData->mGuestPropertiesModified = FALSE;
8279#endif /* VBOX_WITH_GUEST_PROPS defined */
8280 }
8281 catch(std::bad_alloc &)
8282 {
8283 return E_OUTOFMEMORY;
8284 }
8285
8286 AssertComRC(rc);
8287 return rc;
8288}
8289
8290/**
8291 * Saves the storage controller configuration.
8292 *
8293 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8294 */
8295HRESULT Machine::saveStorageControllers(settings::Storage &data)
8296{
8297 data.llStorageControllers.clear();
8298
8299 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8300 it != mStorageControllers->end();
8301 ++it)
8302 {
8303 HRESULT rc;
8304 ComObjPtr<StorageController> pCtl = *it;
8305
8306 settings::StorageController ctl;
8307 ctl.strName = pCtl->getName();
8308 ctl.controllerType = pCtl->getControllerType();
8309 ctl.storageBus = pCtl->getStorageBus();
8310 ctl.ulInstance = pCtl->getInstance();
8311
8312 /* Save the port count. */
8313 ULONG portCount;
8314 rc = pCtl->COMGETTER(PortCount)(&portCount);
8315 ComAssertComRCRet(rc, rc);
8316 ctl.ulPortCount = portCount;
8317
8318 /* Save fUseHostIOCache */
8319 BOOL fUseHostIOCache;
8320 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8321 ComAssertComRCRet(rc, rc);
8322 ctl.fUseHostIOCache = !!fUseHostIOCache;
8323
8324 /* Save IDE emulation settings. */
8325 if (ctl.controllerType == StorageControllerType_IntelAhci)
8326 {
8327 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8328 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8329 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8330 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8331 )
8332 ComAssertComRCRet(rc, rc);
8333 }
8334
8335 /* save the devices now. */
8336 rc = saveStorageDevices(pCtl, ctl);
8337 ComAssertComRCRet(rc, rc);
8338
8339 data.llStorageControllers.push_back(ctl);
8340 }
8341
8342 return S_OK;
8343}
8344
8345/**
8346 * Saves the hard disk configuration.
8347 */
8348HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8349 settings::StorageController &data)
8350{
8351 MediaData::AttachmentList atts;
8352
8353 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8354 if (FAILED(rc)) return rc;
8355
8356 data.llAttachedDevices.clear();
8357 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8358 it != atts.end();
8359 ++it)
8360 {
8361 settings::AttachedDevice dev;
8362
8363 MediumAttachment *pAttach = *it;
8364 Medium *pMedium = pAttach->getMedium();
8365
8366 dev.deviceType = pAttach->getType();
8367 dev.lPort = pAttach->getPort();
8368 dev.lDevice = pAttach->getDevice();
8369 if (pMedium)
8370 {
8371 if (pMedium->isHostDrive())
8372 dev.strHostDriveSrc = pMedium->getLocationFull();
8373 else
8374 dev.uuid = pMedium->getId();
8375 dev.fPassThrough = pAttach->getPassthrough();
8376 }
8377
8378 data.llAttachedDevices.push_back(dev);
8379 }
8380
8381 return S_OK;
8382}
8383
8384/**
8385 * Saves machine state settings as defined by aFlags
8386 * (SaveSTS_* values).
8387 *
8388 * @param aFlags Combination of SaveSTS_* flags.
8389 *
8390 * @note Locks objects for writing.
8391 */
8392HRESULT Machine::saveStateSettings(int aFlags)
8393{
8394 if (aFlags == 0)
8395 return S_OK;
8396
8397 AutoCaller autoCaller(this);
8398 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8399
8400 /* This object's write lock is also necessary to serialize file access
8401 * (prevent concurrent reads and writes) */
8402 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8403
8404 HRESULT rc = S_OK;
8405
8406 Assert(mData->pMachineConfigFile);
8407
8408 try
8409 {
8410 if (aFlags & SaveSTS_CurStateModified)
8411 mData->pMachineConfigFile->fCurrentStateModified = true;
8412
8413 if (aFlags & SaveSTS_StateFilePath)
8414 {
8415 if (!mSSData->mStateFilePath.isEmpty())
8416 /* try to make the file name relative to the settings file dir */
8417 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8418 else
8419 mData->pMachineConfigFile->strStateFile.setNull();
8420 }
8421
8422 if (aFlags & SaveSTS_StateTimeStamp)
8423 {
8424 Assert( mData->mMachineState != MachineState_Aborted
8425 || mSSData->mStateFilePath.isEmpty());
8426
8427 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8428
8429 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8430//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8431 }
8432
8433 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8434 }
8435 catch (...)
8436 {
8437 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8438 }
8439
8440 return rc;
8441}
8442
8443/**
8444 * Creates differencing hard disks for all normal hard disks attached to this
8445 * machine and a new set of attachments to refer to created disks.
8446 *
8447 * Used when taking a snapshot or when deleting the current state. Gets called
8448 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
8449 *
8450 * This method assumes that mMediaData contains the original hard disk attachments
8451 * it needs to create diffs for. On success, these attachments will be replaced
8452 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8453 * called to delete created diffs which will also rollback mMediaData and restore
8454 * whatever was backed up before calling this method.
8455 *
8456 * Attachments with non-normal hard disks are left as is.
8457 *
8458 * If @a aOnline is @c false then the original hard disks that require implicit
8459 * diffs will be locked for reading. Otherwise it is assumed that they are
8460 * already locked for writing (when the VM was started). Note that in the latter
8461 * case it is responsibility of the caller to lock the newly created diffs for
8462 * writing if this method succeeds.
8463 *
8464 * @param aProgress Progress object to run (must contain at least as
8465 * many operations left as the number of hard disks
8466 * attached).
8467 * @param aOnline Whether the VM was online prior to this operation.
8468 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8469 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8470 *
8471 * @note The progress object is not marked as completed, neither on success nor
8472 * on failure. This is a responsibility of the caller.
8473 *
8474 * @note Locks this object for writing.
8475 */
8476HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
8477 ULONG aWeight,
8478 bool aOnline,
8479 bool *pfNeedsSaveSettings)
8480{
8481 LogFlowThisFunc(("aOnline=%d\n", aOnline));
8482
8483 AutoCaller autoCaller(this);
8484 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8485
8486 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8487
8488 /* must be in a protective state because we leave the lock below */
8489 AssertReturn( mData->mMachineState == MachineState_Saving
8490 || mData->mMachineState == MachineState_LiveSnapshotting
8491 || mData->mMachineState == MachineState_RestoringSnapshot
8492 || mData->mMachineState == MachineState_DeletingSnapshot
8493 , E_FAIL);
8494
8495 HRESULT rc = S_OK;
8496
8497 MediumLockListMap lockedMediaOffline;
8498 MediumLockListMap *lockedMediaMap;
8499 if (aOnline)
8500 lockedMediaMap = &mData->mSession.mLockedMedia;
8501 else
8502 lockedMediaMap = &lockedMediaOffline;
8503
8504 try
8505 {
8506 if (!aOnline)
8507 {
8508 /* lock all attached hard disks early to detect "in use"
8509 * situations before creating actual diffs */
8510 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8511 it != mMediaData->mAttachments.end();
8512 ++it)
8513 {
8514 MediumAttachment* pAtt = *it;
8515 if (pAtt->getType() == DeviceType_HardDisk)
8516 {
8517 Medium* pMedium = pAtt->getMedium();
8518 Assert(pMedium);
8519
8520 MediumLockList *pMediumLockList(new MediumLockList());
8521 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8522 false /* fMediumLockWrite */,
8523 NULL,
8524 *pMediumLockList);
8525 if (FAILED(rc))
8526 {
8527 delete pMediumLockList;
8528 throw rc;
8529 }
8530 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8531 if (FAILED(rc))
8532 {
8533 throw setError(rc,
8534 tr("Collecting locking information for all attached media failed"));
8535 }
8536 }
8537 }
8538
8539 /* Now lock all media. If this fails, nothing is locked. */
8540 rc = lockedMediaMap->Lock();
8541 if (FAILED(rc))
8542 {
8543 throw setError(rc,
8544 tr("Locking of attached media failed"));
8545 }
8546 }
8547
8548 /* remember the current list (note that we don't use backup() since
8549 * mMediaData may be already backed up) */
8550 MediaData::AttachmentList atts = mMediaData->mAttachments;
8551
8552 /* start from scratch */
8553 mMediaData->mAttachments.clear();
8554
8555 /* go through remembered attachments and create diffs for normal hard
8556 * disks and attach them */
8557 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8558 it != atts.end();
8559 ++it)
8560 {
8561 MediumAttachment* pAtt = *it;
8562
8563 DeviceType_T devType = pAtt->getType();
8564 Medium* pMedium = pAtt->getMedium();
8565
8566 if ( devType != DeviceType_HardDisk
8567 || pMedium == NULL
8568 || pMedium->getType() != MediumType_Normal)
8569 {
8570 /* copy the attachment as is */
8571
8572 /** @todo the progress object created in Console::TakeSnaphot
8573 * only expects operations for hard disks. Later other
8574 * device types need to show up in the progress as well. */
8575 if (devType == DeviceType_HardDisk)
8576 {
8577 if (pMedium == NULL)
8578 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
8579 aWeight); // weight
8580 else
8581 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8582 pMedium->getBase()->getName().c_str()).raw(),
8583 aWeight); // weight
8584 }
8585
8586 mMediaData->mAttachments.push_back(pAtt);
8587 continue;
8588 }
8589
8590 /* need a diff */
8591 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8592 pMedium->getBase()->getName().c_str()).raw(),
8593 aWeight); // weight
8594
8595 ComObjPtr<Medium> diff;
8596 diff.createObject();
8597 rc = diff->init(mParent,
8598 pMedium->getPreferredDiffFormat(),
8599 Utf8Str(mUserData->m_strSnapshotFolderFull).append(RTPATH_SLASH_STR),
8600 pMedium->getFirstRegistryMachineId(), // store the diff in the same registry as the parent
8601 pfNeedsSaveSettings);
8602 if (FAILED(rc)) throw rc;
8603
8604 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8605 * the push_back? Looks like we're going to leave medium with the
8606 * wrong kind of lock (general issue with if we fail anywhere at all)
8607 * and an orphaned VDI in the snapshots folder. */
8608
8609 /* update the appropriate lock list */
8610 MediumLockList *pMediumLockList;
8611 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8612 AssertComRCThrowRC(rc);
8613 if (aOnline)
8614 {
8615 rc = pMediumLockList->Update(pMedium, false);
8616 AssertComRCThrowRC(rc);
8617 }
8618
8619 /* leave the lock before the potentially lengthy operation */
8620 alock.leave();
8621 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8622 pMediumLockList,
8623 NULL /* aProgress */,
8624 true /* aWait */,
8625 pfNeedsSaveSettings);
8626 alock.enter();
8627 if (FAILED(rc)) throw rc;
8628
8629 rc = lockedMediaMap->Unlock();
8630 AssertComRCThrowRC(rc);
8631 rc = pMediumLockList->Append(diff, true);
8632 AssertComRCThrowRC(rc);
8633 rc = lockedMediaMap->Lock();
8634 AssertComRCThrowRC(rc);
8635
8636 rc = diff->addBackReference(mData->mUuid);
8637 AssertComRCThrowRC(rc);
8638
8639 /* add a new attachment */
8640 ComObjPtr<MediumAttachment> attachment;
8641 attachment.createObject();
8642 rc = attachment->init(this,
8643 diff,
8644 pAtt->getControllerName(),
8645 pAtt->getPort(),
8646 pAtt->getDevice(),
8647 DeviceType_HardDisk,
8648 true /* aImplicit */,
8649 0 /* No bandwidth limit */);
8650 if (FAILED(rc)) throw rc;
8651
8652 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8653 AssertComRCThrowRC(rc);
8654 mMediaData->mAttachments.push_back(attachment);
8655 }
8656 }
8657 catch (HRESULT aRC) { rc = aRC; }
8658
8659 /* unlock all hard disks we locked */
8660 if (!aOnline)
8661 {
8662 ErrorInfoKeeper eik;
8663
8664 rc = lockedMediaMap->Clear();
8665 AssertComRC(rc);
8666 }
8667
8668 if (FAILED(rc))
8669 {
8670 MultiResult mrc = rc;
8671
8672 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8673 }
8674
8675 return rc;
8676}
8677
8678/**
8679 * Deletes implicit differencing hard disks created either by
8680 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8681 *
8682 * Note that to delete hard disks created by #AttachMedium() this method is
8683 * called from #fixupMedia() when the changes are rolled back.
8684 *
8685 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8686 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8687 *
8688 * @note Locks this object for writing.
8689 */
8690HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8691{
8692 AutoCaller autoCaller(this);
8693 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8694
8695 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8696 LogFlowThisFuncEnter();
8697
8698 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8699
8700 HRESULT rc = S_OK;
8701
8702 MediaData::AttachmentList implicitAtts;
8703
8704 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8705
8706 /* enumerate new attachments */
8707 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8708 it != mMediaData->mAttachments.end();
8709 ++it)
8710 {
8711 ComObjPtr<Medium> hd = (*it)->getMedium();
8712 if (hd.isNull())
8713 continue;
8714
8715 if ((*it)->isImplicit())
8716 {
8717 /* deassociate and mark for deletion */
8718 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8719 rc = hd->removeBackReference(mData->mUuid);
8720 AssertComRC(rc);
8721 implicitAtts.push_back(*it);
8722 continue;
8723 }
8724
8725 /* was this hard disk attached before? */
8726 if (!findAttachment(oldAtts, hd))
8727 {
8728 /* no: de-associate */
8729 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8730 rc = hd->removeBackReference(mData->mUuid);
8731 AssertComRC(rc);
8732 continue;
8733 }
8734 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8735 }
8736
8737 /* rollback hard disk changes */
8738 mMediaData.rollback();
8739
8740 MultiResult mrc(S_OK);
8741
8742 /* delete unused implicit diffs */
8743 if (implicitAtts.size() != 0)
8744 {
8745 /* will leave the lock before the potentially lengthy
8746 * operation, so protect with the special state (unless already
8747 * protected) */
8748 MachineState_T oldState = mData->mMachineState;
8749 if ( oldState != MachineState_Saving
8750 && oldState != MachineState_LiveSnapshotting
8751 && oldState != MachineState_RestoringSnapshot
8752 && oldState != MachineState_DeletingSnapshot
8753 && oldState != MachineState_DeletingSnapshotOnline
8754 && oldState != MachineState_DeletingSnapshotPaused
8755 )
8756 setMachineState(MachineState_SettingUp);
8757
8758 alock.leave();
8759
8760 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8761 it != implicitAtts.end();
8762 ++it)
8763 {
8764 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8765 ComObjPtr<Medium> hd = (*it)->getMedium();
8766
8767 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8768 pfNeedsSaveSettings);
8769 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8770 mrc = rc;
8771 }
8772
8773 alock.enter();
8774
8775 if (mData->mMachineState == MachineState_SettingUp)
8776 {
8777 setMachineState(oldState);
8778 }
8779 }
8780
8781 return mrc;
8782}
8783
8784/**
8785 * Looks through the given list of media attachments for one with the given parameters
8786 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8787 * can be searched as well if needed.
8788 *
8789 * @param list
8790 * @param aControllerName
8791 * @param aControllerPort
8792 * @param aDevice
8793 * @return
8794 */
8795MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8796 IN_BSTR aControllerName,
8797 LONG aControllerPort,
8798 LONG aDevice)
8799{
8800 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8801 it != ll.end();
8802 ++it)
8803 {
8804 MediumAttachment *pAttach = *it;
8805 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8806 return pAttach;
8807 }
8808
8809 return NULL;
8810}
8811
8812/**
8813 * Looks through the given list of media attachments for one with the given parameters
8814 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8815 * can be searched as well if needed.
8816 *
8817 * @param list
8818 * @param aControllerName
8819 * @param aControllerPort
8820 * @param aDevice
8821 * @return
8822 */
8823MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8824 ComObjPtr<Medium> pMedium)
8825{
8826 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8827 it != ll.end();
8828 ++it)
8829 {
8830 MediumAttachment *pAttach = *it;
8831 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8832 if (pMediumThis == pMedium)
8833 return pAttach;
8834 }
8835
8836 return NULL;
8837}
8838
8839/**
8840 * Looks through the given list of media attachments for one with the given parameters
8841 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8842 * can be searched as well if needed.
8843 *
8844 * @param list
8845 * @param aControllerName
8846 * @param aControllerPort
8847 * @param aDevice
8848 * @return
8849 */
8850MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8851 Guid &id)
8852{
8853 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8854 it != ll.end();
8855 ++it)
8856 {
8857 MediumAttachment *pAttach = *it;
8858 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8859 if (pMediumThis->getId() == id)
8860 return pAttach;
8861 }
8862
8863 return NULL;
8864}
8865
8866/**
8867 * Main implementation for Machine::DetachDevice. This also gets called
8868 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8869 *
8870 * @param pAttach Medium attachment to detach.
8871 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8872 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8873 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8874 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8875 * @return
8876 */
8877HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8878 AutoWriteLock &writeLock,
8879 Snapshot *pSnapshot,
8880 bool *pfNeedsSaveSettings)
8881{
8882 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8883 DeviceType_T mediumType = pAttach->getType();
8884
8885 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8886
8887 if (pAttach->isImplicit())
8888 {
8889 /* attempt to implicitly delete the implicitly created diff */
8890
8891 /// @todo move the implicit flag from MediumAttachment to Medium
8892 /// and forbid any hard disk operation when it is implicit. Or maybe
8893 /// a special media state for it to make it even more simple.
8894
8895 Assert(mMediaData.isBackedUp());
8896
8897 /* will leave the lock before the potentially lengthy operation, so
8898 * protect with the special state */
8899 MachineState_T oldState = mData->mMachineState;
8900 setMachineState(MachineState_SettingUp);
8901
8902 writeLock.release();
8903
8904 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8905 pfNeedsSaveSettings);
8906
8907 writeLock.acquire();
8908
8909 setMachineState(oldState);
8910
8911 if (FAILED(rc)) return rc;
8912 }
8913
8914 setModified(IsModified_Storage);
8915 mMediaData.backup();
8916
8917 // we cannot use erase (it) below because backup() above will create
8918 // a copy of the list and make this copy active, but the iterator
8919 // still refers to the original and is not valid for the copy
8920 mMediaData->mAttachments.remove(pAttach);
8921
8922 if (!oldmedium.isNull())
8923 {
8924 // if this is from a snapshot, do not defer detachment to commitMedia()
8925 if (pSnapshot)
8926 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8927 // else if non-hard disk media, do not defer detachment to commitMedia() either
8928 else if (mediumType != DeviceType_HardDisk)
8929 oldmedium->removeBackReference(mData->mUuid);
8930 }
8931
8932 return S_OK;
8933}
8934
8935/**
8936 * Goes thru all medium attachments of the list and calls detachDevice() on each
8937 * of them and attaches all Medium objects found in the process to the given list,
8938 * depending on cleanupMode.
8939 *
8940 * This gets called from Machine::Unregister, both for the actual Machine and
8941 * the SnapshotMachine objects that might be found in the snapshots.
8942 *
8943 * Requires caller and locking.
8944 *
8945 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8946 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8947 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
8948 * otherwise no media get added.
8949 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
8950 * @return
8951 */
8952HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8953 Snapshot *pSnapshot,
8954 CleanupMode_T cleanupMode,
8955 MediaList &llMedia)
8956{
8957 Assert(isWriteLockOnCurrentThread());
8958
8959 HRESULT rc;
8960
8961 // make a temporary list because detachDevice invalidates iterators into
8962 // mMediaData->mAttachments
8963 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8964
8965 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8966 it != llAttachments2.end();
8967 ++it)
8968 {
8969 ComObjPtr<MediumAttachment> pAttach = *it;
8970 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8971
8972 if (!pMedium.isNull())
8973 {
8974 DeviceType_T devType = pMedium->getDeviceType();
8975 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
8976 && devType == DeviceType_HardDisk)
8977 || (cleanupMode == CleanupMode_Full)
8978 )
8979 llMedia.push_back(pMedium);
8980 }
8981
8982 // real machine: then we need to use the proper method
8983 rc = detachDevice(pAttach,
8984 writeLock,
8985 pSnapshot,
8986 NULL /* pfNeedsSaveSettings */);
8987
8988 if (FAILED(rc))
8989 return rc;
8990 }
8991
8992 return S_OK;
8993}
8994
8995/**
8996 * Perform deferred hard disk detachments.
8997 *
8998 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8999 * backed up).
9000 *
9001 * If @a aOnline is @c true then this method will also unlock the old hard disks
9002 * for which the new implicit diffs were created and will lock these new diffs for
9003 * writing.
9004 *
9005 * @param aOnline Whether the VM was online prior to this operation.
9006 *
9007 * @note Locks this object for writing!
9008 */
9009void Machine::commitMedia(bool aOnline /*= false*/)
9010{
9011 AutoCaller autoCaller(this);
9012 AssertComRCReturnVoid(autoCaller.rc());
9013
9014 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9015
9016 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9017
9018 HRESULT rc = S_OK;
9019
9020 /* no attach/detach operations -- nothing to do */
9021 if (!mMediaData.isBackedUp())
9022 return;
9023
9024 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9025 bool fMediaNeedsLocking = false;
9026
9027 /* enumerate new attachments */
9028 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9029 it != mMediaData->mAttachments.end();
9030 ++it)
9031 {
9032 MediumAttachment *pAttach = *it;
9033
9034 pAttach->commit();
9035
9036 Medium* pMedium = pAttach->getMedium();
9037 bool fImplicit = pAttach->isImplicit();
9038
9039 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9040 (pMedium) ? pMedium->getName().c_str() : "NULL",
9041 fImplicit));
9042
9043 /** @todo convert all this Machine-based voodoo to MediumAttachment
9044 * based commit logic. */
9045 if (fImplicit)
9046 {
9047 /* convert implicit attachment to normal */
9048 pAttach->setImplicit(false);
9049
9050 if ( aOnline
9051 && pMedium
9052 && pAttach->getType() == DeviceType_HardDisk
9053 )
9054 {
9055 ComObjPtr<Medium> parent = pMedium->getParent();
9056 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9057
9058 /* update the appropriate lock list */
9059 MediumLockList *pMediumLockList;
9060 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9061 AssertComRC(rc);
9062 if (pMediumLockList)
9063 {
9064 /* unlock if there's a need to change the locking */
9065 if (!fMediaNeedsLocking)
9066 {
9067 rc = mData->mSession.mLockedMedia.Unlock();
9068 AssertComRC(rc);
9069 fMediaNeedsLocking = true;
9070 }
9071 rc = pMediumLockList->Update(parent, false);
9072 AssertComRC(rc);
9073 rc = pMediumLockList->Append(pMedium, true);
9074 AssertComRC(rc);
9075 }
9076 }
9077
9078 continue;
9079 }
9080
9081 if (pMedium)
9082 {
9083 /* was this medium attached before? */
9084 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9085 oldIt != oldAtts.end();
9086 ++oldIt)
9087 {
9088 MediumAttachment *pOldAttach = *oldIt;
9089 if (pOldAttach->getMedium() == pMedium)
9090 {
9091 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9092
9093 /* yes: remove from old to avoid de-association */
9094 oldAtts.erase(oldIt);
9095 break;
9096 }
9097 }
9098 }
9099 }
9100
9101 /* enumerate remaining old attachments and de-associate from the
9102 * current machine state */
9103 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9104 it != oldAtts.end();
9105 ++it)
9106 {
9107 MediumAttachment *pAttach = *it;
9108 Medium* pMedium = pAttach->getMedium();
9109
9110 /* Detach only hard disks, since DVD/floppy media is detached
9111 * instantly in MountMedium. */
9112 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9113 {
9114 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9115
9116 /* now de-associate from the current machine state */
9117 rc = pMedium->removeBackReference(mData->mUuid);
9118 AssertComRC(rc);
9119
9120 if (aOnline)
9121 {
9122 /* unlock since medium is not used anymore */
9123 MediumLockList *pMediumLockList;
9124 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9125 AssertComRC(rc);
9126 if (pMediumLockList)
9127 {
9128 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9129 AssertComRC(rc);
9130 }
9131 }
9132 }
9133 }
9134
9135 /* take media locks again so that the locking state is consistent */
9136 if (fMediaNeedsLocking)
9137 {
9138 Assert(aOnline);
9139 rc = mData->mSession.mLockedMedia.Lock();
9140 AssertComRC(rc);
9141 }
9142
9143 /* commit the hard disk changes */
9144 mMediaData.commit();
9145
9146 if (isSessionMachine())
9147 {
9148 /* attach new data to the primary machine and reshare it */
9149 mPeer->mMediaData.attach(mMediaData);
9150 }
9151
9152 return;
9153}
9154
9155/**
9156 * Perform deferred deletion of implicitly created diffs.
9157 *
9158 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9159 * backed up).
9160 *
9161 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9162 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9163 *
9164 * @note Locks this object for writing!
9165 */
9166void Machine::rollbackMedia()
9167{
9168 AutoCaller autoCaller(this);
9169 AssertComRCReturnVoid (autoCaller.rc());
9170
9171 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9172
9173 LogFlowThisFunc(("Entering\n"));
9174
9175 HRESULT rc = S_OK;
9176
9177 /* no attach/detach operations -- nothing to do */
9178 if (!mMediaData.isBackedUp())
9179 return;
9180
9181 /* enumerate new attachments */
9182 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9183 it != mMediaData->mAttachments.end();
9184 ++it)
9185 {
9186 MediumAttachment *pAttach = *it;
9187 /* Fix up the backrefs for DVD/floppy media. */
9188 if (pAttach->getType() != DeviceType_HardDisk)
9189 {
9190 Medium* pMedium = pAttach->getMedium();
9191 if (pMedium)
9192 {
9193 rc = pMedium->removeBackReference(mData->mUuid);
9194 AssertComRC(rc);
9195 }
9196 }
9197
9198 (*it)->rollback();
9199
9200 pAttach = *it;
9201 /* Fix up the backrefs for DVD/floppy media. */
9202 if (pAttach->getType() != DeviceType_HardDisk)
9203 {
9204 Medium* pMedium = pAttach->getMedium();
9205 if (pMedium)
9206 {
9207 rc = pMedium->addBackReference(mData->mUuid);
9208 AssertComRC(rc);
9209 }
9210 }
9211 }
9212
9213 /** @todo convert all this Machine-based voodoo to MediumAttachment
9214 * based rollback logic. */
9215 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9216 // which gets called if Machine::registeredInit() fails...
9217 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9218
9219 return;
9220}
9221
9222/**
9223 * Returns true if the settings file is located in the directory named exactly
9224 * as the machine. This will be true if the machine settings structure was
9225 * created by default in #openConfigLoader().
9226 *
9227 * @param aSettingsDir if not NULL, the full machine settings file directory
9228 * name will be assigned there.
9229 *
9230 * @note Doesn't lock anything.
9231 * @note Not thread safe (must be called from this object's lock).
9232 */
9233bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9234{
9235 Utf8Str settingsDir = mData->m_strConfigFileFull;
9236 settingsDir.stripFilename();
9237 Utf8Str strDirName = RTPathFilename(settingsDir.c_str());
9238
9239 AssertReturn(!strDirName.isEmpty(), false);
9240
9241 /* if we don't rename anything on name change, return false shortly */
9242 if (!mUserData->s.fNameSync)
9243 return false;
9244
9245 if (aSettingsDir)
9246 *aSettingsDir = settingsDir;
9247
9248 return strDirName == mUserData->s.strName;
9249}
9250
9251/**
9252 * Discards all changes to machine settings.
9253 *
9254 * @param aNotify Whether to notify the direct session about changes or not.
9255 *
9256 * @note Locks objects for writing!
9257 */
9258void Machine::rollback(bool aNotify)
9259{
9260 AutoCaller autoCaller(this);
9261 AssertComRCReturn(autoCaller.rc(), (void)0);
9262
9263 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9264
9265 if (!mStorageControllers.isNull())
9266 {
9267 if (mStorageControllers.isBackedUp())
9268 {
9269 /* unitialize all new devices (absent in the backed up list). */
9270 StorageControllerList::const_iterator it = mStorageControllers->begin();
9271 StorageControllerList *backedList = mStorageControllers.backedUpData();
9272 while (it != mStorageControllers->end())
9273 {
9274 if ( std::find(backedList->begin(), backedList->end(), *it)
9275 == backedList->end()
9276 )
9277 {
9278 (*it)->uninit();
9279 }
9280 ++it;
9281 }
9282
9283 /* restore the list */
9284 mStorageControllers.rollback();
9285 }
9286
9287 /* rollback any changes to devices after restoring the list */
9288 if (mData->flModifications & IsModified_Storage)
9289 {
9290 StorageControllerList::const_iterator it = mStorageControllers->begin();
9291 while (it != mStorageControllers->end())
9292 {
9293 (*it)->rollback();
9294 ++it;
9295 }
9296 }
9297 }
9298
9299 mUserData.rollback();
9300
9301 mHWData.rollback();
9302
9303 if (mData->flModifications & IsModified_Storage)
9304 rollbackMedia();
9305
9306 if (mBIOSSettings)
9307 mBIOSSettings->rollback();
9308
9309 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9310 mVRDEServer->rollback();
9311
9312 if (mAudioAdapter)
9313 mAudioAdapter->rollback();
9314
9315 if (mUSBController && (mData->flModifications & IsModified_USB))
9316 mUSBController->rollback();
9317
9318 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9319 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9320 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9321
9322 if (mData->flModifications & IsModified_NetworkAdapters)
9323 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9324 if ( mNetworkAdapters[slot]
9325 && mNetworkAdapters[slot]->isModified())
9326 {
9327 mNetworkAdapters[slot]->rollback();
9328 networkAdapters[slot] = mNetworkAdapters[slot];
9329 }
9330
9331 if (mData->flModifications & IsModified_SerialPorts)
9332 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9333 if ( mSerialPorts[slot]
9334 && mSerialPorts[slot]->isModified())
9335 {
9336 mSerialPorts[slot]->rollback();
9337 serialPorts[slot] = mSerialPorts[slot];
9338 }
9339
9340 if (mData->flModifications & IsModified_ParallelPorts)
9341 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9342 if ( mParallelPorts[slot]
9343 && mParallelPorts[slot]->isModified())
9344 {
9345 mParallelPorts[slot]->rollback();
9346 parallelPorts[slot] = mParallelPorts[slot];
9347 }
9348
9349 if (aNotify)
9350 {
9351 /* inform the direct session about changes */
9352
9353 ComObjPtr<Machine> that = this;
9354 uint32_t flModifications = mData->flModifications;
9355 alock.leave();
9356
9357 if (flModifications & IsModified_SharedFolders)
9358 that->onSharedFolderChange();
9359
9360 if (flModifications & IsModified_VRDEServer)
9361 that->onVRDEServerChange(/* aRestart */ TRUE);
9362 if (flModifications & IsModified_USB)
9363 that->onUSBControllerChange();
9364
9365 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9366 if (networkAdapters[slot])
9367 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9368 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9369 if (serialPorts[slot])
9370 that->onSerialPortChange(serialPorts[slot]);
9371 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9372 if (parallelPorts[slot])
9373 that->onParallelPortChange(parallelPorts[slot]);
9374
9375 if (flModifications & IsModified_Storage)
9376 that->onStorageControllerChange();
9377 }
9378}
9379
9380/**
9381 * Commits all the changes to machine settings.
9382 *
9383 * Note that this operation is supposed to never fail.
9384 *
9385 * @note Locks this object and children for writing.
9386 */
9387void Machine::commit()
9388{
9389 AutoCaller autoCaller(this);
9390 AssertComRCReturnVoid(autoCaller.rc());
9391
9392 AutoCaller peerCaller(mPeer);
9393 AssertComRCReturnVoid(peerCaller.rc());
9394
9395 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9396
9397 /*
9398 * use safe commit to ensure Snapshot machines (that share mUserData)
9399 * will still refer to a valid memory location
9400 */
9401 mUserData.commitCopy();
9402
9403 mHWData.commit();
9404
9405 if (mMediaData.isBackedUp())
9406 commitMedia();
9407
9408 mBIOSSettings->commit();
9409 mVRDEServer->commit();
9410 mAudioAdapter->commit();
9411 mUSBController->commit();
9412
9413 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9414 mNetworkAdapters[slot]->commit();
9415 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9416 mSerialPorts[slot]->commit();
9417 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9418 mParallelPorts[slot]->commit();
9419
9420 bool commitStorageControllers = false;
9421
9422 if (mStorageControllers.isBackedUp())
9423 {
9424 mStorageControllers.commit();
9425
9426 if (mPeer)
9427 {
9428 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9429
9430 /* Commit all changes to new controllers (this will reshare data with
9431 * peers for those who have peers) */
9432 StorageControllerList *newList = new StorageControllerList();
9433 StorageControllerList::const_iterator it = mStorageControllers->begin();
9434 while (it != mStorageControllers->end())
9435 {
9436 (*it)->commit();
9437
9438 /* look if this controller has a peer device */
9439 ComObjPtr<StorageController> peer = (*it)->getPeer();
9440 if (!peer)
9441 {
9442 /* no peer means the device is a newly created one;
9443 * create a peer owning data this device share it with */
9444 peer.createObject();
9445 peer->init(mPeer, *it, true /* aReshare */);
9446 }
9447 else
9448 {
9449 /* remove peer from the old list */
9450 mPeer->mStorageControllers->remove(peer);
9451 }
9452 /* and add it to the new list */
9453 newList->push_back(peer);
9454
9455 ++it;
9456 }
9457
9458 /* uninit old peer's controllers that are left */
9459 it = mPeer->mStorageControllers->begin();
9460 while (it != mPeer->mStorageControllers->end())
9461 {
9462 (*it)->uninit();
9463 ++it;
9464 }
9465
9466 /* attach new list of controllers to our peer */
9467 mPeer->mStorageControllers.attach(newList);
9468 }
9469 else
9470 {
9471 /* we have no peer (our parent is the newly created machine);
9472 * just commit changes to devices */
9473 commitStorageControllers = true;
9474 }
9475 }
9476 else
9477 {
9478 /* the list of controllers itself is not changed,
9479 * just commit changes to controllers themselves */
9480 commitStorageControllers = true;
9481 }
9482
9483 if (commitStorageControllers)
9484 {
9485 StorageControllerList::const_iterator it = mStorageControllers->begin();
9486 while (it != mStorageControllers->end())
9487 {
9488 (*it)->commit();
9489 ++it;
9490 }
9491 }
9492
9493 if (isSessionMachine())
9494 {
9495 /* attach new data to the primary machine and reshare it */
9496 mPeer->mUserData.attach(mUserData);
9497 mPeer->mHWData.attach(mHWData);
9498 /* mMediaData is reshared by fixupMedia */
9499 // mPeer->mMediaData.attach(mMediaData);
9500 Assert(mPeer->mMediaData.data() == mMediaData.data());
9501 }
9502}
9503
9504/**
9505 * Copies all the hardware data from the given machine.
9506 *
9507 * Currently, only called when the VM is being restored from a snapshot. In
9508 * particular, this implies that the VM is not running during this method's
9509 * call.
9510 *
9511 * @note This method must be called from under this object's lock.
9512 *
9513 * @note This method doesn't call #commit(), so all data remains backed up and
9514 * unsaved.
9515 */
9516void Machine::copyFrom(Machine *aThat)
9517{
9518 AssertReturnVoid(!isSnapshotMachine());
9519 AssertReturnVoid(aThat->isSnapshotMachine());
9520
9521 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9522
9523 mHWData.assignCopy(aThat->mHWData);
9524
9525 // create copies of all shared folders (mHWData after attaching a copy
9526 // contains just references to original objects)
9527 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9528 it != mHWData->mSharedFolders.end();
9529 ++it)
9530 {
9531 ComObjPtr<SharedFolder> folder;
9532 folder.createObject();
9533 HRESULT rc = folder->initCopy(getMachine(), *it);
9534 AssertComRC(rc);
9535 *it = folder;
9536 }
9537
9538 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9539 mVRDEServer->copyFrom(aThat->mVRDEServer);
9540 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9541 mUSBController->copyFrom(aThat->mUSBController);
9542
9543 /* create private copies of all controllers */
9544 mStorageControllers.backup();
9545 mStorageControllers->clear();
9546 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9547 it != aThat->mStorageControllers->end();
9548 ++it)
9549 {
9550 ComObjPtr<StorageController> ctrl;
9551 ctrl.createObject();
9552 ctrl->initCopy(this, *it);
9553 mStorageControllers->push_back(ctrl);
9554 }
9555
9556 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9557 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9558 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9559 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9560 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9561 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9562}
9563
9564#ifdef VBOX_WITH_RESOURCE_USAGE_API
9565
9566void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9567{
9568 AssertReturnVoid(isWriteLockOnCurrentThread());
9569 AssertPtrReturnVoid(aCollector);
9570
9571 pm::CollectorHAL *hal = aCollector->getHAL();
9572 /* Create sub metrics */
9573 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9574 "Percentage of processor time spent in user mode by the VM process.");
9575 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9576 "Percentage of processor time spent in kernel mode by the VM process.");
9577 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9578 "Size of resident portion of VM process in memory.");
9579 /* Create and register base metrics */
9580 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9581 cpuLoadUser, cpuLoadKernel);
9582 aCollector->registerBaseMetric(cpuLoad);
9583 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9584 ramUsageUsed);
9585 aCollector->registerBaseMetric(ramUsage);
9586
9587 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9588 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9589 new pm::AggregateAvg()));
9590 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9591 new pm::AggregateMin()));
9592 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9593 new pm::AggregateMax()));
9594 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9595 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9596 new pm::AggregateAvg()));
9597 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9598 new pm::AggregateMin()));
9599 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9600 new pm::AggregateMax()));
9601
9602 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9603 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9604 new pm::AggregateAvg()));
9605 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9606 new pm::AggregateMin()));
9607 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9608 new pm::AggregateMax()));
9609
9610
9611 /* Guest metrics */
9612 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9613
9614 /* Create sub metrics */
9615 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9616 "Percentage of processor time spent in user mode as seen by the guest.");
9617 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9618 "Percentage of processor time spent in kernel mode as seen by the guest.");
9619 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9620 "Percentage of processor time spent idling as seen by the guest.");
9621
9622 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9623 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9624 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9625 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9626 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9627 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9628
9629 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9630
9631 /* Create and register base metrics */
9632 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9633 aCollector->registerBaseMetric(guestCpuLoad);
9634
9635 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9636 guestMemCache, guestPagedTotal);
9637 aCollector->registerBaseMetric(guestCpuMem);
9638
9639 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9640 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9641 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9642 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9643
9644 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9645 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9646 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9647 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9648
9649 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9650 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9651 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9652 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9653
9654 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9655 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9656 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9657 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9658
9659 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9660 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9661 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9662 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9663
9664 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9665 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9666 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9667 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9668
9669 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9670 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9671 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9672 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9673
9674 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9675 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9676 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9677 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9678
9679 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9680 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9681 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9682 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9683}
9684
9685void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9686{
9687 AssertReturnVoid(isWriteLockOnCurrentThread());
9688
9689 if (aCollector)
9690 {
9691 aCollector->unregisterMetricsFor(aMachine);
9692 aCollector->unregisterBaseMetricsFor(aMachine);
9693 }
9694
9695 if (mGuestHAL)
9696 {
9697 delete mGuestHAL;
9698 mGuestHAL = NULL;
9699 }
9700}
9701
9702#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9703
9704
9705////////////////////////////////////////////////////////////////////////////////
9706
9707DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9708
9709HRESULT SessionMachine::FinalConstruct()
9710{
9711 LogFlowThisFunc(("\n"));
9712
9713#if defined(RT_OS_WINDOWS)
9714 mIPCSem = NULL;
9715#elif defined(RT_OS_OS2)
9716 mIPCSem = NULLHANDLE;
9717#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9718 mIPCSem = -1;
9719#else
9720# error "Port me!"
9721#endif
9722
9723 return S_OK;
9724}
9725
9726void SessionMachine::FinalRelease()
9727{
9728 LogFlowThisFunc(("\n"));
9729
9730 uninit(Uninit::Unexpected);
9731}
9732
9733/**
9734 * @note Must be called only by Machine::openSession() from its own write lock.
9735 */
9736HRESULT SessionMachine::init(Machine *aMachine)
9737{
9738 LogFlowThisFuncEnter();
9739 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
9740
9741 AssertReturn(aMachine, E_INVALIDARG);
9742
9743 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9744
9745 /* Enclose the state transition NotReady->InInit->Ready */
9746 AutoInitSpan autoInitSpan(this);
9747 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9748
9749 /* create the interprocess semaphore */
9750#if defined(RT_OS_WINDOWS)
9751 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9752 for (size_t i = 0; i < mIPCSemName.length(); i++)
9753 if (mIPCSemName.raw()[i] == '\\')
9754 mIPCSemName.raw()[i] = '/';
9755 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
9756 ComAssertMsgRet(mIPCSem,
9757 ("Cannot create IPC mutex '%ls', err=%d",
9758 mIPCSemName.raw(), ::GetLastError()),
9759 E_FAIL);
9760#elif defined(RT_OS_OS2)
9761 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9762 aMachine->mData->mUuid.raw());
9763 mIPCSemName = ipcSem;
9764 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
9765 ComAssertMsgRet(arc == NO_ERROR,
9766 ("Cannot create IPC mutex '%s', arc=%ld",
9767 ipcSem.c_str(), arc),
9768 E_FAIL);
9769#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9770# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9771# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9772 /** @todo Check that this still works correctly. */
9773 AssertCompileSize(key_t, 8);
9774# else
9775 AssertCompileSize(key_t, 4);
9776# endif
9777 key_t key;
9778 mIPCSem = -1;
9779 mIPCKey = "0";
9780 for (uint32_t i = 0; i < 1 << 24; i++)
9781 {
9782 key = ((uint32_t)'V' << 24) | i;
9783 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9784 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9785 {
9786 mIPCSem = sem;
9787 if (sem >= 0)
9788 mIPCKey = BstrFmt("%u", key);
9789 break;
9790 }
9791 }
9792# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9793 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9794 char *pszSemName = NULL;
9795 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9796 key_t key = ::ftok(pszSemName, 'V');
9797 RTStrFree(pszSemName);
9798
9799 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9800# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9801
9802 int errnoSave = errno;
9803 if (mIPCSem < 0 && errnoSave == ENOSYS)
9804 {
9805 setError(E_FAIL,
9806 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9807 "support for SysV IPC. Check the host kernel configuration for "
9808 "CONFIG_SYSVIPC=y"));
9809 return E_FAIL;
9810 }
9811 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9812 * the IPC semaphores */
9813 if (mIPCSem < 0 && errnoSave == ENOSPC)
9814 {
9815#ifdef RT_OS_LINUX
9816 setError(E_FAIL,
9817 tr("Cannot create IPC semaphore because the system limit for the "
9818 "maximum number of semaphore sets (SEMMNI), or the system wide "
9819 "maximum number of semaphores (SEMMNS) would be exceeded. The "
9820 "current set of SysV IPC semaphores can be determined from "
9821 "the file /proc/sysvipc/sem"));
9822#else
9823 setError(E_FAIL,
9824 tr("Cannot create IPC semaphore because the system-imposed limit "
9825 "on the maximum number of allowed semaphores or semaphore "
9826 "identifiers system-wide would be exceeded"));
9827#endif
9828 return E_FAIL;
9829 }
9830 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9831 E_FAIL);
9832 /* set the initial value to 1 */
9833 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9834 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9835 E_FAIL);
9836#else
9837# error "Port me!"
9838#endif
9839
9840 /* memorize the peer Machine */
9841 unconst(mPeer) = aMachine;
9842 /* share the parent pointer */
9843 unconst(mParent) = aMachine->mParent;
9844
9845 /* take the pointers to data to share */
9846 mData.share(aMachine->mData);
9847 mSSData.share(aMachine->mSSData);
9848
9849 mUserData.share(aMachine->mUserData);
9850 mHWData.share(aMachine->mHWData);
9851 mMediaData.share(aMachine->mMediaData);
9852
9853 mStorageControllers.allocate();
9854 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9855 it != aMachine->mStorageControllers->end();
9856 ++it)
9857 {
9858 ComObjPtr<StorageController> ctl;
9859 ctl.createObject();
9860 ctl->init(this, *it);
9861 mStorageControllers->push_back(ctl);
9862 }
9863
9864 unconst(mBIOSSettings).createObject();
9865 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9866 /* create another VRDEServer object that will be mutable */
9867 unconst(mVRDEServer).createObject();
9868 mVRDEServer->init(this, aMachine->mVRDEServer);
9869 /* create another audio adapter object that will be mutable */
9870 unconst(mAudioAdapter).createObject();
9871 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9872 /* create a list of serial ports that will be mutable */
9873 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9874 {
9875 unconst(mSerialPorts[slot]).createObject();
9876 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9877 }
9878 /* create a list of parallel ports that will be mutable */
9879 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9880 {
9881 unconst(mParallelPorts[slot]).createObject();
9882 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9883 }
9884 /* create another USB controller object that will be mutable */
9885 unconst(mUSBController).createObject();
9886 mUSBController->init(this, aMachine->mUSBController);
9887
9888 /* create a list of network adapters that will be mutable */
9889 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9890 {
9891 unconst(mNetworkAdapters[slot]).createObject();
9892 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9893 }
9894
9895 /* default is to delete saved state on Saved -> PoweredOff transition */
9896 mRemoveSavedState = true;
9897
9898 /* Confirm a successful initialization when it's the case */
9899 autoInitSpan.setSucceeded();
9900
9901 LogFlowThisFuncLeave();
9902 return S_OK;
9903}
9904
9905/**
9906 * Uninitializes this session object. If the reason is other than
9907 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9908 *
9909 * @param aReason uninitialization reason
9910 *
9911 * @note Locks mParent + this object for writing.
9912 */
9913void SessionMachine::uninit(Uninit::Reason aReason)
9914{
9915 LogFlowThisFuncEnter();
9916 LogFlowThisFunc(("reason=%d\n", aReason));
9917
9918 /*
9919 * Strongly reference ourselves to prevent this object deletion after
9920 * mData->mSession.mMachine.setNull() below (which can release the last
9921 * reference and call the destructor). Important: this must be done before
9922 * accessing any members (and before AutoUninitSpan that does it as well).
9923 * This self reference will be released as the very last step on return.
9924 */
9925 ComObjPtr<SessionMachine> selfRef = this;
9926
9927 /* Enclose the state transition Ready->InUninit->NotReady */
9928 AutoUninitSpan autoUninitSpan(this);
9929 if (autoUninitSpan.uninitDone())
9930 {
9931 LogFlowThisFunc(("Already uninitialized\n"));
9932 LogFlowThisFuncLeave();
9933 return;
9934 }
9935
9936 if (autoUninitSpan.initFailed())
9937 {
9938 /* We've been called by init() because it's failed. It's not really
9939 * necessary (nor it's safe) to perform the regular uninit sequence
9940 * below, the following is enough.
9941 */
9942 LogFlowThisFunc(("Initialization failed.\n"));
9943#if defined(RT_OS_WINDOWS)
9944 if (mIPCSem)
9945 ::CloseHandle(mIPCSem);
9946 mIPCSem = NULL;
9947#elif defined(RT_OS_OS2)
9948 if (mIPCSem != NULLHANDLE)
9949 ::DosCloseMutexSem(mIPCSem);
9950 mIPCSem = NULLHANDLE;
9951#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9952 if (mIPCSem >= 0)
9953 ::semctl(mIPCSem, 0, IPC_RMID);
9954 mIPCSem = -1;
9955# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9956 mIPCKey = "0";
9957# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9958#else
9959# error "Port me!"
9960#endif
9961 uninitDataAndChildObjects();
9962 mData.free();
9963 unconst(mParent) = NULL;
9964 unconst(mPeer) = NULL;
9965 LogFlowThisFuncLeave();
9966 return;
9967 }
9968
9969 MachineState_T lastState;
9970 {
9971 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9972 lastState = mData->mMachineState;
9973 }
9974 NOREF(lastState);
9975
9976#ifdef VBOX_WITH_USB
9977 // release all captured USB devices, but do this before requesting the locks below
9978 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9979 {
9980 /* Console::captureUSBDevices() is called in the VM process only after
9981 * setting the machine state to Starting or Restoring.
9982 * Console::detachAllUSBDevices() will be called upon successful
9983 * termination. So, we need to release USB devices only if there was
9984 * an abnormal termination of a running VM.
9985 *
9986 * This is identical to SessionMachine::DetachAllUSBDevices except
9987 * for the aAbnormal argument. */
9988 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9989 AssertComRC(rc);
9990 NOREF(rc);
9991
9992 USBProxyService *service = mParent->host()->usbProxyService();
9993 if (service)
9994 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9995 }
9996#endif /* VBOX_WITH_USB */
9997
9998 // we need to lock this object in uninit() because the lock is shared
9999 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10000 // and others need mParent lock, and USB needs host lock.
10001 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10002
10003 // Trigger async cleanup tasks, avoid doing things here which are not
10004 // vital to be done immediately and maybe need more locks. This calls
10005 // Machine::unregisterMetrics().
10006 mParent->onMachineUninit(mPeer);
10007
10008 if (aReason == Uninit::Abnormal)
10009 {
10010 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10011 Global::IsOnlineOrTransient(lastState)));
10012
10013 /* reset the state to Aborted */
10014 if (mData->mMachineState != MachineState_Aborted)
10015 setMachineState(MachineState_Aborted);
10016 }
10017
10018 // any machine settings modified?
10019 if (mData->flModifications)
10020 {
10021 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10022 rollback(false /* aNotify */);
10023 }
10024
10025 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
10026 if (!mSnapshotData.mStateFilePath.isEmpty())
10027 {
10028 LogWarningThisFunc(("canceling failed save state request!\n"));
10029 endSavingState(FALSE /* aSuccess */);
10030 }
10031 else if (!mSnapshotData.mSnapshot.isNull())
10032 {
10033 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10034
10035 /* delete all differencing hard disks created (this will also attach
10036 * their parents back by rolling back mMediaData) */
10037 rollbackMedia();
10038 /* delete the saved state file (it might have been already created) */
10039 if (mSnapshotData.mSnapshot->stateFilePath().length())
10040 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
10041
10042 mSnapshotData.mSnapshot->uninit();
10043 }
10044
10045 if (!mData->mSession.mType.isEmpty())
10046 {
10047 /* mType is not null when this machine's process has been started by
10048 * Machine::launchVMProcess(), therefore it is our child. We
10049 * need to queue the PID to reap the process (and avoid zombies on
10050 * Linux). */
10051 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10052 mParent->addProcessToReap(mData->mSession.mPid);
10053 }
10054
10055 mData->mSession.mPid = NIL_RTPROCESS;
10056
10057 if (aReason == Uninit::Unexpected)
10058 {
10059 /* Uninitialization didn't come from #checkForDeath(), so tell the
10060 * client watcher thread to update the set of machines that have open
10061 * sessions. */
10062 mParent->updateClientWatcher();
10063 }
10064
10065 /* uninitialize all remote controls */
10066 if (mData->mSession.mRemoteControls.size())
10067 {
10068 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10069 mData->mSession.mRemoteControls.size()));
10070
10071 Data::Session::RemoteControlList::iterator it =
10072 mData->mSession.mRemoteControls.begin();
10073 while (it != mData->mSession.mRemoteControls.end())
10074 {
10075 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10076 HRESULT rc = (*it)->Uninitialize();
10077 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10078 if (FAILED(rc))
10079 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10080 ++it;
10081 }
10082 mData->mSession.mRemoteControls.clear();
10083 }
10084
10085 /*
10086 * An expected uninitialization can come only from #checkForDeath().
10087 * Otherwise it means that something's gone really wrong (for example,
10088 * the Session implementation has released the VirtualBox reference
10089 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10090 * etc). However, it's also possible, that the client releases the IPC
10091 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10092 * but the VirtualBox release event comes first to the server process.
10093 * This case is practically possible, so we should not assert on an
10094 * unexpected uninit, just log a warning.
10095 */
10096
10097 if ((aReason == Uninit::Unexpected))
10098 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10099
10100 if (aReason != Uninit::Normal)
10101 {
10102 mData->mSession.mDirectControl.setNull();
10103 }
10104 else
10105 {
10106 /* this must be null here (see #OnSessionEnd()) */
10107 Assert(mData->mSession.mDirectControl.isNull());
10108 Assert(mData->mSession.mState == SessionState_Unlocking);
10109 Assert(!mData->mSession.mProgress.isNull());
10110 }
10111 if (mData->mSession.mProgress)
10112 {
10113 if (aReason == Uninit::Normal)
10114 mData->mSession.mProgress->notifyComplete(S_OK);
10115 else
10116 mData->mSession.mProgress->notifyComplete(E_FAIL,
10117 COM_IIDOF(ISession),
10118 getComponentName(),
10119 tr("The VM session was aborted"));
10120 mData->mSession.mProgress.setNull();
10121 }
10122
10123 /* remove the association between the peer machine and this session machine */
10124 Assert( (SessionMachine*)mData->mSession.mMachine == this
10125 || aReason == Uninit::Unexpected);
10126
10127 /* reset the rest of session data */
10128 mData->mSession.mMachine.setNull();
10129 mData->mSession.mState = SessionState_Unlocked;
10130 mData->mSession.mType.setNull();
10131
10132 /* close the interprocess semaphore before leaving the exclusive lock */
10133#if defined(RT_OS_WINDOWS)
10134 if (mIPCSem)
10135 ::CloseHandle(mIPCSem);
10136 mIPCSem = NULL;
10137#elif defined(RT_OS_OS2)
10138 if (mIPCSem != NULLHANDLE)
10139 ::DosCloseMutexSem(mIPCSem);
10140 mIPCSem = NULLHANDLE;
10141#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10142 if (mIPCSem >= 0)
10143 ::semctl(mIPCSem, 0, IPC_RMID);
10144 mIPCSem = -1;
10145# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10146 mIPCKey = "0";
10147# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10148#else
10149# error "Port me!"
10150#endif
10151
10152 /* fire an event */
10153 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10154
10155 uninitDataAndChildObjects();
10156
10157 /* free the essential data structure last */
10158 mData.free();
10159
10160#if 1 /** @todo Please review this change! (bird) */
10161 /* drop the exclusive lock before setting the below two to NULL */
10162 multilock.release();
10163#else
10164 /* leave the exclusive lock before setting the below two to NULL */
10165 multilock.leave();
10166#endif
10167
10168 unconst(mParent) = NULL;
10169 unconst(mPeer) = NULL;
10170
10171 LogFlowThisFuncLeave();
10172}
10173
10174// util::Lockable interface
10175////////////////////////////////////////////////////////////////////////////////
10176
10177/**
10178 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10179 * with the primary Machine instance (mPeer).
10180 */
10181RWLockHandle *SessionMachine::lockHandle() const
10182{
10183 AssertReturn(mPeer != NULL, NULL);
10184 return mPeer->lockHandle();
10185}
10186
10187// IInternalMachineControl methods
10188////////////////////////////////////////////////////////////////////////////////
10189
10190/**
10191 * @note Locks this object for writing.
10192 */
10193STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10194{
10195 AutoCaller autoCaller(this);
10196 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10197
10198 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10199
10200 mRemoveSavedState = aRemove;
10201
10202 return S_OK;
10203}
10204
10205/**
10206 * @note Locks the same as #setMachineState() does.
10207 */
10208STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10209{
10210 return setMachineState(aMachineState);
10211}
10212
10213/**
10214 * @note Locks this object for reading.
10215 */
10216STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10217{
10218 AutoCaller autoCaller(this);
10219 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10220
10221 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10222
10223#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10224 mIPCSemName.cloneTo(aId);
10225 return S_OK;
10226#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10227# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10228 mIPCKey.cloneTo(aId);
10229# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10230 mData->m_strConfigFileFull.cloneTo(aId);
10231# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10232 return S_OK;
10233#else
10234# error "Port me!"
10235#endif
10236}
10237
10238/**
10239 * @note Locks this object for writing.
10240 */
10241STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10242{
10243 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10244 AutoCaller autoCaller(this);
10245 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10246
10247 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10248
10249 if (mData->mSession.mState != SessionState_Locked)
10250 return VBOX_E_INVALID_OBJECT_STATE;
10251
10252 if (!mData->mSession.mProgress.isNull())
10253 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10254
10255 LogFlowThisFunc(("returns S_OK.\n"));
10256 return S_OK;
10257}
10258
10259
10260/**
10261 * @note Locks this object for writing.
10262 */
10263STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10264{
10265 AutoCaller autoCaller(this);
10266 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10267
10268 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10269
10270 if (mData->mSession.mState != SessionState_Locked)
10271 return VBOX_E_INVALID_OBJECT_STATE;
10272
10273 /* Finalize the openRemoteSession progress object. */
10274 if (mData->mSession.mProgress)
10275 {
10276 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10277 mData->mSession.mProgress.setNull();
10278 }
10279
10280 if (SUCCEEDED((HRESULT)iResult))
10281 {
10282#ifdef VBOX_WITH_RESOURCE_USAGE_API
10283 /* The VM has been powered up successfully, so it makes sense
10284 * now to offer the performance metrics for a running machine
10285 * object. Doing it earlier wouldn't be safe. */
10286 registerMetrics(mParent->performanceCollector(), mPeer,
10287 mData->mSession.mPid);
10288#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10289 }
10290
10291 return S_OK;
10292}
10293
10294/**
10295 * Goes through the USB filters of the given machine to see if the given
10296 * device matches any filter or not.
10297 *
10298 * @note Locks the same as USBController::hasMatchingFilter() does.
10299 */
10300STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10301 BOOL *aMatched,
10302 ULONG *aMaskedIfs)
10303{
10304 LogFlowThisFunc(("\n"));
10305
10306 CheckComArgNotNull(aUSBDevice);
10307 CheckComArgOutPointerValid(aMatched);
10308
10309 AutoCaller autoCaller(this);
10310 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10311
10312#ifdef VBOX_WITH_USB
10313 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10314#else
10315 NOREF(aUSBDevice);
10316 NOREF(aMaskedIfs);
10317 *aMatched = FALSE;
10318#endif
10319
10320 return S_OK;
10321}
10322
10323/**
10324 * @note Locks the same as Host::captureUSBDevice() does.
10325 */
10326STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10327{
10328 LogFlowThisFunc(("\n"));
10329
10330 AutoCaller autoCaller(this);
10331 AssertComRCReturnRC(autoCaller.rc());
10332
10333#ifdef VBOX_WITH_USB
10334 /* if captureDeviceForVM() fails, it must have set extended error info */
10335 MultiResult rc = mParent->host()->checkUSBProxyService();
10336 if (FAILED(rc)) return rc;
10337
10338 USBProxyService *service = mParent->host()->usbProxyService();
10339 AssertReturn(service, E_FAIL);
10340 return service->captureDeviceForVM(this, Guid(aId).ref());
10341#else
10342 NOREF(aId);
10343 return E_NOTIMPL;
10344#endif
10345}
10346
10347/**
10348 * @note Locks the same as Host::detachUSBDevice() does.
10349 */
10350STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10351{
10352 LogFlowThisFunc(("\n"));
10353
10354 AutoCaller autoCaller(this);
10355 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10356
10357#ifdef VBOX_WITH_USB
10358 USBProxyService *service = mParent->host()->usbProxyService();
10359 AssertReturn(service, E_FAIL);
10360 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
10361#else
10362 NOREF(aId);
10363 NOREF(aDone);
10364 return E_NOTIMPL;
10365#endif
10366}
10367
10368/**
10369 * Inserts all machine filters to the USB proxy service and then calls
10370 * Host::autoCaptureUSBDevices().
10371 *
10372 * Called by Console from the VM process upon VM startup.
10373 *
10374 * @note Locks what called methods lock.
10375 */
10376STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10377{
10378 LogFlowThisFunc(("\n"));
10379
10380 AutoCaller autoCaller(this);
10381 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10382
10383#ifdef VBOX_WITH_USB
10384 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10385 AssertComRC(rc);
10386 NOREF(rc);
10387
10388 USBProxyService *service = mParent->host()->usbProxyService();
10389 AssertReturn(service, E_FAIL);
10390 return service->autoCaptureDevicesForVM(this);
10391#else
10392 return S_OK;
10393#endif
10394}
10395
10396/**
10397 * Removes all machine filters from the USB proxy service and then calls
10398 * Host::detachAllUSBDevices().
10399 *
10400 * Called by Console from the VM process upon normal VM termination or by
10401 * SessionMachine::uninit() upon abnormal VM termination (from under the
10402 * Machine/SessionMachine lock).
10403 *
10404 * @note Locks what called methods lock.
10405 */
10406STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10407{
10408 LogFlowThisFunc(("\n"));
10409
10410 AutoCaller autoCaller(this);
10411 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10412
10413#ifdef VBOX_WITH_USB
10414 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10415 AssertComRC(rc);
10416 NOREF(rc);
10417
10418 USBProxyService *service = mParent->host()->usbProxyService();
10419 AssertReturn(service, E_FAIL);
10420 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10421#else
10422 NOREF(aDone);
10423 return S_OK;
10424#endif
10425}
10426
10427/**
10428 * @note Locks this object for writing.
10429 */
10430STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10431 IProgress **aProgress)
10432{
10433 LogFlowThisFuncEnter();
10434
10435 AssertReturn(aSession, E_INVALIDARG);
10436 AssertReturn(aProgress, E_INVALIDARG);
10437
10438 AutoCaller autoCaller(this);
10439
10440 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10441 /*
10442 * We don't assert below because it might happen that a non-direct session
10443 * informs us it is closed right after we've been uninitialized -- it's ok.
10444 */
10445 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10446
10447 /* get IInternalSessionControl interface */
10448 ComPtr<IInternalSessionControl> control(aSession);
10449
10450 ComAssertRet(!control.isNull(), E_INVALIDARG);
10451
10452 /* Creating a Progress object requires the VirtualBox lock, and
10453 * thus locking it here is required by the lock order rules. */
10454 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10455
10456 if (control == mData->mSession.mDirectControl)
10457 {
10458 ComAssertRet(aProgress, E_POINTER);
10459
10460 /* The direct session is being normally closed by the client process
10461 * ----------------------------------------------------------------- */
10462
10463 /* go to the closing state (essential for all open*Session() calls and
10464 * for #checkForDeath()) */
10465 Assert(mData->mSession.mState == SessionState_Locked);
10466 mData->mSession.mState = SessionState_Unlocking;
10467
10468 /* set direct control to NULL to release the remote instance */
10469 mData->mSession.mDirectControl.setNull();
10470 LogFlowThisFunc(("Direct control is set to NULL\n"));
10471
10472 if (mData->mSession.mProgress)
10473 {
10474 /* finalize the progress, someone might wait if a frontend
10475 * closes the session before powering on the VM. */
10476 mData->mSession.mProgress->notifyComplete(E_FAIL,
10477 COM_IIDOF(ISession),
10478 getComponentName(),
10479 tr("The VM session was closed before any attempt to power it on"));
10480 mData->mSession.mProgress.setNull();
10481 }
10482
10483 /* Create the progress object the client will use to wait until
10484 * #checkForDeath() is called to uninitialize this session object after
10485 * it releases the IPC semaphore.
10486 * Note! Because we're "reusing" mProgress here, this must be a proxy
10487 * object just like for openRemoteSession. */
10488 Assert(mData->mSession.mProgress.isNull());
10489 ComObjPtr<ProgressProxy> progress;
10490 progress.createObject();
10491 ComPtr<IUnknown> pPeer(mPeer);
10492 progress->init(mParent, pPeer,
10493 Bstr(tr("Closing session")).raw(),
10494 FALSE /* aCancelable */);
10495 progress.queryInterfaceTo(aProgress);
10496 mData->mSession.mProgress = progress;
10497 }
10498 else
10499 {
10500 /* the remote session is being normally closed */
10501 Data::Session::RemoteControlList::iterator it =
10502 mData->mSession.mRemoteControls.begin();
10503 while (it != mData->mSession.mRemoteControls.end())
10504 {
10505 if (control == *it)
10506 break;
10507 ++it;
10508 }
10509 BOOL found = it != mData->mSession.mRemoteControls.end();
10510 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10511 E_INVALIDARG);
10512 mData->mSession.mRemoteControls.remove(*it);
10513 }
10514
10515 LogFlowThisFuncLeave();
10516 return S_OK;
10517}
10518
10519/**
10520 * @note Locks this object for writing.
10521 */
10522STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10523{
10524 LogFlowThisFuncEnter();
10525
10526 AssertReturn(aProgress, E_INVALIDARG);
10527 AssertReturn(aStateFilePath, E_POINTER);
10528
10529 AutoCaller autoCaller(this);
10530 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10531
10532 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10533
10534 AssertReturn( mData->mMachineState == MachineState_Paused
10535 && mSnapshotData.mLastState == MachineState_Null
10536 && mSnapshotData.mProgressId.isEmpty()
10537 && mSnapshotData.mStateFilePath.isEmpty(),
10538 E_FAIL);
10539
10540 /* memorize the progress ID and add it to the global collection */
10541 Bstr progressId;
10542 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10543 AssertComRCReturn(rc, rc);
10544 rc = mParent->addProgress(aProgress);
10545 AssertComRCReturn(rc, rc);
10546
10547 Bstr stateFilePath;
10548 /* stateFilePath is null when the machine is not running */
10549 if (mData->mMachineState == MachineState_Paused)
10550 {
10551 stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
10552 mUserData->m_strSnapshotFolderFull.c_str(),
10553 RTPATH_DELIMITER, mData->mUuid.raw());
10554 }
10555
10556 /* fill in the snapshot data */
10557 mSnapshotData.mLastState = mData->mMachineState;
10558 mSnapshotData.mProgressId = Guid(progressId);
10559 mSnapshotData.mStateFilePath = stateFilePath;
10560
10561 /* set the state to Saving (this is expected by Console::SaveState()) */
10562 setMachineState(MachineState_Saving);
10563
10564 stateFilePath.cloneTo(aStateFilePath);
10565
10566 return S_OK;
10567}
10568
10569/**
10570 * @note Locks mParent + this object for writing.
10571 */
10572STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10573{
10574 LogFlowThisFunc(("\n"));
10575
10576 AutoCaller autoCaller(this);
10577 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10578
10579 /* endSavingState() need mParent lock */
10580 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10581
10582 AssertReturn( mData->mMachineState == MachineState_Saving
10583 && mSnapshotData.mLastState != MachineState_Null
10584 && !mSnapshotData.mProgressId.isEmpty()
10585 && !mSnapshotData.mStateFilePath.isEmpty(),
10586 E_FAIL);
10587
10588 /*
10589 * on success, set the state to Saved;
10590 * on failure, set the state to the state we had when BeginSavingState() was
10591 * called (this is expected by Console::SaveState() and
10592 * Console::saveStateThread())
10593 */
10594 if (aSuccess)
10595 setMachineState(MachineState_Saved);
10596 else
10597 setMachineState(mSnapshotData.mLastState);
10598
10599 return endSavingState(aSuccess);
10600}
10601
10602/**
10603 * @note Locks this object for writing.
10604 */
10605STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10606{
10607 LogFlowThisFunc(("\n"));
10608
10609 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10610
10611 AutoCaller autoCaller(this);
10612 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10613
10614 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10615
10616 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10617 || mData->mMachineState == MachineState_Teleported
10618 || mData->mMachineState == MachineState_Aborted
10619 , E_FAIL); /** @todo setError. */
10620
10621 Utf8Str stateFilePathFull = aSavedStateFile;
10622 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10623 if (RT_FAILURE(vrc))
10624 return setError(VBOX_E_FILE_ERROR,
10625 tr("Invalid saved state file path '%ls' (%Rrc)"),
10626 aSavedStateFile,
10627 vrc);
10628
10629 mSSData->mStateFilePath = stateFilePathFull;
10630
10631 /* The below setMachineState() will detect the state transition and will
10632 * update the settings file */
10633
10634 return setMachineState(MachineState_Saved);
10635}
10636
10637STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10638 ComSafeArrayOut(BSTR, aValues),
10639 ComSafeArrayOut(LONG64, aTimestamps),
10640 ComSafeArrayOut(BSTR, aFlags))
10641{
10642 LogFlowThisFunc(("\n"));
10643
10644#ifdef VBOX_WITH_GUEST_PROPS
10645 using namespace guestProp;
10646
10647 AutoCaller autoCaller(this);
10648 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10649
10650 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10651
10652 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10653 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10654 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10655 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10656
10657 size_t cEntries = mHWData->mGuestProperties.size();
10658 com::SafeArray<BSTR> names(cEntries);
10659 com::SafeArray<BSTR> values(cEntries);
10660 com::SafeArray<LONG64> timestamps(cEntries);
10661 com::SafeArray<BSTR> flags(cEntries);
10662 unsigned i = 0;
10663 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10664 it != mHWData->mGuestProperties.end();
10665 ++it)
10666 {
10667 char szFlags[MAX_FLAGS_LEN + 1];
10668 it->strName.cloneTo(&names[i]);
10669 it->strValue.cloneTo(&values[i]);
10670 timestamps[i] = it->mTimestamp;
10671 /* If it is NULL, keep it NULL. */
10672 if (it->mFlags)
10673 {
10674 writeFlags(it->mFlags, szFlags);
10675 Bstr(szFlags).cloneTo(&flags[i]);
10676 }
10677 else
10678 flags[i] = NULL;
10679 ++i;
10680 }
10681 names.detachTo(ComSafeArrayOutArg(aNames));
10682 values.detachTo(ComSafeArrayOutArg(aValues));
10683 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10684 flags.detachTo(ComSafeArrayOutArg(aFlags));
10685 return S_OK;
10686#else
10687 ReturnComNotImplemented();
10688#endif
10689}
10690
10691STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10692 IN_BSTR aValue,
10693 LONG64 aTimestamp,
10694 IN_BSTR aFlags)
10695{
10696 LogFlowThisFunc(("\n"));
10697
10698#ifdef VBOX_WITH_GUEST_PROPS
10699 using namespace guestProp;
10700
10701 CheckComArgStrNotEmptyOrNull(aName);
10702 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10703 return E_POINTER; /* aValue can be NULL to indicate deletion */
10704
10705 try
10706 {
10707 /*
10708 * Convert input up front.
10709 */
10710 Utf8Str utf8Name(aName);
10711 uint32_t fFlags = NILFLAG;
10712 if (aFlags)
10713 {
10714 Utf8Str utf8Flags(aFlags);
10715 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
10716 AssertRCReturn(vrc, E_INVALIDARG);
10717 }
10718
10719 /*
10720 * Now grab the object lock, validate the state and do the update.
10721 */
10722 AutoCaller autoCaller(this);
10723 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10724
10725 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10726
10727 switch (mData->mMachineState)
10728 {
10729 case MachineState_Paused:
10730 case MachineState_Running:
10731 case MachineState_Teleporting:
10732 case MachineState_TeleportingPausedVM:
10733 case MachineState_LiveSnapshotting:
10734 case MachineState_DeletingSnapshotOnline:
10735 case MachineState_DeletingSnapshotPaused:
10736 case MachineState_Saving:
10737 break;
10738
10739 default:
10740#ifndef DEBUG_sunlover
10741 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10742 VBOX_E_INVALID_VM_STATE);
10743#else
10744 return VBOX_E_INVALID_VM_STATE;
10745#endif
10746 }
10747
10748 setModified(IsModified_MachineData);
10749 mHWData.backup();
10750
10751 /** @todo r=bird: The careful memory handling doesn't work out here because
10752 * the catch block won't undo any damage we've done. So, if push_back throws
10753 * bad_alloc then you've lost the value.
10754 *
10755 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10756 * since values that changes actually bubbles to the end of the list. Using
10757 * something that has an efficient lookup and can tolerate a bit of updates
10758 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10759 * combination of RTStrCache (for sharing names and getting uniqueness into
10760 * the bargain) and hash/tree is another. */
10761 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10762 iter != mHWData->mGuestProperties.end();
10763 ++iter)
10764 if (utf8Name == iter->strName)
10765 {
10766 mHWData->mGuestProperties.erase(iter);
10767 mData->mGuestPropertiesModified = TRUE;
10768 break;
10769 }
10770 if (aValue != NULL)
10771 {
10772 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10773 mHWData->mGuestProperties.push_back(property);
10774 mData->mGuestPropertiesModified = TRUE;
10775 }
10776
10777 /*
10778 * Send a callback notification if appropriate
10779 */
10780 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10781 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
10782 RTSTR_MAX,
10783 utf8Name.c_str(),
10784 RTSTR_MAX, NULL)
10785 )
10786 {
10787 alock.leave();
10788
10789 mParent->onGuestPropertyChange(mData->mUuid,
10790 aName,
10791 aValue,
10792 aFlags);
10793 }
10794 }
10795 catch (...)
10796 {
10797 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10798 }
10799 return S_OK;
10800#else
10801 ReturnComNotImplemented();
10802#endif
10803}
10804
10805// public methods only for internal purposes
10806/////////////////////////////////////////////////////////////////////////////
10807
10808/**
10809 * Called from the client watcher thread to check for expected or unexpected
10810 * death of the client process that has a direct session to this machine.
10811 *
10812 * On Win32 and on OS/2, this method is called only when we've got the
10813 * mutex (i.e. the client has either died or terminated normally) so it always
10814 * returns @c true (the client is terminated, the session machine is
10815 * uninitialized).
10816 *
10817 * On other platforms, the method returns @c true if the client process has
10818 * terminated normally or abnormally and the session machine was uninitialized,
10819 * and @c false if the client process is still alive.
10820 *
10821 * @note Locks this object for writing.
10822 */
10823bool SessionMachine::checkForDeath()
10824{
10825 Uninit::Reason reason;
10826 bool terminated = false;
10827
10828 /* Enclose autoCaller with a block because calling uninit() from under it
10829 * will deadlock. */
10830 {
10831 AutoCaller autoCaller(this);
10832 if (!autoCaller.isOk())
10833 {
10834 /* return true if not ready, to cause the client watcher to exclude
10835 * the corresponding session from watching */
10836 LogFlowThisFunc(("Already uninitialized!\n"));
10837 return true;
10838 }
10839
10840 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10841
10842 /* Determine the reason of death: if the session state is Closing here,
10843 * everything is fine. Otherwise it means that the client did not call
10844 * OnSessionEnd() before it released the IPC semaphore. This may happen
10845 * either because the client process has abnormally terminated, or
10846 * because it simply forgot to call ISession::Close() before exiting. We
10847 * threat the latter also as an abnormal termination (see
10848 * Session::uninit() for details). */
10849 reason = mData->mSession.mState == SessionState_Unlocking ?
10850 Uninit::Normal :
10851 Uninit::Abnormal;
10852
10853#if defined(RT_OS_WINDOWS)
10854
10855 AssertMsg(mIPCSem, ("semaphore must be created"));
10856
10857 /* release the IPC mutex */
10858 ::ReleaseMutex(mIPCSem);
10859
10860 terminated = true;
10861
10862#elif defined(RT_OS_OS2)
10863
10864 AssertMsg(mIPCSem, ("semaphore must be created"));
10865
10866 /* release the IPC mutex */
10867 ::DosReleaseMutexSem(mIPCSem);
10868
10869 terminated = true;
10870
10871#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10872
10873 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10874
10875 int val = ::semctl(mIPCSem, 0, GETVAL);
10876 if (val > 0)
10877 {
10878 /* the semaphore is signaled, meaning the session is terminated */
10879 terminated = true;
10880 }
10881
10882#else
10883# error "Port me!"
10884#endif
10885
10886 } /* AutoCaller block */
10887
10888 if (terminated)
10889 uninit(reason);
10890
10891 return terminated;
10892}
10893
10894/**
10895 * @note Locks this object for reading.
10896 */
10897HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10898{
10899 LogFlowThisFunc(("\n"));
10900
10901 AutoCaller autoCaller(this);
10902 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10903
10904 ComPtr<IInternalSessionControl> directControl;
10905 {
10906 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10907 directControl = mData->mSession.mDirectControl;
10908 }
10909
10910 /* ignore notifications sent after #OnSessionEnd() is called */
10911 if (!directControl)
10912 return S_OK;
10913
10914 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10915}
10916
10917/**
10918 * @note Locks this object for reading.
10919 */
10920HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10921{
10922 LogFlowThisFunc(("\n"));
10923
10924 AutoCaller autoCaller(this);
10925 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10926
10927 ComPtr<IInternalSessionControl> directControl;
10928 {
10929 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10930 directControl = mData->mSession.mDirectControl;
10931 }
10932
10933 /* ignore notifications sent after #OnSessionEnd() is called */
10934 if (!directControl)
10935 return S_OK;
10936
10937 return directControl->OnSerialPortChange(serialPort);
10938}
10939
10940/**
10941 * @note Locks this object for reading.
10942 */
10943HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10944{
10945 LogFlowThisFunc(("\n"));
10946
10947 AutoCaller autoCaller(this);
10948 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10949
10950 ComPtr<IInternalSessionControl> directControl;
10951 {
10952 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10953 directControl = mData->mSession.mDirectControl;
10954 }
10955
10956 /* ignore notifications sent after #OnSessionEnd() is called */
10957 if (!directControl)
10958 return S_OK;
10959
10960 return directControl->OnParallelPortChange(parallelPort);
10961}
10962
10963/**
10964 * @note Locks this object for reading.
10965 */
10966HRESULT SessionMachine::onStorageControllerChange()
10967{
10968 LogFlowThisFunc(("\n"));
10969
10970 AutoCaller autoCaller(this);
10971 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10972
10973 ComPtr<IInternalSessionControl> directControl;
10974 {
10975 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10976 directControl = mData->mSession.mDirectControl;
10977 }
10978
10979 /* ignore notifications sent after #OnSessionEnd() is called */
10980 if (!directControl)
10981 return S_OK;
10982
10983 return directControl->OnStorageControllerChange();
10984}
10985
10986/**
10987 * @note Locks this object for reading.
10988 */
10989HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10990{
10991 LogFlowThisFunc(("\n"));
10992
10993 AutoCaller autoCaller(this);
10994 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10995
10996 ComPtr<IInternalSessionControl> directControl;
10997 {
10998 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10999 directControl = mData->mSession.mDirectControl;
11000 }
11001
11002 /* ignore notifications sent after #OnSessionEnd() is called */
11003 if (!directControl)
11004 return S_OK;
11005
11006 return directControl->OnMediumChange(aAttachment, aForce);
11007}
11008
11009/**
11010 * @note Locks this object for reading.
11011 */
11012HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11013{
11014 LogFlowThisFunc(("\n"));
11015
11016 AutoCaller autoCaller(this);
11017 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11018
11019 ComPtr<IInternalSessionControl> directControl;
11020 {
11021 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11022 directControl = mData->mSession.mDirectControl;
11023 }
11024
11025 /* ignore notifications sent after #OnSessionEnd() is called */
11026 if (!directControl)
11027 return S_OK;
11028
11029 return directControl->OnCPUChange(aCPU, aRemove);
11030}
11031
11032HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11033{
11034 LogFlowThisFunc(("\n"));
11035
11036 AutoCaller autoCaller(this);
11037 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11038
11039 ComPtr<IInternalSessionControl> directControl;
11040 {
11041 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11042 directControl = mData->mSession.mDirectControl;
11043 }
11044
11045 /* ignore notifications sent after #OnSessionEnd() is called */
11046 if (!directControl)
11047 return S_OK;
11048
11049 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11050}
11051
11052/**
11053 * @note Locks this object for reading.
11054 */
11055HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11056{
11057 LogFlowThisFunc(("\n"));
11058
11059 AutoCaller autoCaller(this);
11060 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11061
11062 ComPtr<IInternalSessionControl> directControl;
11063 {
11064 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11065 directControl = mData->mSession.mDirectControl;
11066 }
11067
11068 /* ignore notifications sent after #OnSessionEnd() is called */
11069 if (!directControl)
11070 return S_OK;
11071
11072 return directControl->OnVRDEServerChange(aRestart);
11073}
11074
11075/**
11076 * @note Locks this object for reading.
11077 */
11078HRESULT SessionMachine::onUSBControllerChange()
11079{
11080 LogFlowThisFunc(("\n"));
11081
11082 AutoCaller autoCaller(this);
11083 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11084
11085 ComPtr<IInternalSessionControl> directControl;
11086 {
11087 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11088 directControl = mData->mSession.mDirectControl;
11089 }
11090
11091 /* ignore notifications sent after #OnSessionEnd() is called */
11092 if (!directControl)
11093 return S_OK;
11094
11095 return directControl->OnUSBControllerChange();
11096}
11097
11098/**
11099 * @note Locks this object for reading.
11100 */
11101HRESULT SessionMachine::onSharedFolderChange()
11102{
11103 LogFlowThisFunc(("\n"));
11104
11105 AutoCaller autoCaller(this);
11106 AssertComRCReturnRC(autoCaller.rc());
11107
11108 ComPtr<IInternalSessionControl> directControl;
11109 {
11110 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11111 directControl = mData->mSession.mDirectControl;
11112 }
11113
11114 /* ignore notifications sent after #OnSessionEnd() is called */
11115 if (!directControl)
11116 return S_OK;
11117
11118 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11119}
11120
11121/**
11122 * Returns @c true if this machine's USB controller reports it has a matching
11123 * filter for the given USB device and @c false otherwise.
11124 *
11125 * @note Caller must have requested machine read lock.
11126 */
11127bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11128{
11129 AutoCaller autoCaller(this);
11130 /* silently return if not ready -- this method may be called after the
11131 * direct machine session has been called */
11132 if (!autoCaller.isOk())
11133 return false;
11134
11135
11136#ifdef VBOX_WITH_USB
11137 switch (mData->mMachineState)
11138 {
11139 case MachineState_Starting:
11140 case MachineState_Restoring:
11141 case MachineState_TeleportingIn:
11142 case MachineState_Paused:
11143 case MachineState_Running:
11144 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11145 * elsewhere... */
11146 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11147 default: break;
11148 }
11149#else
11150 NOREF(aDevice);
11151 NOREF(aMaskedIfs);
11152#endif
11153 return false;
11154}
11155
11156/**
11157 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11158 */
11159HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11160 IVirtualBoxErrorInfo *aError,
11161 ULONG aMaskedIfs)
11162{
11163 LogFlowThisFunc(("\n"));
11164
11165 AutoCaller autoCaller(this);
11166
11167 /* This notification may happen after the machine object has been
11168 * uninitialized (the session was closed), so don't assert. */
11169 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11170
11171 ComPtr<IInternalSessionControl> directControl;
11172 {
11173 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11174 directControl = mData->mSession.mDirectControl;
11175 }
11176
11177 /* fail on notifications sent after #OnSessionEnd() is called, it is
11178 * expected by the caller */
11179 if (!directControl)
11180 return E_FAIL;
11181
11182 /* No locks should be held at this point. */
11183 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11184 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11185
11186 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
11187}
11188
11189/**
11190 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11191 */
11192HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
11193 IVirtualBoxErrorInfo *aError)
11194{
11195 LogFlowThisFunc(("\n"));
11196
11197 AutoCaller autoCaller(this);
11198
11199 /* This notification may happen after the machine object has been
11200 * uninitialized (the session was closed), so don't assert. */
11201 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11202
11203 ComPtr<IInternalSessionControl> directControl;
11204 {
11205 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11206 directControl = mData->mSession.mDirectControl;
11207 }
11208
11209 /* fail on notifications sent after #OnSessionEnd() is called, it is
11210 * expected by the caller */
11211 if (!directControl)
11212 return E_FAIL;
11213
11214 /* No locks should be held at this point. */
11215 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11216 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11217
11218 return directControl->OnUSBDeviceDetach(aId, aError);
11219}
11220
11221// protected methods
11222/////////////////////////////////////////////////////////////////////////////
11223
11224/**
11225 * Helper method to finalize saving the state.
11226 *
11227 * @note Must be called from under this object's lock.
11228 *
11229 * @param aSuccess TRUE if the snapshot has been taken successfully
11230 *
11231 * @note Locks mParent + this objects for writing.
11232 */
11233HRESULT SessionMachine::endSavingState(BOOL aSuccess)
11234{
11235 LogFlowThisFuncEnter();
11236
11237 AutoCaller autoCaller(this);
11238 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11239
11240 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11241
11242 HRESULT rc = S_OK;
11243
11244 if (aSuccess)
11245 {
11246 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11247
11248 /* save all VM settings */
11249 rc = saveSettings(NULL);
11250 // no need to check whether VirtualBox.xml needs saving also since
11251 // we can't have a name change pending at this point
11252 }
11253 else
11254 {
11255 /* delete the saved state file (it might have been already created) */
11256 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11257 }
11258
11259 /* remove the completed progress object */
11260 mParent->removeProgress(mSnapshotData.mProgressId.ref());
11261
11262 /* clear out the temporary saved state data */
11263 mSnapshotData.mLastState = MachineState_Null;
11264 mSnapshotData.mProgressId.clear();
11265 mSnapshotData.mStateFilePath.setNull();
11266
11267 LogFlowThisFuncLeave();
11268 return rc;
11269}
11270
11271/**
11272 * Locks the attached media.
11273 *
11274 * All attached hard disks are locked for writing and DVD/floppy are locked for
11275 * reading. Parents of attached hard disks (if any) are locked for reading.
11276 *
11277 * This method also performs accessibility check of all media it locks: if some
11278 * media is inaccessible, the method will return a failure and a bunch of
11279 * extended error info objects per each inaccessible medium.
11280 *
11281 * Note that this method is atomic: if it returns a success, all media are
11282 * locked as described above; on failure no media is locked at all (all
11283 * succeeded individual locks will be undone).
11284 *
11285 * This method is intended to be called when the machine is in Starting or
11286 * Restoring state and asserts otherwise.
11287 *
11288 * The locks made by this method must be undone by calling #unlockMedia() when
11289 * no more needed.
11290 */
11291HRESULT SessionMachine::lockMedia()
11292{
11293 AutoCaller autoCaller(this);
11294 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11295
11296 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11297
11298 AssertReturn( mData->mMachineState == MachineState_Starting
11299 || mData->mMachineState == MachineState_Restoring
11300 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11301 /* bail out if trying to lock things with already set up locking */
11302 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11303
11304 MultiResult mrc(S_OK);
11305
11306 /* Collect locking information for all medium objects attached to the VM. */
11307 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11308 it != mMediaData->mAttachments.end();
11309 ++it)
11310 {
11311 MediumAttachment* pAtt = *it;
11312 DeviceType_T devType = pAtt->getType();
11313 Medium *pMedium = pAtt->getMedium();
11314
11315 MediumLockList *pMediumLockList(new MediumLockList());
11316 // There can be attachments without a medium (floppy/dvd), and thus
11317 // it's impossible to create a medium lock list. It still makes sense
11318 // to have the empty medium lock list in the map in case a medium is
11319 // attached later.
11320 if (pMedium != NULL)
11321 {
11322 MediumType_T mediumType = pMedium->getType();
11323 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
11324 || mediumType == MediumType_Shareable;
11325 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11326
11327 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11328 !fIsReadOnlyLock /* fMediumLockWrite */,
11329 NULL,
11330 *pMediumLockList);
11331 if (FAILED(mrc))
11332 {
11333 delete pMediumLockList;
11334 mData->mSession.mLockedMedia.Clear();
11335 break;
11336 }
11337 }
11338
11339 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11340 if (FAILED(rc))
11341 {
11342 mData->mSession.mLockedMedia.Clear();
11343 mrc = setError(rc,
11344 tr("Collecting locking information for all attached media failed"));
11345 break;
11346 }
11347 }
11348
11349 if (SUCCEEDED(mrc))
11350 {
11351 /* Now lock all media. If this fails, nothing is locked. */
11352 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11353 if (FAILED(rc))
11354 {
11355 mrc = setError(rc,
11356 tr("Locking of attached media failed"));
11357 }
11358 }
11359
11360 return mrc;
11361}
11362
11363/**
11364 * Undoes the locks made by by #lockMedia().
11365 */
11366void SessionMachine::unlockMedia()
11367{
11368 AutoCaller autoCaller(this);
11369 AssertComRCReturnVoid(autoCaller.rc());
11370
11371 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11372
11373 /* we may be holding important error info on the current thread;
11374 * preserve it */
11375 ErrorInfoKeeper eik;
11376
11377 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11378 AssertComRC(rc);
11379}
11380
11381/**
11382 * Helper to change the machine state (reimplementation).
11383 *
11384 * @note Locks this object for writing.
11385 */
11386HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11387{
11388 LogFlowThisFuncEnter();
11389 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11390
11391 AutoCaller autoCaller(this);
11392 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11393
11394 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11395
11396 MachineState_T oldMachineState = mData->mMachineState;
11397
11398 AssertMsgReturn(oldMachineState != aMachineState,
11399 ("oldMachineState=%s, aMachineState=%s\n",
11400 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11401 E_FAIL);
11402
11403 HRESULT rc = S_OK;
11404
11405 int stsFlags = 0;
11406 bool deleteSavedState = false;
11407
11408 /* detect some state transitions */
11409
11410 if ( ( oldMachineState == MachineState_Saved
11411 && aMachineState == MachineState_Restoring)
11412 || ( ( oldMachineState == MachineState_PoweredOff
11413 || oldMachineState == MachineState_Teleported
11414 || oldMachineState == MachineState_Aborted
11415 )
11416 && ( aMachineState == MachineState_TeleportingIn
11417 || aMachineState == MachineState_Starting
11418 )
11419 )
11420 )
11421 {
11422 /* The EMT thread is about to start */
11423
11424 /* Nothing to do here for now... */
11425
11426 /// @todo NEWMEDIA don't let mDVDDrive and other children
11427 /// change anything when in the Starting/Restoring state
11428 }
11429 else if ( ( oldMachineState == MachineState_Running
11430 || oldMachineState == MachineState_Paused
11431 || oldMachineState == MachineState_Teleporting
11432 || oldMachineState == MachineState_LiveSnapshotting
11433 || oldMachineState == MachineState_Stuck
11434 || oldMachineState == MachineState_Starting
11435 || oldMachineState == MachineState_Stopping
11436 || oldMachineState == MachineState_Saving
11437 || oldMachineState == MachineState_Restoring
11438 || oldMachineState == MachineState_TeleportingPausedVM
11439 || oldMachineState == MachineState_TeleportingIn
11440 )
11441 && ( aMachineState == MachineState_PoweredOff
11442 || aMachineState == MachineState_Saved
11443 || aMachineState == MachineState_Teleported
11444 || aMachineState == MachineState_Aborted
11445 )
11446 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11447 * snapshot */
11448 && ( mSnapshotData.mSnapshot.isNull()
11449 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11450 )
11451 )
11452 {
11453 /* The EMT thread has just stopped, unlock attached media. Note that as
11454 * opposed to locking that is done from Console, we do unlocking here
11455 * because the VM process may have aborted before having a chance to
11456 * properly unlock all media it locked. */
11457
11458 unlockMedia();
11459 }
11460
11461 if (oldMachineState == MachineState_Restoring)
11462 {
11463 if (aMachineState != MachineState_Saved)
11464 {
11465 /*
11466 * delete the saved state file once the machine has finished
11467 * restoring from it (note that Console sets the state from
11468 * Restoring to Saved if the VM couldn't restore successfully,
11469 * to give the user an ability to fix an error and retry --
11470 * we keep the saved state file in this case)
11471 */
11472 deleteSavedState = true;
11473 }
11474 }
11475 else if ( oldMachineState == MachineState_Saved
11476 && ( aMachineState == MachineState_PoweredOff
11477 || aMachineState == MachineState_Aborted
11478 || aMachineState == MachineState_Teleported
11479 )
11480 )
11481 {
11482 /*
11483 * delete the saved state after Console::ForgetSavedState() is called
11484 * or if the VM process (owning a direct VM session) crashed while the
11485 * VM was Saved
11486 */
11487
11488 /// @todo (dmik)
11489 // Not sure that deleting the saved state file just because of the
11490 // client death before it attempted to restore the VM is a good
11491 // thing. But when it crashes we need to go to the Aborted state
11492 // which cannot have the saved state file associated... The only
11493 // way to fix this is to make the Aborted condition not a VM state
11494 // but a bool flag: i.e., when a crash occurs, set it to true and
11495 // change the state to PoweredOff or Saved depending on the
11496 // saved state presence.
11497
11498 deleteSavedState = true;
11499 mData->mCurrentStateModified = TRUE;
11500 stsFlags |= SaveSTS_CurStateModified;
11501 }
11502
11503 if ( aMachineState == MachineState_Starting
11504 || aMachineState == MachineState_Restoring
11505 || aMachineState == MachineState_TeleportingIn
11506 )
11507 {
11508 /* set the current state modified flag to indicate that the current
11509 * state is no more identical to the state in the
11510 * current snapshot */
11511 if (!mData->mCurrentSnapshot.isNull())
11512 {
11513 mData->mCurrentStateModified = TRUE;
11514 stsFlags |= SaveSTS_CurStateModified;
11515 }
11516 }
11517
11518 if (deleteSavedState)
11519 {
11520 if (mRemoveSavedState)
11521 {
11522 Assert(!mSSData->mStateFilePath.isEmpty());
11523 RTFileDelete(mSSData->mStateFilePath.c_str());
11524 }
11525 mSSData->mStateFilePath.setNull();
11526 stsFlags |= SaveSTS_StateFilePath;
11527 }
11528
11529 /* redirect to the underlying peer machine */
11530 mPeer->setMachineState(aMachineState);
11531
11532 if ( aMachineState == MachineState_PoweredOff
11533 || aMachineState == MachineState_Teleported
11534 || aMachineState == MachineState_Aborted
11535 || aMachineState == MachineState_Saved)
11536 {
11537 /* the machine has stopped execution
11538 * (or the saved state file was adopted) */
11539 stsFlags |= SaveSTS_StateTimeStamp;
11540 }
11541
11542 if ( ( oldMachineState == MachineState_PoweredOff
11543 || oldMachineState == MachineState_Aborted
11544 || oldMachineState == MachineState_Teleported
11545 )
11546 && aMachineState == MachineState_Saved)
11547 {
11548 /* the saved state file was adopted */
11549 Assert(!mSSData->mStateFilePath.isEmpty());
11550 stsFlags |= SaveSTS_StateFilePath;
11551 }
11552
11553#ifdef VBOX_WITH_GUEST_PROPS
11554 if ( aMachineState == MachineState_PoweredOff
11555 || aMachineState == MachineState_Aborted
11556 || aMachineState == MachineState_Teleported)
11557 {
11558 /* Make sure any transient guest properties get removed from the
11559 * property store on shutdown. */
11560
11561 HWData::GuestPropertyList::iterator it;
11562 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11563 if (!fNeedsSaving)
11564 for (it = mHWData->mGuestProperties.begin();
11565 it != mHWData->mGuestProperties.end(); ++it)
11566 if (it->mFlags & guestProp::TRANSIENT)
11567 {
11568 fNeedsSaving = true;
11569 break;
11570 }
11571 if (fNeedsSaving)
11572 {
11573 mData->mCurrentStateModified = TRUE;
11574 stsFlags |= SaveSTS_CurStateModified;
11575 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11576 }
11577 }
11578#endif
11579
11580 rc = saveStateSettings(stsFlags);
11581
11582 if ( ( oldMachineState != MachineState_PoweredOff
11583 && oldMachineState != MachineState_Aborted
11584 && oldMachineState != MachineState_Teleported
11585 )
11586 && ( aMachineState == MachineState_PoweredOff
11587 || aMachineState == MachineState_Aborted
11588 || aMachineState == MachineState_Teleported
11589 )
11590 )
11591 {
11592 /* we've been shut down for any reason */
11593 /* no special action so far */
11594 }
11595
11596 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11597 LogFlowThisFuncLeave();
11598 return rc;
11599}
11600
11601/**
11602 * Sends the current machine state value to the VM process.
11603 *
11604 * @note Locks this object for reading, then calls a client process.
11605 */
11606HRESULT SessionMachine::updateMachineStateOnClient()
11607{
11608 AutoCaller autoCaller(this);
11609 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11610
11611 ComPtr<IInternalSessionControl> directControl;
11612 {
11613 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11614 AssertReturn(!!mData, E_FAIL);
11615 directControl = mData->mSession.mDirectControl;
11616
11617 /* directControl may be already set to NULL here in #OnSessionEnd()
11618 * called too early by the direct session process while there is still
11619 * some operation (like deleting the snapshot) in progress. The client
11620 * process in this case is waiting inside Session::close() for the
11621 * "end session" process object to complete, while #uninit() called by
11622 * #checkForDeath() on the Watcher thread is waiting for the pending
11623 * operation to complete. For now, we accept this inconsistent behavior
11624 * and simply do nothing here. */
11625
11626 if (mData->mSession.mState == SessionState_Unlocking)
11627 return S_OK;
11628
11629 AssertReturn(!directControl.isNull(), E_FAIL);
11630 }
11631
11632 return directControl->UpdateMachineState(mData->mMachineState);
11633}
Note: See TracBrowser for help on using the repository browser.

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