VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MachineImpl.cpp@ 37554

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

Main: tabs

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