VirtualBox

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

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

Main: use paths relative to machine folder in machine registries

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

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