VirtualBox

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

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

Main-CloneVM: factor out the clone VM task

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 415.7 KB
Line 
1/* $Id: MachineImpl.cpp 37491 2011-06-16 12:23: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, BOOL fFullClone, IProgress **pProgress)
6077{
6078 LogFlowFuncEnter();
6079
6080 CheckComArgNotNull(pTarget);
6081 CheckComArgOutPointerValid(pProgress);
6082 AssertReturn(!fFullClone, E_NOTIMPL);
6083
6084 AutoCaller autoCaller(this);
6085 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6086
6087 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), mode, fFullClone);
6088
6089 HRESULT rc = pWorker->start(pProgress);
6090
6091 LogFlowFuncLeave();
6092
6093 return rc;
6094}
6095
6096// public methods for internal purposes
6097/////////////////////////////////////////////////////////////////////////////
6098
6099/**
6100 * Adds the given IsModified_* flag to the dirty flags of the machine.
6101 * This must be called either during loadSettings or under the machine write lock.
6102 * @param fl
6103 */
6104void Machine::setModified(uint32_t fl)
6105{
6106 mData->flModifications |= fl;
6107}
6108
6109/**
6110 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
6111 * care of the write locking.
6112 *
6113 * @param fModifications The flag to add.
6114 */
6115void Machine::setModifiedLock(uint32_t fModification)
6116{
6117 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6118 mData->flModifications |= fModification;
6119}
6120
6121/**
6122 * Saves the registry entry of this machine to the given configuration node.
6123 *
6124 * @param aEntryNode Node to save the registry entry to.
6125 *
6126 * @note locks this object for reading.
6127 */
6128HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
6129{
6130 AutoLimitedCaller autoCaller(this);
6131 AssertComRCReturnRC(autoCaller.rc());
6132
6133 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6134
6135 data.uuid = mData->mUuid;
6136 data.strSettingsFile = mData->m_strConfigFile;
6137
6138 return S_OK;
6139}
6140
6141/**
6142 * Calculates the absolute path of the given path taking the directory of the
6143 * machine settings file as the current directory.
6144 *
6145 * @param aPath Path to calculate the absolute path for.
6146 * @param aResult Where to put the result (used only on success, can be the
6147 * same Utf8Str instance as passed in @a aPath).
6148 * @return IPRT result.
6149 *
6150 * @note Locks this object for reading.
6151 */
6152int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
6153{
6154 AutoCaller autoCaller(this);
6155 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6156
6157 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6158
6159 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
6160
6161 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
6162
6163 strSettingsDir.stripFilename();
6164 char folder[RTPATH_MAX];
6165 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
6166 if (RT_SUCCESS(vrc))
6167 aResult = folder;
6168
6169 return vrc;
6170}
6171
6172/**
6173 * Copies strSource to strTarget, making it relative to the machine folder
6174 * if it is a subdirectory thereof, or simply copying it otherwise.
6175 *
6176 * @param strSource Path to evaluate and copy.
6177 * @param strTarget Buffer to receive target path.
6178 *
6179 * @note Locks this object for reading.
6180 */
6181void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6182 Utf8Str &strTarget)
6183{
6184 AutoCaller autoCaller(this);
6185 AssertComRCReturn(autoCaller.rc(), (void)0);
6186
6187 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6188
6189 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6190 // use strTarget as a temporary buffer to hold the machine settings dir
6191 strTarget = mData->m_strConfigFileFull;
6192 strTarget.stripFilename();
6193 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6194 {
6195 // is relative: then append what's left
6196 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6197 // for empty paths (only possible for subdirs) use "." to avoid
6198 // triggering default settings for not present config attributes.
6199 if (strTarget.isEmpty())
6200 strTarget = ".";
6201 }
6202 else
6203 // is not relative: then overwrite
6204 strTarget = strSource;
6205}
6206
6207/**
6208 * Returns the full path to the machine's log folder in the
6209 * \a aLogFolder argument.
6210 */
6211void Machine::getLogFolder(Utf8Str &aLogFolder)
6212{
6213 AutoCaller autoCaller(this);
6214 AssertComRCReturnVoid(autoCaller.rc());
6215
6216 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6217
6218 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6219 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6220 aLogFolder.append(RTPATH_DELIMITER);
6221 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6222}
6223
6224/**
6225 * Returns the full path to the machine's log file for an given index.
6226 */
6227Utf8Str Machine::queryLogFilename(ULONG idx)
6228{
6229 Utf8Str logFolder;
6230 getLogFolder(logFolder);
6231 Assert(logFolder.length());
6232 Utf8Str log;
6233 if (idx == 0)
6234 log = Utf8StrFmt("%s%cVBox.log",
6235 logFolder.c_str(), RTPATH_DELIMITER);
6236 else
6237 log = Utf8StrFmt("%s%cVBox.log.%d",
6238 logFolder.c_str(), RTPATH_DELIMITER, idx);
6239 return log;
6240}
6241
6242/**
6243 * Composes a unique saved state filename based on the current system time. The filename is
6244 * granular to the second so this will work so long as no more than one snapshot is taken on
6245 * a machine per second.
6246 *
6247 * Before version 4.1, we used this formula for saved state files:
6248 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6249 * which no longer works because saved state files can now be shared between the saved state of the
6250 * "saved" machine and an online snapshot, and the following would cause problems:
6251 * 1) save machine
6252 * 2) create online snapshot from that machine state --> reusing saved state file
6253 * 3) save machine again --> filename would be reused, breaking the online snapshot
6254 *
6255 * So instead we now use a timestamp.
6256 *
6257 * @param str
6258 */
6259void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6260{
6261 AutoCaller autoCaller(this);
6262 AssertComRCReturnVoid(autoCaller.rc());
6263
6264 {
6265 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6266 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6267 }
6268
6269 RTTIMESPEC ts;
6270 RTTimeNow(&ts);
6271 RTTIME time;
6272 RTTimeExplode(&time, &ts);
6273
6274 strStateFilePath += RTPATH_DELIMITER;
6275 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
6276 time.i32Year, time.u8Month, time.u8MonthDay,
6277 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
6278}
6279
6280/**
6281 * @note Locks this object for writing, calls the client process
6282 * (inside the lock).
6283 */
6284HRESULT Machine::launchVMProcess(IInternalSessionControl *aControl,
6285 const Utf8Str &strType,
6286 const Utf8Str &strEnvironment,
6287 ProgressProxy *aProgress)
6288{
6289 LogFlowThisFuncEnter();
6290
6291 AssertReturn(aControl, E_FAIL);
6292 AssertReturn(aProgress, E_FAIL);
6293
6294 AutoCaller autoCaller(this);
6295 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6296
6297 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6298
6299 if (!mData->mRegistered)
6300 return setError(E_UNEXPECTED,
6301 tr("The machine '%s' is not registered"),
6302 mUserData->s.strName.c_str());
6303
6304 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6305
6306 if ( mData->mSession.mState == SessionState_Locked
6307 || mData->mSession.mState == SessionState_Spawning
6308 || mData->mSession.mState == SessionState_Unlocking)
6309 return setError(VBOX_E_INVALID_OBJECT_STATE,
6310 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6311 mUserData->s.strName.c_str());
6312
6313 /* may not be busy */
6314 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6315
6316 /* get the path to the executable */
6317 char szPath[RTPATH_MAX];
6318 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6319 size_t sz = strlen(szPath);
6320 szPath[sz++] = RTPATH_DELIMITER;
6321 szPath[sz] = 0;
6322 char *cmd = szPath + sz;
6323 sz = RTPATH_MAX - sz;
6324
6325 int vrc = VINF_SUCCESS;
6326 RTPROCESS pid = NIL_RTPROCESS;
6327
6328 RTENV env = RTENV_DEFAULT;
6329
6330 if (!strEnvironment.isEmpty())
6331 {
6332 char *newEnvStr = NULL;
6333
6334 do
6335 {
6336 /* clone the current environment */
6337 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6338 AssertRCBreakStmt(vrc2, vrc = vrc2);
6339
6340 newEnvStr = RTStrDup(strEnvironment.c_str());
6341 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6342
6343 /* put new variables to the environment
6344 * (ignore empty variable names here since RTEnv API
6345 * intentionally doesn't do that) */
6346 char *var = newEnvStr;
6347 for (char *p = newEnvStr; *p; ++p)
6348 {
6349 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6350 {
6351 *p = '\0';
6352 if (*var)
6353 {
6354 char *val = strchr(var, '=');
6355 if (val)
6356 {
6357 *val++ = '\0';
6358 vrc2 = RTEnvSetEx(env, var, val);
6359 }
6360 else
6361 vrc2 = RTEnvUnsetEx(env, var);
6362 if (RT_FAILURE(vrc2))
6363 break;
6364 }
6365 var = p + 1;
6366 }
6367 }
6368 if (RT_SUCCESS(vrc2) && *var)
6369 vrc2 = RTEnvPutEx(env, var);
6370
6371 AssertRCBreakStmt(vrc2, vrc = vrc2);
6372 }
6373 while (0);
6374
6375 if (newEnvStr != NULL)
6376 RTStrFree(newEnvStr);
6377 }
6378
6379 /* Qt is default */
6380#ifdef VBOX_WITH_QTGUI
6381 if (strType == "gui" || strType == "GUI/Qt")
6382 {
6383# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6384 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6385# else
6386 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6387# endif
6388 Assert(sz >= sizeof(VirtualBox_exe));
6389 strcpy(cmd, VirtualBox_exe);
6390
6391 Utf8Str idStr = mData->mUuid.toString();
6392 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6393 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6394 }
6395#else /* !VBOX_WITH_QTGUI */
6396 if (0)
6397 ;
6398#endif /* VBOX_WITH_QTGUI */
6399
6400 else
6401
6402#ifdef VBOX_WITH_VBOXSDL
6403 if (strType == "sdl" || strType == "GUI/SDL")
6404 {
6405 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6406 Assert(sz >= sizeof(VBoxSDL_exe));
6407 strcpy(cmd, VBoxSDL_exe);
6408
6409 Utf8Str idStr = mData->mUuid.toString();
6410 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6411 fprintf(stderr, "SDL=%s\n", szPath);
6412 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6413 }
6414#else /* !VBOX_WITH_VBOXSDL */
6415 if (0)
6416 ;
6417#endif /* !VBOX_WITH_VBOXSDL */
6418
6419 else
6420
6421#ifdef VBOX_WITH_HEADLESS
6422 if ( strType == "headless"
6423 || strType == "capture"
6424 || strType == "vrdp" /* Deprecated. Same as headless. */
6425 )
6426 {
6427 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6428 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6429 * and a VM works even if the server has not been installed.
6430 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6431 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6432 * differently in 4.0 and 3.x.
6433 */
6434 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6435 Assert(sz >= sizeof(VBoxHeadless_exe));
6436 strcpy(cmd, VBoxHeadless_exe);
6437
6438 Utf8Str idStr = mData->mUuid.toString();
6439 /* Leave space for "--capture" arg. */
6440 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
6441 "--startvm", idStr.c_str(),
6442 "--vrde", "config",
6443 0, /* For "--capture". */
6444 0 };
6445 if (strType == "capture")
6446 {
6447 unsigned pos = RT_ELEMENTS(args) - 2;
6448 args[pos] = "--capture";
6449 }
6450 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6451 }
6452#else /* !VBOX_WITH_HEADLESS */
6453 if (0)
6454 ;
6455#endif /* !VBOX_WITH_HEADLESS */
6456 else
6457 {
6458 RTEnvDestroy(env);
6459 return setError(E_INVALIDARG,
6460 tr("Invalid session type: '%s'"),
6461 strType.c_str());
6462 }
6463
6464 RTEnvDestroy(env);
6465
6466 if (RT_FAILURE(vrc))
6467 return setError(VBOX_E_IPRT_ERROR,
6468 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6469 mUserData->s.strName.c_str(), vrc);
6470
6471 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6472
6473 /*
6474 * Note that we don't leave the lock here before calling the client,
6475 * because it doesn't need to call us back if called with a NULL argument.
6476 * Leaving the lock here is dangerous because we didn't prepare the
6477 * launch data yet, but the client we've just started may happen to be
6478 * too fast and call openSession() that will fail (because of PID, etc.),
6479 * so that the Machine will never get out of the Spawning session state.
6480 */
6481
6482 /* inform the session that it will be a remote one */
6483 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6484 HRESULT rc = aControl->AssignMachine(NULL);
6485 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6486
6487 if (FAILED(rc))
6488 {
6489 /* restore the session state */
6490 mData->mSession.mState = SessionState_Unlocked;
6491 /* The failure may occur w/o any error info (from RPC), so provide one */
6492 return setError(VBOX_E_VM_ERROR,
6493 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6494 }
6495
6496 /* attach launch data to the machine */
6497 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6498 mData->mSession.mRemoteControls.push_back (aControl);
6499 mData->mSession.mProgress = aProgress;
6500 mData->mSession.mPid = pid;
6501 mData->mSession.mState = SessionState_Spawning;
6502 mData->mSession.mType = strType;
6503
6504 LogFlowThisFuncLeave();
6505 return S_OK;
6506}
6507
6508/**
6509 * Returns @c true if the given machine has an open direct session and returns
6510 * the session machine instance and additional session data (on some platforms)
6511 * if so.
6512 *
6513 * Note that when the method returns @c false, the arguments remain unchanged.
6514 *
6515 * @param aMachine Session machine object.
6516 * @param aControl Direct session control object (optional).
6517 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6518 *
6519 * @note locks this object for reading.
6520 */
6521#if defined(RT_OS_WINDOWS)
6522bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6523 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6524 HANDLE *aIPCSem /*= NULL*/,
6525 bool aAllowClosing /*= false*/)
6526#elif defined(RT_OS_OS2)
6527bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6528 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6529 HMTX *aIPCSem /*= NULL*/,
6530 bool aAllowClosing /*= false*/)
6531#else
6532bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6533 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6534 bool aAllowClosing /*= false*/)
6535#endif
6536{
6537 AutoLimitedCaller autoCaller(this);
6538 AssertComRCReturn(autoCaller.rc(), false);
6539
6540 /* just return false for inaccessible machines */
6541 if (autoCaller.state() != Ready)
6542 return false;
6543
6544 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6545
6546 if ( mData->mSession.mState == SessionState_Locked
6547 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6548 )
6549 {
6550 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6551
6552 aMachine = mData->mSession.mMachine;
6553
6554 if (aControl != NULL)
6555 *aControl = mData->mSession.mDirectControl;
6556
6557#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6558 /* Additional session data */
6559 if (aIPCSem != NULL)
6560 *aIPCSem = aMachine->mIPCSem;
6561#endif
6562 return true;
6563 }
6564
6565 return false;
6566}
6567
6568/**
6569 * Returns @c true if the given machine has an spawning direct session and
6570 * returns and additional session data (on some platforms) if so.
6571 *
6572 * Note that when the method returns @c false, the arguments remain unchanged.
6573 *
6574 * @param aPID PID of the spawned direct session process.
6575 *
6576 * @note locks this object for reading.
6577 */
6578#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6579bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6580#else
6581bool Machine::isSessionSpawning()
6582#endif
6583{
6584 AutoLimitedCaller autoCaller(this);
6585 AssertComRCReturn(autoCaller.rc(), false);
6586
6587 /* just return false for inaccessible machines */
6588 if (autoCaller.state() != Ready)
6589 return false;
6590
6591 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6592
6593 if (mData->mSession.mState == SessionState_Spawning)
6594 {
6595#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6596 /* Additional session data */
6597 if (aPID != NULL)
6598 {
6599 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6600 *aPID = mData->mSession.mPid;
6601 }
6602#endif
6603 return true;
6604 }
6605
6606 return false;
6607}
6608
6609/**
6610 * Called from the client watcher thread to check for unexpected client process
6611 * death during Session_Spawning state (e.g. before it successfully opened a
6612 * direct session).
6613 *
6614 * On Win32 and on OS/2, this method is called only when we've got the
6615 * direct client's process termination notification, so it always returns @c
6616 * true.
6617 *
6618 * On other platforms, this method returns @c true if the client process is
6619 * terminated and @c false if it's still alive.
6620 *
6621 * @note Locks this object for writing.
6622 */
6623bool Machine::checkForSpawnFailure()
6624{
6625 AutoCaller autoCaller(this);
6626 if (!autoCaller.isOk())
6627 {
6628 /* nothing to do */
6629 LogFlowThisFunc(("Already uninitialized!\n"));
6630 return true;
6631 }
6632
6633 /* VirtualBox::addProcessToReap() needs a write lock */
6634 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6635
6636 if (mData->mSession.mState != SessionState_Spawning)
6637 {
6638 /* nothing to do */
6639 LogFlowThisFunc(("Not spawning any more!\n"));
6640 return true;
6641 }
6642
6643 HRESULT rc = S_OK;
6644
6645#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6646
6647 /* the process was already unexpectedly terminated, we just need to set an
6648 * error and finalize session spawning */
6649 rc = setError(E_FAIL,
6650 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6651 getName().c_str());
6652#else
6653
6654 /* PID not yet initialized, skip check. */
6655 if (mData->mSession.mPid == NIL_RTPROCESS)
6656 return false;
6657
6658 RTPROCSTATUS status;
6659 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6660 &status);
6661
6662 if (vrc != VERR_PROCESS_RUNNING)
6663 {
6664 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6665 rc = setError(E_FAIL,
6666 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6667 getName().c_str(), status.iStatus);
6668 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6669 rc = setError(E_FAIL,
6670 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6671 getName().c_str(), status.iStatus);
6672 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6673 rc = setError(E_FAIL,
6674 tr("The virtual machine '%s' has terminated abnormally"),
6675 getName().c_str(), status.iStatus);
6676 else
6677 rc = setError(E_FAIL,
6678 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6679 getName().c_str(), rc);
6680 }
6681
6682#endif
6683
6684 if (FAILED(rc))
6685 {
6686 /* Close the remote session, remove the remote control from the list
6687 * and reset session state to Closed (@note keep the code in sync with
6688 * the relevant part in checkForSpawnFailure()). */
6689
6690 Assert(mData->mSession.mRemoteControls.size() == 1);
6691 if (mData->mSession.mRemoteControls.size() == 1)
6692 {
6693 ErrorInfoKeeper eik;
6694 mData->mSession.mRemoteControls.front()->Uninitialize();
6695 }
6696
6697 mData->mSession.mRemoteControls.clear();
6698 mData->mSession.mState = SessionState_Unlocked;
6699
6700 /* finalize the progress after setting the state */
6701 if (!mData->mSession.mProgress.isNull())
6702 {
6703 mData->mSession.mProgress->notifyComplete(rc);
6704 mData->mSession.mProgress.setNull();
6705 }
6706
6707 mParent->addProcessToReap(mData->mSession.mPid);
6708 mData->mSession.mPid = NIL_RTPROCESS;
6709
6710 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6711 return true;
6712 }
6713
6714 return false;
6715}
6716
6717/**
6718 * Checks whether the machine can be registered. If so, commits and saves
6719 * all settings.
6720 *
6721 * @note Must be called from mParent's write lock. Locks this object and
6722 * children for writing.
6723 */
6724HRESULT Machine::prepareRegister()
6725{
6726 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6727
6728 AutoLimitedCaller autoCaller(this);
6729 AssertComRCReturnRC(autoCaller.rc());
6730
6731 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6732
6733 /* wait for state dependents to drop to zero */
6734 ensureNoStateDependencies();
6735
6736 if (!mData->mAccessible)
6737 return setError(VBOX_E_INVALID_OBJECT_STATE,
6738 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6739 mUserData->s.strName.c_str(),
6740 mData->mUuid.toString().c_str());
6741
6742 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6743
6744 if (mData->mRegistered)
6745 return setError(VBOX_E_INVALID_OBJECT_STATE,
6746 tr("The machine '%s' with UUID {%s} is already registered"),
6747 mUserData->s.strName.c_str(),
6748 mData->mUuid.toString().c_str());
6749
6750 HRESULT rc = S_OK;
6751
6752 // Ensure the settings are saved. If we are going to be registered and
6753 // no config file exists yet, create it by calling saveSettings() too.
6754 if ( (mData->flModifications)
6755 || (!mData->pMachineConfigFile->fileExists())
6756 )
6757 {
6758 rc = saveSettings(NULL);
6759 // no need to check whether VirtualBox.xml needs saving too since
6760 // we can't have a machine XML file rename pending
6761 if (FAILED(rc)) return rc;
6762 }
6763
6764 /* more config checking goes here */
6765
6766 if (SUCCEEDED(rc))
6767 {
6768 /* we may have had implicit modifications we want to fix on success */
6769 commit();
6770
6771 mData->mRegistered = true;
6772 }
6773 else
6774 {
6775 /* we may have had implicit modifications we want to cancel on failure*/
6776 rollback(false /* aNotify */);
6777 }
6778
6779 return rc;
6780}
6781
6782/**
6783 * Increases the number of objects dependent on the machine state or on the
6784 * registered state. Guarantees that these two states will not change at least
6785 * until #releaseStateDependency() is called.
6786 *
6787 * Depending on the @a aDepType value, additional state checks may be made.
6788 * These checks will set extended error info on failure. See
6789 * #checkStateDependency() for more info.
6790 *
6791 * If this method returns a failure, the dependency is not added and the caller
6792 * is not allowed to rely on any particular machine state or registration state
6793 * value and may return the failed result code to the upper level.
6794 *
6795 * @param aDepType Dependency type to add.
6796 * @param aState Current machine state (NULL if not interested).
6797 * @param aRegistered Current registered state (NULL if not interested).
6798 *
6799 * @note Locks this object for writing.
6800 */
6801HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6802 MachineState_T *aState /* = NULL */,
6803 BOOL *aRegistered /* = NULL */)
6804{
6805 AutoCaller autoCaller(this);
6806 AssertComRCReturnRC(autoCaller.rc());
6807
6808 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6809
6810 HRESULT rc = checkStateDependency(aDepType);
6811 if (FAILED(rc)) return rc;
6812
6813 {
6814 if (mData->mMachineStateChangePending != 0)
6815 {
6816 /* ensureNoStateDependencies() is waiting for state dependencies to
6817 * drop to zero so don't add more. It may make sense to wait a bit
6818 * and retry before reporting an error (since the pending state
6819 * transition should be really quick) but let's just assert for
6820 * now to see if it ever happens on practice. */
6821
6822 AssertFailed();
6823
6824 return setError(E_ACCESSDENIED,
6825 tr("Machine state change is in progress. Please retry the operation later."));
6826 }
6827
6828 ++mData->mMachineStateDeps;
6829 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6830 }
6831
6832 if (aState)
6833 *aState = mData->mMachineState;
6834 if (aRegistered)
6835 *aRegistered = mData->mRegistered;
6836
6837 return S_OK;
6838}
6839
6840/**
6841 * Decreases the number of objects dependent on the machine state.
6842 * Must always complete the #addStateDependency() call after the state
6843 * dependency is no more necessary.
6844 */
6845void Machine::releaseStateDependency()
6846{
6847 AutoCaller autoCaller(this);
6848 AssertComRCReturnVoid(autoCaller.rc());
6849
6850 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6851
6852 /* releaseStateDependency() w/o addStateDependency()? */
6853 AssertReturnVoid(mData->mMachineStateDeps != 0);
6854 -- mData->mMachineStateDeps;
6855
6856 if (mData->mMachineStateDeps == 0)
6857 {
6858 /* inform ensureNoStateDependencies() that there are no more deps */
6859 if (mData->mMachineStateChangePending != 0)
6860 {
6861 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6862 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6863 }
6864 }
6865}
6866
6867// protected methods
6868/////////////////////////////////////////////////////////////////////////////
6869
6870/**
6871 * Performs machine state checks based on the @a aDepType value. If a check
6872 * fails, this method will set extended error info, otherwise it will return
6873 * S_OK. It is supposed, that on failure, the caller will immediately return
6874 * the return value of this method to the upper level.
6875 *
6876 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6877 *
6878 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6879 * current state of this machine object allows to change settings of the
6880 * machine (i.e. the machine is not registered, or registered but not running
6881 * and not saved). It is useful to call this method from Machine setters
6882 * before performing any change.
6883 *
6884 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6885 * as for MutableStateDep except that if the machine is saved, S_OK is also
6886 * returned. This is useful in setters which allow changing machine
6887 * properties when it is in the saved state.
6888 *
6889 * @param aDepType Dependency type to check.
6890 *
6891 * @note Non Machine based classes should use #addStateDependency() and
6892 * #releaseStateDependency() methods or the smart AutoStateDependency
6893 * template.
6894 *
6895 * @note This method must be called from under this object's read or write
6896 * lock.
6897 */
6898HRESULT Machine::checkStateDependency(StateDependency aDepType)
6899{
6900 switch (aDepType)
6901 {
6902 case AnyStateDep:
6903 {
6904 break;
6905 }
6906 case MutableStateDep:
6907 {
6908 if ( mData->mRegistered
6909 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6910 || ( mData->mMachineState != MachineState_Paused
6911 && mData->mMachineState != MachineState_Running
6912 && mData->mMachineState != MachineState_Aborted
6913 && mData->mMachineState != MachineState_Teleported
6914 && mData->mMachineState != MachineState_PoweredOff
6915 )
6916 )
6917 )
6918 return setError(VBOX_E_INVALID_VM_STATE,
6919 tr("The machine is not mutable (state is %s)"),
6920 Global::stringifyMachineState(mData->mMachineState));
6921 break;
6922 }
6923 case MutableOrSavedStateDep:
6924 {
6925 if ( mData->mRegistered
6926 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6927 || ( mData->mMachineState != MachineState_Paused
6928 && mData->mMachineState != MachineState_Running
6929 && mData->mMachineState != MachineState_Aborted
6930 && mData->mMachineState != MachineState_Teleported
6931 && mData->mMachineState != MachineState_Saved
6932 && mData->mMachineState != MachineState_PoweredOff
6933 )
6934 )
6935 )
6936 return setError(VBOX_E_INVALID_VM_STATE,
6937 tr("The machine is not mutable (state is %s)"),
6938 Global::stringifyMachineState(mData->mMachineState));
6939 break;
6940 }
6941 }
6942
6943 return S_OK;
6944}
6945
6946/**
6947 * Helper to initialize all associated child objects and allocate data
6948 * structures.
6949 *
6950 * This method must be called as a part of the object's initialization procedure
6951 * (usually done in the #init() method).
6952 *
6953 * @note Must be called only from #init() or from #registeredInit().
6954 */
6955HRESULT Machine::initDataAndChildObjects()
6956{
6957 AutoCaller autoCaller(this);
6958 AssertComRCReturnRC(autoCaller.rc());
6959 AssertComRCReturn(autoCaller.state() == InInit ||
6960 autoCaller.state() == Limited, E_FAIL);
6961
6962 AssertReturn(!mData->mAccessible, E_FAIL);
6963
6964 /* allocate data structures */
6965 mSSData.allocate();
6966 mUserData.allocate();
6967 mHWData.allocate();
6968 mMediaData.allocate();
6969 mStorageControllers.allocate();
6970
6971 /* initialize mOSTypeId */
6972 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6973
6974 /* create associated BIOS settings object */
6975 unconst(mBIOSSettings).createObject();
6976 mBIOSSettings->init(this);
6977
6978 /* create an associated VRDE object (default is disabled) */
6979 unconst(mVRDEServer).createObject();
6980 mVRDEServer->init(this);
6981
6982 /* create associated serial port objects */
6983 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6984 {
6985 unconst(mSerialPorts[slot]).createObject();
6986 mSerialPorts[slot]->init(this, slot);
6987 }
6988
6989 /* create associated parallel port objects */
6990 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6991 {
6992 unconst(mParallelPorts[slot]).createObject();
6993 mParallelPorts[slot]->init(this, slot);
6994 }
6995
6996 /* create the audio adapter object (always present, default is disabled) */
6997 unconst(mAudioAdapter).createObject();
6998 mAudioAdapter->init(this);
6999
7000 /* create the USB controller object (always present, default is disabled) */
7001 unconst(mUSBController).createObject();
7002 mUSBController->init(this);
7003
7004 /* create associated network adapter objects */
7005 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
7006 {
7007 unconst(mNetworkAdapters[slot]).createObject();
7008 mNetworkAdapters[slot]->init(this, slot);
7009 }
7010
7011 /* create the bandwidth control */
7012 unconst(mBandwidthControl).createObject();
7013 mBandwidthControl->init(this);
7014
7015 return S_OK;
7016}
7017
7018/**
7019 * Helper to uninitialize all associated child objects and to free all data
7020 * structures.
7021 *
7022 * This method must be called as a part of the object's uninitialization
7023 * procedure (usually done in the #uninit() method).
7024 *
7025 * @note Must be called only from #uninit() or from #registeredInit().
7026 */
7027void Machine::uninitDataAndChildObjects()
7028{
7029 AutoCaller autoCaller(this);
7030 AssertComRCReturnVoid(autoCaller.rc());
7031 AssertComRCReturnVoid( autoCaller.state() == InUninit
7032 || autoCaller.state() == Limited);
7033
7034 /* tell all our other child objects we've been uninitialized */
7035 if (mBandwidthControl)
7036 {
7037 mBandwidthControl->uninit();
7038 unconst(mBandwidthControl).setNull();
7039 }
7040
7041 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
7042 {
7043 if (mNetworkAdapters[slot])
7044 {
7045 mNetworkAdapters[slot]->uninit();
7046 unconst(mNetworkAdapters[slot]).setNull();
7047 }
7048 }
7049
7050 if (mUSBController)
7051 {
7052 mUSBController->uninit();
7053 unconst(mUSBController).setNull();
7054 }
7055
7056 if (mAudioAdapter)
7057 {
7058 mAudioAdapter->uninit();
7059 unconst(mAudioAdapter).setNull();
7060 }
7061
7062 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7063 {
7064 if (mParallelPorts[slot])
7065 {
7066 mParallelPorts[slot]->uninit();
7067 unconst(mParallelPorts[slot]).setNull();
7068 }
7069 }
7070
7071 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7072 {
7073 if (mSerialPorts[slot])
7074 {
7075 mSerialPorts[slot]->uninit();
7076 unconst(mSerialPorts[slot]).setNull();
7077 }
7078 }
7079
7080 if (mVRDEServer)
7081 {
7082 mVRDEServer->uninit();
7083 unconst(mVRDEServer).setNull();
7084 }
7085
7086 if (mBIOSSettings)
7087 {
7088 mBIOSSettings->uninit();
7089 unconst(mBIOSSettings).setNull();
7090 }
7091
7092 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
7093 * instance is uninitialized; SessionMachine instances refer to real
7094 * Machine hard disks). This is necessary for a clean re-initialization of
7095 * the VM after successfully re-checking the accessibility state. Note
7096 * that in case of normal Machine or SnapshotMachine uninitialization (as
7097 * a result of unregistering or deleting the snapshot), outdated hard
7098 * disk attachments will already be uninitialized and deleted, so this
7099 * code will not affect them. */
7100 if ( !!mMediaData
7101 && (!isSessionMachine())
7102 )
7103 {
7104 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7105 it != mMediaData->mAttachments.end();
7106 ++it)
7107 {
7108 ComObjPtr<Medium> hd = (*it)->getMedium();
7109 if (hd.isNull())
7110 continue;
7111 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
7112 AssertComRC(rc);
7113 }
7114 }
7115
7116 if (!isSessionMachine() && !isSnapshotMachine())
7117 {
7118 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
7119 if (mData->mFirstSnapshot)
7120 {
7121 // snapshots tree is protected by media write lock; strictly
7122 // this isn't necessary here since we're deleting the entire
7123 // machine, but otherwise we assert in Snapshot::uninit()
7124 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7125 mData->mFirstSnapshot->uninit();
7126 mData->mFirstSnapshot.setNull();
7127 }
7128
7129 mData->mCurrentSnapshot.setNull();
7130 }
7131
7132 /* free data structures (the essential mData structure is not freed here
7133 * since it may be still in use) */
7134 mMediaData.free();
7135 mStorageControllers.free();
7136 mHWData.free();
7137 mUserData.free();
7138 mSSData.free();
7139}
7140
7141/**
7142 * Returns a pointer to the Machine object for this machine that acts like a
7143 * parent for complex machine data objects such as shared folders, etc.
7144 *
7145 * For primary Machine objects and for SnapshotMachine objects, returns this
7146 * object's pointer itself. For SessionMachine objects, returns the peer
7147 * (primary) machine pointer.
7148 */
7149Machine* Machine::getMachine()
7150{
7151 if (isSessionMachine())
7152 return (Machine*)mPeer;
7153 return this;
7154}
7155
7156/**
7157 * Makes sure that there are no machine state dependents. If necessary, waits
7158 * for the number of dependents to drop to zero.
7159 *
7160 * Make sure this method is called from under this object's write lock to
7161 * guarantee that no new dependents may be added when this method returns
7162 * control to the caller.
7163 *
7164 * @note Locks this object for writing. The lock will be released while waiting
7165 * (if necessary).
7166 *
7167 * @warning To be used only in methods that change the machine state!
7168 */
7169void Machine::ensureNoStateDependencies()
7170{
7171 AssertReturnVoid(isWriteLockOnCurrentThread());
7172
7173 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7174
7175 /* Wait for all state dependents if necessary */
7176 if (mData->mMachineStateDeps != 0)
7177 {
7178 /* lazy semaphore creation */
7179 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
7180 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
7181
7182 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
7183 mData->mMachineStateDeps));
7184
7185 ++mData->mMachineStateChangePending;
7186
7187 /* reset the semaphore before waiting, the last dependent will signal
7188 * it */
7189 RTSemEventMultiReset(mData->mMachineStateDepsSem);
7190
7191 alock.leave();
7192
7193 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
7194
7195 alock.enter();
7196
7197 -- mData->mMachineStateChangePending;
7198 }
7199}
7200
7201/**
7202 * Changes the machine state and informs callbacks.
7203 *
7204 * This method is not intended to fail so it either returns S_OK or asserts (and
7205 * returns a failure).
7206 *
7207 * @note Locks this object for writing.
7208 */
7209HRESULT Machine::setMachineState(MachineState_T aMachineState)
7210{
7211 LogFlowThisFuncEnter();
7212 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
7213
7214 AutoCaller autoCaller(this);
7215 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7216
7217 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7218
7219 /* wait for state dependents to drop to zero */
7220 ensureNoStateDependencies();
7221
7222 if (mData->mMachineState != aMachineState)
7223 {
7224 mData->mMachineState = aMachineState;
7225
7226 RTTimeNow(&mData->mLastStateChange);
7227
7228 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7229 }
7230
7231 LogFlowThisFuncLeave();
7232 return S_OK;
7233}
7234
7235/**
7236 * Searches for a shared folder with the given logical name
7237 * in the collection of shared folders.
7238 *
7239 * @param aName logical name of the shared folder
7240 * @param aSharedFolder where to return the found object
7241 * @param aSetError whether to set the error info if the folder is
7242 * not found
7243 * @return
7244 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7245 *
7246 * @note
7247 * must be called from under the object's lock!
7248 */
7249HRESULT Machine::findSharedFolder(const Utf8Str &aName,
7250 ComObjPtr<SharedFolder> &aSharedFolder,
7251 bool aSetError /* = false */)
7252{
7253 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
7254 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7255 it != mHWData->mSharedFolders.end();
7256 ++it)
7257 {
7258 SharedFolder *pSF = *it;
7259 AutoCaller autoCaller(pSF);
7260 if (pSF->getName() == aName)
7261 {
7262 aSharedFolder = pSF;
7263 rc = S_OK;
7264 break;
7265 }
7266 }
7267
7268 if (aSetError && FAILED(rc))
7269 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
7270
7271 return rc;
7272}
7273
7274/**
7275 * Initializes all machine instance data from the given settings structures
7276 * from XML. The exception is the machine UUID which needs special handling
7277 * depending on the caller's use case, so the caller needs to set that herself.
7278 *
7279 * This gets called in several contexts during machine initialization:
7280 *
7281 * -- When machine XML exists on disk already and needs to be loaded into memory,
7282 * for example, from registeredInit() to load all registered machines on
7283 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7284 * attached to the machine should be part of some media registry already.
7285 *
7286 * -- During OVF import, when a machine config has been constructed from an
7287 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7288 * ensure that the media listed as attachments in the config (which have
7289 * been imported from the OVF) receive the correct registry ID.
7290 *
7291 * -- During VM cloning.
7292 *
7293 * @param config Machine settings from XML.
7294 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7295 * @return
7296 */
7297HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7298 const Guid *puuidRegistry)
7299{
7300 // copy name, description, OS type, teleporter, UTC etc.
7301 mUserData->s = config.machineUserData;
7302
7303 // look up the object by Id to check it is valid
7304 ComPtr<IGuestOSType> guestOSType;
7305 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7306 guestOSType.asOutParam());
7307 if (FAILED(rc)) return rc;
7308
7309 // stateFile (optional)
7310 if (config.strStateFile.isEmpty())
7311 mSSData->strStateFilePath.setNull();
7312 else
7313 {
7314 Utf8Str stateFilePathFull(config.strStateFile);
7315 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7316 if (RT_FAILURE(vrc))
7317 return setError(E_FAIL,
7318 tr("Invalid saved state file path '%s' (%Rrc)"),
7319 config.strStateFile.c_str(),
7320 vrc);
7321 mSSData->strStateFilePath = stateFilePathFull;
7322 }
7323
7324 // snapshot folder needs special processing so set it again
7325 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7326 if (FAILED(rc)) return rc;
7327
7328 /* currentStateModified (optional, default is true) */
7329 mData->mCurrentStateModified = config.fCurrentStateModified;
7330
7331 mData->mLastStateChange = config.timeLastStateChange;
7332
7333 /*
7334 * note: all mUserData members must be assigned prior this point because
7335 * we need to commit changes in order to let mUserData be shared by all
7336 * snapshot machine instances.
7337 */
7338 mUserData.commitCopy();
7339
7340 // machine registry, if present (must be loaded before snapshots)
7341 if (config.canHaveOwnMediaRegistry())
7342 {
7343 // determine machine folder
7344 Utf8Str strMachineFolder = getSettingsFileFull();
7345 strMachineFolder.stripFilename();
7346 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7347 config.mediaRegistry,
7348 strMachineFolder);
7349 if (FAILED(rc)) return rc;
7350 }
7351
7352 /* Snapshot node (optional) */
7353 size_t cRootSnapshots;
7354 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7355 {
7356 // there must be only one root snapshot
7357 Assert(cRootSnapshots == 1);
7358
7359 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7360
7361 rc = loadSnapshot(snap,
7362 config.uuidCurrentSnapshot,
7363 NULL); // no parent == first snapshot
7364 if (FAILED(rc)) return rc;
7365 }
7366
7367 // hardware data
7368 rc = loadHardware(config.hardwareMachine);
7369 if (FAILED(rc)) return rc;
7370
7371 // load storage controllers
7372 rc = loadStorageControllers(config.storageMachine,
7373 puuidRegistry,
7374 NULL /* puuidSnapshot */);
7375 if (FAILED(rc)) return rc;
7376
7377 /*
7378 * NOTE: the assignment below must be the last thing to do,
7379 * otherwise it will be not possible to change the settings
7380 * somewhere in the code above because all setters will be
7381 * blocked by checkStateDependency(MutableStateDep).
7382 */
7383
7384 /* set the machine state to Aborted or Saved when appropriate */
7385 if (config.fAborted)
7386 {
7387 Assert(!mSSData->strStateFilePath.isEmpty());
7388 mSSData->strStateFilePath.setNull();
7389
7390 /* no need to use setMachineState() during init() */
7391 mData->mMachineState = MachineState_Aborted;
7392 }
7393 else if (!mSSData->strStateFilePath.isEmpty())
7394 {
7395 /* no need to use setMachineState() during init() */
7396 mData->mMachineState = MachineState_Saved;
7397 }
7398
7399 // after loading settings, we are no longer different from the XML on disk
7400 mData->flModifications = 0;
7401
7402 return S_OK;
7403}
7404
7405/**
7406 * Recursively loads all snapshots starting from the given.
7407 *
7408 * @param aNode <Snapshot> node.
7409 * @param aCurSnapshotId Current snapshot ID from the settings file.
7410 * @param aParentSnapshot Parent snapshot.
7411 */
7412HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7413 const Guid &aCurSnapshotId,
7414 Snapshot *aParentSnapshot)
7415{
7416 AssertReturn(!isSnapshotMachine(), E_FAIL);
7417 AssertReturn(!isSessionMachine(), E_FAIL);
7418
7419 HRESULT rc = S_OK;
7420
7421 Utf8Str strStateFile;
7422 if (!data.strStateFile.isEmpty())
7423 {
7424 /* optional */
7425 strStateFile = data.strStateFile;
7426 int vrc = calculateFullPath(strStateFile, strStateFile);
7427 if (RT_FAILURE(vrc))
7428 return setError(E_FAIL,
7429 tr("Invalid saved state file path '%s' (%Rrc)"),
7430 strStateFile.c_str(),
7431 vrc);
7432 }
7433
7434 /* create a snapshot machine object */
7435 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7436 pSnapshotMachine.createObject();
7437 rc = pSnapshotMachine->init(this,
7438 data.hardware,
7439 data.storage,
7440 data.uuid.ref(),
7441 strStateFile);
7442 if (FAILED(rc)) return rc;
7443
7444 /* create a snapshot object */
7445 ComObjPtr<Snapshot> pSnapshot;
7446 pSnapshot.createObject();
7447 /* initialize the snapshot */
7448 rc = pSnapshot->init(mParent, // VirtualBox object
7449 data.uuid,
7450 data.strName,
7451 data.strDescription,
7452 data.timestamp,
7453 pSnapshotMachine,
7454 aParentSnapshot);
7455 if (FAILED(rc)) return rc;
7456
7457 /* memorize the first snapshot if necessary */
7458 if (!mData->mFirstSnapshot)
7459 mData->mFirstSnapshot = pSnapshot;
7460
7461 /* memorize the current snapshot when appropriate */
7462 if ( !mData->mCurrentSnapshot
7463 && pSnapshot->getId() == aCurSnapshotId
7464 )
7465 mData->mCurrentSnapshot = pSnapshot;
7466
7467 // now create the children
7468 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7469 it != data.llChildSnapshots.end();
7470 ++it)
7471 {
7472 const settings::Snapshot &childData = *it;
7473 // recurse
7474 rc = loadSnapshot(childData,
7475 aCurSnapshotId,
7476 pSnapshot); // parent = the one we created above
7477 if (FAILED(rc)) return rc;
7478 }
7479
7480 return rc;
7481}
7482
7483/**
7484 * @param aNode <Hardware> node.
7485 */
7486HRESULT Machine::loadHardware(const settings::Hardware &data)
7487{
7488 AssertReturn(!isSessionMachine(), E_FAIL);
7489
7490 HRESULT rc = S_OK;
7491
7492 try
7493 {
7494 /* The hardware version attribute (optional). */
7495 mHWData->mHWVersion = data.strVersion;
7496 mHWData->mHardwareUUID = data.uuid;
7497
7498 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7499 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7500 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7501 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7502 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7503 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7504 mHWData->mPAEEnabled = data.fPAE;
7505 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7506
7507 mHWData->mCPUCount = data.cCPUs;
7508 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7509 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7510
7511 // cpu
7512 if (mHWData->mCPUHotPlugEnabled)
7513 {
7514 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7515 it != data.llCpus.end();
7516 ++it)
7517 {
7518 const settings::Cpu &cpu = *it;
7519
7520 mHWData->mCPUAttached[cpu.ulId] = true;
7521 }
7522 }
7523
7524 // cpuid leafs
7525 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7526 it != data.llCpuIdLeafs.end();
7527 ++it)
7528 {
7529 const settings::CpuIdLeaf &leaf = *it;
7530
7531 switch (leaf.ulId)
7532 {
7533 case 0x0:
7534 case 0x1:
7535 case 0x2:
7536 case 0x3:
7537 case 0x4:
7538 case 0x5:
7539 case 0x6:
7540 case 0x7:
7541 case 0x8:
7542 case 0x9:
7543 case 0xA:
7544 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7545 break;
7546
7547 case 0x80000000:
7548 case 0x80000001:
7549 case 0x80000002:
7550 case 0x80000003:
7551 case 0x80000004:
7552 case 0x80000005:
7553 case 0x80000006:
7554 case 0x80000007:
7555 case 0x80000008:
7556 case 0x80000009:
7557 case 0x8000000A:
7558 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7559 break;
7560
7561 default:
7562 /* just ignore */
7563 break;
7564 }
7565 }
7566
7567 mHWData->mMemorySize = data.ulMemorySizeMB;
7568 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7569
7570 // boot order
7571 for (size_t i = 0;
7572 i < RT_ELEMENTS(mHWData->mBootOrder);
7573 i++)
7574 {
7575 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7576 if (it == data.mapBootOrder.end())
7577 mHWData->mBootOrder[i] = DeviceType_Null;
7578 else
7579 mHWData->mBootOrder[i] = it->second;
7580 }
7581
7582 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7583 mHWData->mMonitorCount = data.cMonitors;
7584 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7585 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7586 mHWData->mFirmwareType = data.firmwareType;
7587 mHWData->mPointingHidType = data.pointingHidType;
7588 mHWData->mKeyboardHidType = data.keyboardHidType;
7589 mHWData->mChipsetType = data.chipsetType;
7590 mHWData->mHpetEnabled = data.fHpetEnabled;
7591
7592 /* VRDEServer */
7593 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7594 if (FAILED(rc)) return rc;
7595
7596 /* BIOS */
7597 rc = mBIOSSettings->loadSettings(data.biosSettings);
7598 if (FAILED(rc)) return rc;
7599
7600 // Bandwidth control (must come before network adapters)
7601 rc = mBandwidthControl->loadSettings(data.ioSettings);
7602 if (FAILED(rc)) return rc;
7603
7604 /* USB Controller */
7605 rc = mUSBController->loadSettings(data.usbController);
7606 if (FAILED(rc)) return rc;
7607
7608 // network adapters
7609 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7610 it != data.llNetworkAdapters.end();
7611 ++it)
7612 {
7613 const settings::NetworkAdapter &nic = *it;
7614
7615 /* slot unicity is guaranteed by XML Schema */
7616 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7617 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
7618 if (FAILED(rc)) return rc;
7619 }
7620
7621 // serial ports
7622 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7623 it != data.llSerialPorts.end();
7624 ++it)
7625 {
7626 const settings::SerialPort &s = *it;
7627
7628 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7629 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7630 if (FAILED(rc)) return rc;
7631 }
7632
7633 // parallel ports (optional)
7634 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7635 it != data.llParallelPorts.end();
7636 ++it)
7637 {
7638 const settings::ParallelPort &p = *it;
7639
7640 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7641 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7642 if (FAILED(rc)) return rc;
7643 }
7644
7645 /* AudioAdapter */
7646 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7647 if (FAILED(rc)) return rc;
7648
7649 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7650 it != data.llSharedFolders.end();
7651 ++it)
7652 {
7653 const settings::SharedFolder &sf = *it;
7654 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7655 Bstr(sf.strHostPath).raw(),
7656 sf.fWritable, sf.fAutoMount);
7657 if (FAILED(rc)) return rc;
7658 }
7659
7660 // Clipboard
7661 mHWData->mClipboardMode = data.clipboardMode;
7662
7663 // guest settings
7664 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7665
7666 // IO settings
7667 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7668 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7669
7670 // Host PCI devices
7671 for (settings::HostPciDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
7672 it != data.pciAttachments.end();
7673 ++it)
7674 {
7675 const settings::HostPciDeviceAttachment &hpda = *it;
7676 ComObjPtr<PciDeviceAttachment> pda;
7677
7678 pda.createObject();
7679 pda->loadSettings(this, hpda);
7680 mHWData->mPciDeviceAssignments.push_back(pda);
7681 }
7682
7683#ifdef VBOX_WITH_GUEST_PROPS
7684 /* Guest properties (optional) */
7685 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7686 it != data.llGuestProperties.end();
7687 ++it)
7688 {
7689 const settings::GuestProperty &prop = *it;
7690 uint32_t fFlags = guestProp::NILFLAG;
7691 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7692 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7693 mHWData->mGuestProperties.push_back(property);
7694 }
7695
7696 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7697#endif /* VBOX_WITH_GUEST_PROPS defined */
7698 }
7699 catch(std::bad_alloc &)
7700 {
7701 return E_OUTOFMEMORY;
7702 }
7703
7704 AssertComRC(rc);
7705 return rc;
7706}
7707
7708/**
7709 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7710 *
7711 * @param data
7712 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7713 * @param puuidSnapshot
7714 * @return
7715 */
7716HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7717 const Guid *puuidRegistry,
7718 const Guid *puuidSnapshot)
7719{
7720 AssertReturn(!isSessionMachine(), E_FAIL);
7721
7722 HRESULT rc = S_OK;
7723
7724 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7725 it != data.llStorageControllers.end();
7726 ++it)
7727 {
7728 const settings::StorageController &ctlData = *it;
7729
7730 ComObjPtr<StorageController> pCtl;
7731 /* Try to find one with the name first. */
7732 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7733 if (SUCCEEDED(rc))
7734 return setError(VBOX_E_OBJECT_IN_USE,
7735 tr("Storage controller named '%s' already exists"),
7736 ctlData.strName.c_str());
7737
7738 pCtl.createObject();
7739 rc = pCtl->init(this,
7740 ctlData.strName,
7741 ctlData.storageBus,
7742 ctlData.ulInstance,
7743 ctlData.fBootable);
7744 if (FAILED(rc)) return rc;
7745
7746 mStorageControllers->push_back(pCtl);
7747
7748 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7749 if (FAILED(rc)) return rc;
7750
7751 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7752 if (FAILED(rc)) return rc;
7753
7754 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7755 if (FAILED(rc)) return rc;
7756
7757 /* Set IDE emulation settings (only for AHCI controller). */
7758 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7759 {
7760 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7761 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7762 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7763 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7764 )
7765 return rc;
7766 }
7767
7768 /* Load the attached devices now. */
7769 rc = loadStorageDevices(pCtl,
7770 ctlData,
7771 puuidRegistry,
7772 puuidSnapshot);
7773 if (FAILED(rc)) return rc;
7774 }
7775
7776 return S_OK;
7777}
7778
7779/**
7780 * Called from loadStorageControllers for a controller's devices.
7781 *
7782 * @param aStorageController
7783 * @param data
7784 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7785 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7786 * @return
7787 */
7788HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7789 const settings::StorageController &data,
7790 const Guid *puuidRegistry,
7791 const Guid *puuidSnapshot)
7792{
7793 HRESULT rc = S_OK;
7794
7795 /* paranoia: detect duplicate attachments */
7796 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7797 it != data.llAttachedDevices.end();
7798 ++it)
7799 {
7800 const settings::AttachedDevice &ad = *it;
7801
7802 for (settings::AttachedDevicesList::const_iterator it2 = it;
7803 it2 != data.llAttachedDevices.end();
7804 ++it2)
7805 {
7806 if (it == it2)
7807 continue;
7808
7809 const settings::AttachedDevice &ad2 = *it2;
7810
7811 if ( ad.lPort == ad2.lPort
7812 && ad.lDevice == ad2.lDevice)
7813 {
7814 return setError(E_FAIL,
7815 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7816 aStorageController->getName().c_str(),
7817 ad.lPort,
7818 ad.lDevice,
7819 mUserData->s.strName.c_str());
7820 }
7821 }
7822 }
7823
7824 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7825 it != data.llAttachedDevices.end();
7826 ++it)
7827 {
7828 const settings::AttachedDevice &dev = *it;
7829 ComObjPtr<Medium> medium;
7830
7831 switch (dev.deviceType)
7832 {
7833 case DeviceType_Floppy:
7834 case DeviceType_DVD:
7835 if (dev.strHostDriveSrc.isNotEmpty())
7836 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
7837 else
7838 rc = mParent->findRemoveableMedium(dev.deviceType,
7839 dev.uuid,
7840 false /* fRefresh */,
7841 false /* aSetError */,
7842 medium);
7843 if (rc == VBOX_E_OBJECT_NOT_FOUND)
7844 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
7845 rc = S_OK;
7846 break;
7847
7848 case DeviceType_HardDisk:
7849 {
7850 /* find a hard disk by UUID */
7851 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7852 if (FAILED(rc))
7853 {
7854 if (isSnapshotMachine())
7855 {
7856 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7857 // so the user knows that the bad disk is in a snapshot somewhere
7858 com::ErrorInfo info;
7859 return setError(E_FAIL,
7860 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7861 puuidSnapshot->raw(),
7862 info.getText().raw());
7863 }
7864 else
7865 return rc;
7866 }
7867
7868 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7869
7870 if (medium->getType() == MediumType_Immutable)
7871 {
7872 if (isSnapshotMachine())
7873 return setError(E_FAIL,
7874 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7875 "of the virtual machine '%s' ('%s')"),
7876 medium->getLocationFull().c_str(),
7877 dev.uuid.raw(),
7878 puuidSnapshot->raw(),
7879 mUserData->s.strName.c_str(),
7880 mData->m_strConfigFileFull.c_str());
7881
7882 return setError(E_FAIL,
7883 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7884 medium->getLocationFull().c_str(),
7885 dev.uuid.raw(),
7886 mUserData->s.strName.c_str(),
7887 mData->m_strConfigFileFull.c_str());
7888 }
7889
7890 if (medium->getType() == MediumType_MultiAttach)
7891 {
7892 if (isSnapshotMachine())
7893 return setError(E_FAIL,
7894 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7895 "of the virtual machine '%s' ('%s')"),
7896 medium->getLocationFull().c_str(),
7897 dev.uuid.raw(),
7898 puuidSnapshot->raw(),
7899 mUserData->s.strName.c_str(),
7900 mData->m_strConfigFileFull.c_str());
7901
7902 return setError(E_FAIL,
7903 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7904 medium->getLocationFull().c_str(),
7905 dev.uuid.raw(),
7906 mUserData->s.strName.c_str(),
7907 mData->m_strConfigFileFull.c_str());
7908 }
7909
7910 if ( !isSnapshotMachine()
7911 && medium->getChildren().size() != 0
7912 )
7913 return setError(E_FAIL,
7914 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7915 "because it has %d differencing child hard disks"),
7916 medium->getLocationFull().c_str(),
7917 dev.uuid.raw(),
7918 mUserData->s.strName.c_str(),
7919 mData->m_strConfigFileFull.c_str(),
7920 medium->getChildren().size());
7921
7922 if (findAttachment(mMediaData->mAttachments,
7923 medium))
7924 return setError(E_FAIL,
7925 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7926 medium->getLocationFull().c_str(),
7927 dev.uuid.raw(),
7928 mUserData->s.strName.c_str(),
7929 mData->m_strConfigFileFull.c_str());
7930
7931 break;
7932 }
7933
7934 default:
7935 return setError(E_FAIL,
7936 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7937 medium->getLocationFull().c_str(),
7938 mUserData->s.strName.c_str(),
7939 mData->m_strConfigFileFull.c_str());
7940 }
7941
7942 if (FAILED(rc))
7943 break;
7944
7945 /* Bandwidth groups are loaded at this point. */
7946 ComObjPtr<BandwidthGroup> pBwGroup;
7947
7948 if (!dev.strBwGroup.isEmpty())
7949 {
7950 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
7951 if (FAILED(rc))
7952 return setError(E_FAIL,
7953 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
7954 medium->getLocationFull().c_str(),
7955 dev.strBwGroup.c_str(),
7956 mUserData->s.strName.c_str(),
7957 mData->m_strConfigFileFull.c_str());
7958 pBwGroup->reference();
7959 }
7960
7961 const Bstr controllerName = aStorageController->getName();
7962 ComObjPtr<MediumAttachment> pAttachment;
7963 pAttachment.createObject();
7964 rc = pAttachment->init(this,
7965 medium,
7966 controllerName,
7967 dev.lPort,
7968 dev.lDevice,
7969 dev.deviceType,
7970 dev.fPassThrough,
7971 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
7972 if (FAILED(rc)) break;
7973
7974 /* associate the medium with this machine and snapshot */
7975 if (!medium.isNull())
7976 {
7977 AutoCaller medCaller(medium);
7978 if (FAILED(medCaller.rc())) return medCaller.rc();
7979 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
7980
7981 if (isSnapshotMachine())
7982 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7983 else
7984 rc = medium->addBackReference(mData->mUuid);
7985 /* If the medium->addBackReference fails it sets an appropriate
7986 * error message, so no need to do any guesswork here. */
7987
7988 if (puuidRegistry)
7989 // caller wants registry ID to be set on all attached media (OVF import case)
7990 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
7991 }
7992
7993 if (FAILED(rc))
7994 break;
7995
7996 /* back up mMediaData to let registeredInit() properly rollback on failure
7997 * (= limited accessibility) */
7998 setModified(IsModified_Storage);
7999 mMediaData.backup();
8000 mMediaData->mAttachments.push_back(pAttachment);
8001 }
8002
8003 return rc;
8004}
8005
8006/**
8007 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
8008 *
8009 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
8010 * @param aSnapshot where to return the found snapshot
8011 * @param aSetError true to set extended error info on failure
8012 */
8013HRESULT Machine::findSnapshotById(const Guid &aId,
8014 ComObjPtr<Snapshot> &aSnapshot,
8015 bool aSetError /* = false */)
8016{
8017 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8018
8019 if (!mData->mFirstSnapshot)
8020 {
8021 if (aSetError)
8022 return setError(E_FAIL, tr("This machine does not have any snapshots"));
8023 return E_FAIL;
8024 }
8025
8026 if (aId.isEmpty())
8027 aSnapshot = mData->mFirstSnapshot;
8028 else
8029 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
8030
8031 if (!aSnapshot)
8032 {
8033 if (aSetError)
8034 return setError(E_FAIL,
8035 tr("Could not find a snapshot with UUID {%s}"),
8036 aId.toString().c_str());
8037 return E_FAIL;
8038 }
8039
8040 return S_OK;
8041}
8042
8043/**
8044 * Returns the snapshot with the given name or fails of no such snapshot.
8045 *
8046 * @param aName snapshot name to find
8047 * @param aSnapshot where to return the found snapshot
8048 * @param aSetError true to set extended error info on failure
8049 */
8050HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
8051 ComObjPtr<Snapshot> &aSnapshot,
8052 bool aSetError /* = false */)
8053{
8054 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
8055
8056 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8057
8058 if (!mData->mFirstSnapshot)
8059 {
8060 if (aSetError)
8061 return setError(VBOX_E_OBJECT_NOT_FOUND,
8062 tr("This machine does not have any snapshots"));
8063 return VBOX_E_OBJECT_NOT_FOUND;
8064 }
8065
8066 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
8067
8068 if (!aSnapshot)
8069 {
8070 if (aSetError)
8071 return setError(VBOX_E_OBJECT_NOT_FOUND,
8072 tr("Could not find a snapshot named '%s'"), strName.c_str());
8073 return VBOX_E_OBJECT_NOT_FOUND;
8074 }
8075
8076 return S_OK;
8077}
8078
8079/**
8080 * Returns a storage controller object with the given name.
8081 *
8082 * @param aName storage controller name to find
8083 * @param aStorageController where to return the found storage controller
8084 * @param aSetError true to set extended error info on failure
8085 */
8086HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
8087 ComObjPtr<StorageController> &aStorageController,
8088 bool aSetError /* = false */)
8089{
8090 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
8091
8092 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8093 it != mStorageControllers->end();
8094 ++it)
8095 {
8096 if ((*it)->getName() == aName)
8097 {
8098 aStorageController = (*it);
8099 return S_OK;
8100 }
8101 }
8102
8103 if (aSetError)
8104 return setError(VBOX_E_OBJECT_NOT_FOUND,
8105 tr("Could not find a storage controller named '%s'"),
8106 aName.c_str());
8107 return VBOX_E_OBJECT_NOT_FOUND;
8108}
8109
8110HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
8111 MediaData::AttachmentList &atts)
8112{
8113 AutoCaller autoCaller(this);
8114 if (FAILED(autoCaller.rc())) return autoCaller.rc();
8115
8116 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8117
8118 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
8119 it != mMediaData->mAttachments.end();
8120 ++it)
8121 {
8122 const ComObjPtr<MediumAttachment> &pAtt = *it;
8123
8124 // should never happen, but deal with NULL pointers in the list.
8125 AssertStmt(!pAtt.isNull(), continue);
8126
8127 // getControllerName() needs caller+read lock
8128 AutoCaller autoAttCaller(pAtt);
8129 if (FAILED(autoAttCaller.rc()))
8130 {
8131 atts.clear();
8132 return autoAttCaller.rc();
8133 }
8134 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
8135
8136 if (pAtt->getControllerName() == aName)
8137 atts.push_back(pAtt);
8138 }
8139
8140 return S_OK;
8141}
8142
8143/**
8144 * Helper for #saveSettings. Cares about renaming the settings directory and
8145 * file if the machine name was changed and about creating a new settings file
8146 * if this is a new machine.
8147 *
8148 * @note Must be never called directly but only from #saveSettings().
8149 */
8150HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
8151{
8152 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8153
8154 HRESULT rc = S_OK;
8155
8156 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
8157
8158 /* attempt to rename the settings file if machine name is changed */
8159 if ( mUserData->s.fNameSync
8160 && mUserData.isBackedUp()
8161 && mUserData.backedUpData()->s.strName != mUserData->s.strName
8162 )
8163 {
8164 bool dirRenamed = false;
8165 bool fileRenamed = false;
8166
8167 Utf8Str configFile, newConfigFile;
8168 Utf8Str configFilePrev, newConfigFilePrev;
8169 Utf8Str configDir, newConfigDir;
8170
8171 do
8172 {
8173 int vrc = VINF_SUCCESS;
8174
8175 Utf8Str name = mUserData.backedUpData()->s.strName;
8176 Utf8Str newName = mUserData->s.strName;
8177
8178 configFile = mData->m_strConfigFileFull;
8179
8180 /* first, rename the directory if it matches the machine name */
8181 configDir = configFile;
8182 configDir.stripFilename();
8183 newConfigDir = configDir;
8184 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8185 {
8186 newConfigDir.stripFilename();
8187 newConfigDir.append(RTPATH_DELIMITER);
8188 newConfigDir.append(newName);
8189 /* new dir and old dir cannot be equal here because of 'if'
8190 * above and because name != newName */
8191 Assert(configDir != newConfigDir);
8192 if (!fSettingsFileIsNew)
8193 {
8194 /* perform real rename only if the machine is not new */
8195 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8196 if (RT_FAILURE(vrc))
8197 {
8198 rc = setError(E_FAIL,
8199 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8200 configDir.c_str(),
8201 newConfigDir.c_str(),
8202 vrc);
8203 break;
8204 }
8205 dirRenamed = true;
8206 }
8207 }
8208
8209 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8210 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8211
8212 /* then try to rename the settings file itself */
8213 if (newConfigFile != configFile)
8214 {
8215 /* get the path to old settings file in renamed directory */
8216 configFile = Utf8StrFmt("%s%c%s",
8217 newConfigDir.c_str(),
8218 RTPATH_DELIMITER,
8219 RTPathFilename(configFile.c_str()));
8220 if (!fSettingsFileIsNew)
8221 {
8222 /* perform real rename only if the machine is not new */
8223 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8224 if (RT_FAILURE(vrc))
8225 {
8226 rc = setError(E_FAIL,
8227 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8228 configFile.c_str(),
8229 newConfigFile.c_str(),
8230 vrc);
8231 break;
8232 }
8233 fileRenamed = true;
8234 configFilePrev = configFile;
8235 configFilePrev += "-prev";
8236 newConfigFilePrev = newConfigFile;
8237 newConfigFilePrev += "-prev";
8238 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
8239 }
8240 }
8241
8242 // update m_strConfigFileFull amd mConfigFile
8243 mData->m_strConfigFileFull = newConfigFile;
8244 // compute the relative path too
8245 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8246
8247 // store the old and new so that VirtualBox::saveSettings() can update
8248 // the media registry
8249 if ( mData->mRegistered
8250 && configDir != newConfigDir)
8251 {
8252 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8253
8254 if (pfNeedsGlobalSaveSettings)
8255 *pfNeedsGlobalSaveSettings = true;
8256 }
8257
8258 // in the saved state file path, replace the old directory with the new directory
8259 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8260 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8261
8262 // and do the same thing for the saved state file paths of all the online snapshots
8263 if (mData->mFirstSnapshot)
8264 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8265 newConfigDir.c_str());
8266 }
8267 while (0);
8268
8269 if (FAILED(rc))
8270 {
8271 /* silently try to rename everything back */
8272 if (fileRenamed)
8273 {
8274 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
8275 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8276 }
8277 if (dirRenamed)
8278 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8279 }
8280
8281 if (FAILED(rc)) return rc;
8282 }
8283
8284 if (fSettingsFileIsNew)
8285 {
8286 /* create a virgin config file */
8287 int vrc = VINF_SUCCESS;
8288
8289 /* ensure the settings directory exists */
8290 Utf8Str path(mData->m_strConfigFileFull);
8291 path.stripFilename();
8292 if (!RTDirExists(path.c_str()))
8293 {
8294 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8295 if (RT_FAILURE(vrc))
8296 {
8297 return setError(E_FAIL,
8298 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8299 path.c_str(),
8300 vrc);
8301 }
8302 }
8303
8304 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8305 path = Utf8Str(mData->m_strConfigFileFull);
8306 RTFILE f = NIL_RTFILE;
8307 vrc = RTFileOpen(&f, path.c_str(),
8308 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8309 if (RT_FAILURE(vrc))
8310 return setError(E_FAIL,
8311 tr("Could not create the settings file '%s' (%Rrc)"),
8312 path.c_str(),
8313 vrc);
8314 RTFileClose(f);
8315 }
8316
8317 return rc;
8318}
8319
8320/**
8321 * Saves and commits machine data, user data and hardware data.
8322 *
8323 * Note that on failure, the data remains uncommitted.
8324 *
8325 * @a aFlags may combine the following flags:
8326 *
8327 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8328 * Used when saving settings after an operation that makes them 100%
8329 * correspond to the settings from the current snapshot.
8330 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8331 * #isReallyModified() returns false. This is necessary for cases when we
8332 * change machine data directly, not through the backup()/commit() mechanism.
8333 * - SaveS_Force: settings will be saved without doing a deep compare of the
8334 * settings structures. This is used when this is called because snapshots
8335 * have changed to avoid the overhead of the deep compare.
8336 *
8337 * @note Must be called from under this object's write lock. Locks children for
8338 * writing.
8339 *
8340 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8341 * initialized to false and that will be set to true by this function if
8342 * the caller must invoke VirtualBox::saveSettings() because the global
8343 * settings have changed. This will happen if a machine rename has been
8344 * saved and the global machine and media registries will therefore need
8345 * updating.
8346 */
8347HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8348 int aFlags /*= 0*/)
8349{
8350 LogFlowThisFuncEnter();
8351
8352 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8353
8354 /* make sure child objects are unable to modify the settings while we are
8355 * saving them */
8356 ensureNoStateDependencies();
8357
8358 AssertReturn(!isSnapshotMachine(),
8359 E_FAIL);
8360
8361 HRESULT rc = S_OK;
8362 bool fNeedsWrite = false;
8363
8364 /* First, prepare to save settings. It will care about renaming the
8365 * settings directory and file if the machine name was changed and about
8366 * creating a new settings file if this is a new machine. */
8367 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8368 if (FAILED(rc)) return rc;
8369
8370 // keep a pointer to the current settings structures
8371 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8372 settings::MachineConfigFile *pNewConfig = NULL;
8373
8374 try
8375 {
8376 // make a fresh one to have everyone write stuff into
8377 pNewConfig = new settings::MachineConfigFile(NULL);
8378 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8379
8380 // now go and copy all the settings data from COM to the settings structures
8381 // (this calles saveSettings() on all the COM objects in the machine)
8382 copyMachineDataToSettings(*pNewConfig);
8383
8384 if (aFlags & SaveS_ResetCurStateModified)
8385 {
8386 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8387 mData->mCurrentStateModified = FALSE;
8388 fNeedsWrite = true; // always, no need to compare
8389 }
8390 else if (aFlags & SaveS_Force)
8391 {
8392 fNeedsWrite = true; // always, no need to compare
8393 }
8394 else
8395 {
8396 if (!mData->mCurrentStateModified)
8397 {
8398 // do a deep compare of the settings that we just saved with the settings
8399 // previously stored in the config file; this invokes MachineConfigFile::operator==
8400 // which does a deep compare of all the settings, which is expensive but less expensive
8401 // than writing out XML in vain
8402 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8403
8404 // could still be modified if any settings changed
8405 mData->mCurrentStateModified = fAnySettingsChanged;
8406
8407 fNeedsWrite = fAnySettingsChanged;
8408 }
8409 else
8410 fNeedsWrite = true;
8411 }
8412
8413 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8414
8415 if (fNeedsWrite)
8416 // now spit it all out!
8417 pNewConfig->write(mData->m_strConfigFileFull);
8418
8419 mData->pMachineConfigFile = pNewConfig;
8420 delete pOldConfig;
8421 commit();
8422
8423 // after saving settings, we are no longer different from the XML on disk
8424 mData->flModifications = 0;
8425 }
8426 catch (HRESULT err)
8427 {
8428 // we assume that error info is set by the thrower
8429 rc = err;
8430
8431 // restore old config
8432 delete pNewConfig;
8433 mData->pMachineConfigFile = pOldConfig;
8434 }
8435 catch (...)
8436 {
8437 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8438 }
8439
8440 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8441 {
8442 /* Fire the data change event, even on failure (since we've already
8443 * committed all data). This is done only for SessionMachines because
8444 * mutable Machine instances are always not registered (i.e. private
8445 * to the client process that creates them) and thus don't need to
8446 * inform callbacks. */
8447 if (isSessionMachine())
8448 mParent->onMachineDataChange(mData->mUuid);
8449 }
8450
8451 LogFlowThisFunc(("rc=%08X\n", rc));
8452 LogFlowThisFuncLeave();
8453 return rc;
8454}
8455
8456/**
8457 * Implementation for saving the machine settings into the given
8458 * settings::MachineConfigFile instance. This copies machine extradata
8459 * from the previous machine config file in the instance data, if any.
8460 *
8461 * This gets called from two locations:
8462 *
8463 * -- Machine::saveSettings(), during the regular XML writing;
8464 *
8465 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8466 * exported to OVF and we write the VirtualBox proprietary XML
8467 * into a <vbox:Machine> tag.
8468 *
8469 * This routine fills all the fields in there, including snapshots, *except*
8470 * for the following:
8471 *
8472 * -- fCurrentStateModified. There is some special logic associated with that.
8473 *
8474 * The caller can then call MachineConfigFile::write() or do something else
8475 * with it.
8476 *
8477 * Caller must hold the machine lock!
8478 *
8479 * This throws XML errors and HRESULT, so the caller must have a catch block!
8480 */
8481void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8482{
8483 // deep copy extradata
8484 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8485
8486 config.uuid = mData->mUuid;
8487
8488 // copy name, description, OS type, teleport, UTC etc.
8489 config.machineUserData = mUserData->s;
8490
8491 if ( mData->mMachineState == MachineState_Saved
8492 || mData->mMachineState == MachineState_Restoring
8493 // when deleting a snapshot we may or may not have a saved state in the current state,
8494 // so let's not assert here please
8495 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8496 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8497 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8498 && (!mSSData->strStateFilePath.isEmpty())
8499 )
8500 )
8501 {
8502 Assert(!mSSData->strStateFilePath.isEmpty());
8503 /* try to make the file name relative to the settings file dir */
8504 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
8505 }
8506 else
8507 {
8508 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
8509 config.strStateFile.setNull();
8510 }
8511
8512 if (mData->mCurrentSnapshot)
8513 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8514 else
8515 config.uuidCurrentSnapshot.clear();
8516
8517 config.timeLastStateChange = mData->mLastStateChange;
8518 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8519 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8520
8521 HRESULT rc = saveHardware(config.hardwareMachine);
8522 if (FAILED(rc)) throw rc;
8523
8524 rc = saveStorageControllers(config.storageMachine);
8525 if (FAILED(rc)) throw rc;
8526
8527 // save machine's media registry if this is VirtualBox 4.0 or later
8528 if (config.canHaveOwnMediaRegistry())
8529 {
8530 // determine machine folder
8531 Utf8Str strMachineFolder = getSettingsFileFull();
8532 strMachineFolder.stripFilename();
8533 mParent->saveMediaRegistry(config.mediaRegistry,
8534 getId(), // only media with registry ID == machine UUID
8535 strMachineFolder);
8536 // this throws HRESULT
8537 }
8538
8539 // save snapshots
8540 rc = saveAllSnapshots(config);
8541 if (FAILED(rc)) throw rc;
8542}
8543
8544/**
8545 * Saves all snapshots of the machine into the given machine config file. Called
8546 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8547 * @param config
8548 * @return
8549 */
8550HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8551{
8552 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8553
8554 HRESULT rc = S_OK;
8555
8556 try
8557 {
8558 config.llFirstSnapshot.clear();
8559
8560 if (mData->mFirstSnapshot)
8561 {
8562 settings::Snapshot snapNew;
8563 config.llFirstSnapshot.push_back(snapNew);
8564
8565 // get reference to the fresh copy of the snapshot on the list and
8566 // work on that copy directly to avoid excessive copying later
8567 settings::Snapshot &snap = config.llFirstSnapshot.front();
8568
8569 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8570 if (FAILED(rc)) throw rc;
8571 }
8572
8573// if (mType == IsSessionMachine)
8574// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8575
8576 }
8577 catch (HRESULT err)
8578 {
8579 /* we assume that error info is set by the thrower */
8580 rc = err;
8581 }
8582 catch (...)
8583 {
8584 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8585 }
8586
8587 return rc;
8588}
8589
8590/**
8591 * Saves the VM hardware configuration. It is assumed that the
8592 * given node is empty.
8593 *
8594 * @param aNode <Hardware> node to save the VM hardware configuration to.
8595 */
8596HRESULT Machine::saveHardware(settings::Hardware &data)
8597{
8598 HRESULT rc = S_OK;
8599
8600 try
8601 {
8602 /* The hardware version attribute (optional).
8603 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8604 if ( mHWData->mHWVersion == "1"
8605 && mSSData->strStateFilePath.isEmpty()
8606 )
8607 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. */
8608
8609 data.strVersion = mHWData->mHWVersion;
8610 data.uuid = mHWData->mHardwareUUID;
8611
8612 // CPU
8613 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8614 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8615 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8616 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8617 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8618 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8619 data.fPAE = !!mHWData->mPAEEnabled;
8620 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8621
8622 /* Standard and Extended CPUID leafs. */
8623 data.llCpuIdLeafs.clear();
8624 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8625 {
8626 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8627 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8628 }
8629 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8630 {
8631 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8632 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8633 }
8634
8635 data.cCPUs = mHWData->mCPUCount;
8636 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8637 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8638
8639 data.llCpus.clear();
8640 if (data.fCpuHotPlug)
8641 {
8642 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8643 {
8644 if (mHWData->mCPUAttached[idx])
8645 {
8646 settings::Cpu cpu;
8647 cpu.ulId = idx;
8648 data.llCpus.push_back(cpu);
8649 }
8650 }
8651 }
8652
8653 // memory
8654 data.ulMemorySizeMB = mHWData->mMemorySize;
8655 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8656
8657 // firmware
8658 data.firmwareType = mHWData->mFirmwareType;
8659
8660 // HID
8661 data.pointingHidType = mHWData->mPointingHidType;
8662 data.keyboardHidType = mHWData->mKeyboardHidType;
8663
8664 // chipset
8665 data.chipsetType = mHWData->mChipsetType;
8666
8667 // HPET
8668 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8669
8670 // boot order
8671 data.mapBootOrder.clear();
8672 for (size_t i = 0;
8673 i < RT_ELEMENTS(mHWData->mBootOrder);
8674 ++i)
8675 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8676
8677 // display
8678 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8679 data.cMonitors = mHWData->mMonitorCount;
8680 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8681 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8682
8683 /* VRDEServer settings (optional) */
8684 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8685 if (FAILED(rc)) throw rc;
8686
8687 /* BIOS (required) */
8688 rc = mBIOSSettings->saveSettings(data.biosSettings);
8689 if (FAILED(rc)) throw rc;
8690
8691 /* USB Controller (required) */
8692 rc = mUSBController->saveSettings(data.usbController);
8693 if (FAILED(rc)) throw rc;
8694
8695 /* Network adapters (required) */
8696 data.llNetworkAdapters.clear();
8697 for (ULONG slot = 0;
8698 slot < RT_ELEMENTS(mNetworkAdapters);
8699 ++slot)
8700 {
8701 settings::NetworkAdapter nic;
8702 nic.ulSlot = slot;
8703 rc = mNetworkAdapters[slot]->saveSettings(nic);
8704 if (FAILED(rc)) throw rc;
8705
8706 data.llNetworkAdapters.push_back(nic);
8707 }
8708
8709 /* Serial ports */
8710 data.llSerialPorts.clear();
8711 for (ULONG slot = 0;
8712 slot < RT_ELEMENTS(mSerialPorts);
8713 ++slot)
8714 {
8715 settings::SerialPort s;
8716 s.ulSlot = slot;
8717 rc = mSerialPorts[slot]->saveSettings(s);
8718 if (FAILED(rc)) return rc;
8719
8720 data.llSerialPorts.push_back(s);
8721 }
8722
8723 /* Parallel ports */
8724 data.llParallelPorts.clear();
8725 for (ULONG slot = 0;
8726 slot < RT_ELEMENTS(mParallelPorts);
8727 ++slot)
8728 {
8729 settings::ParallelPort p;
8730 p.ulSlot = slot;
8731 rc = mParallelPorts[slot]->saveSettings(p);
8732 if (FAILED(rc)) return rc;
8733
8734 data.llParallelPorts.push_back(p);
8735 }
8736
8737 /* Audio adapter */
8738 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8739 if (FAILED(rc)) return rc;
8740
8741 /* Shared folders */
8742 data.llSharedFolders.clear();
8743 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8744 it != mHWData->mSharedFolders.end();
8745 ++it)
8746 {
8747 SharedFolder *pSF = *it;
8748 AutoCaller sfCaller(pSF);
8749 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8750 settings::SharedFolder sf;
8751 sf.strName = pSF->getName();
8752 sf.strHostPath = pSF->getHostPath();
8753 sf.fWritable = !!pSF->isWritable();
8754 sf.fAutoMount = !!pSF->isAutoMounted();
8755
8756 data.llSharedFolders.push_back(sf);
8757 }
8758
8759 // clipboard
8760 data.clipboardMode = mHWData->mClipboardMode;
8761
8762 /* Guest */
8763 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8764
8765 // IO settings
8766 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8767 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8768
8769 /* BandwidthControl (required) */
8770 rc = mBandwidthControl->saveSettings(data.ioSettings);
8771 if (FAILED(rc)) throw rc;
8772
8773 /* Host PCI devices */
8774 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
8775 it != mHWData->mPciDeviceAssignments.end();
8776 ++it)
8777 {
8778 ComObjPtr<PciDeviceAttachment> pda = *it;
8779 settings::HostPciDeviceAttachment hpda;
8780
8781 rc = pda->saveSettings(hpda);
8782 if (FAILED(rc)) throw rc;
8783
8784 data.pciAttachments.push_back(hpda);
8785 }
8786
8787
8788 // guest properties
8789 data.llGuestProperties.clear();
8790#ifdef VBOX_WITH_GUEST_PROPS
8791 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8792 it != mHWData->mGuestProperties.end();
8793 ++it)
8794 {
8795 HWData::GuestProperty property = *it;
8796
8797 /* Remove transient guest properties at shutdown unless we
8798 * are saving state */
8799 if ( ( mData->mMachineState == MachineState_PoweredOff
8800 || mData->mMachineState == MachineState_Aborted
8801 || mData->mMachineState == MachineState_Teleported)
8802 && ( property.mFlags & guestProp::TRANSIENT
8803 || property.mFlags & guestProp::TRANSRESET))
8804 continue;
8805 settings::GuestProperty prop;
8806 prop.strName = property.strName;
8807 prop.strValue = property.strValue;
8808 prop.timestamp = property.mTimestamp;
8809 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8810 guestProp::writeFlags(property.mFlags, szFlags);
8811 prop.strFlags = szFlags;
8812
8813 data.llGuestProperties.push_back(prop);
8814 }
8815
8816 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8817 /* I presume this doesn't require a backup(). */
8818 mData->mGuestPropertiesModified = FALSE;
8819#endif /* VBOX_WITH_GUEST_PROPS defined */
8820 }
8821 catch(std::bad_alloc &)
8822 {
8823 return E_OUTOFMEMORY;
8824 }
8825
8826 AssertComRC(rc);
8827 return rc;
8828}
8829
8830/**
8831 * Saves the storage controller configuration.
8832 *
8833 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8834 */
8835HRESULT Machine::saveStorageControllers(settings::Storage &data)
8836{
8837 data.llStorageControllers.clear();
8838
8839 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8840 it != mStorageControllers->end();
8841 ++it)
8842 {
8843 HRESULT rc;
8844 ComObjPtr<StorageController> pCtl = *it;
8845
8846 settings::StorageController ctl;
8847 ctl.strName = pCtl->getName();
8848 ctl.controllerType = pCtl->getControllerType();
8849 ctl.storageBus = pCtl->getStorageBus();
8850 ctl.ulInstance = pCtl->getInstance();
8851 ctl.fBootable = pCtl->getBootable();
8852
8853 /* Save the port count. */
8854 ULONG portCount;
8855 rc = pCtl->COMGETTER(PortCount)(&portCount);
8856 ComAssertComRCRet(rc, rc);
8857 ctl.ulPortCount = portCount;
8858
8859 /* Save fUseHostIOCache */
8860 BOOL fUseHostIOCache;
8861 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8862 ComAssertComRCRet(rc, rc);
8863 ctl.fUseHostIOCache = !!fUseHostIOCache;
8864
8865 /* Save IDE emulation settings. */
8866 if (ctl.controllerType == StorageControllerType_IntelAhci)
8867 {
8868 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8869 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8870 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8871 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8872 )
8873 ComAssertComRCRet(rc, rc);
8874 }
8875
8876 /* save the devices now. */
8877 rc = saveStorageDevices(pCtl, ctl);
8878 ComAssertComRCRet(rc, rc);
8879
8880 data.llStorageControllers.push_back(ctl);
8881 }
8882
8883 return S_OK;
8884}
8885
8886/**
8887 * Saves the hard disk configuration.
8888 */
8889HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8890 settings::StorageController &data)
8891{
8892 MediaData::AttachmentList atts;
8893
8894 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8895 if (FAILED(rc)) return rc;
8896
8897 data.llAttachedDevices.clear();
8898 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8899 it != atts.end();
8900 ++it)
8901 {
8902 settings::AttachedDevice dev;
8903
8904 MediumAttachment *pAttach = *it;
8905 Medium *pMedium = pAttach->getMedium();
8906
8907 dev.deviceType = pAttach->getType();
8908 dev.lPort = pAttach->getPort();
8909 dev.lDevice = pAttach->getDevice();
8910 if (pMedium)
8911 {
8912 if (pMedium->isHostDrive())
8913 dev.strHostDriveSrc = pMedium->getLocationFull();
8914 else
8915 dev.uuid = pMedium->getId();
8916 dev.fPassThrough = pAttach->getPassthrough();
8917 }
8918
8919 dev.strBwGroup = pAttach->getBandwidthGroup();
8920
8921 data.llAttachedDevices.push_back(dev);
8922 }
8923
8924 return S_OK;
8925}
8926
8927/**
8928 * Saves machine state settings as defined by aFlags
8929 * (SaveSTS_* values).
8930 *
8931 * @param aFlags Combination of SaveSTS_* flags.
8932 *
8933 * @note Locks objects for writing.
8934 */
8935HRESULT Machine::saveStateSettings(int aFlags)
8936{
8937 if (aFlags == 0)
8938 return S_OK;
8939
8940 AutoCaller autoCaller(this);
8941 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8942
8943 /* This object's write lock is also necessary to serialize file access
8944 * (prevent concurrent reads and writes) */
8945 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8946
8947 HRESULT rc = S_OK;
8948
8949 Assert(mData->pMachineConfigFile);
8950
8951 try
8952 {
8953 if (aFlags & SaveSTS_CurStateModified)
8954 mData->pMachineConfigFile->fCurrentStateModified = true;
8955
8956 if (aFlags & SaveSTS_StateFilePath)
8957 {
8958 if (!mSSData->strStateFilePath.isEmpty())
8959 /* try to make the file name relative to the settings file dir */
8960 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
8961 else
8962 mData->pMachineConfigFile->strStateFile.setNull();
8963 }
8964
8965 if (aFlags & SaveSTS_StateTimeStamp)
8966 {
8967 Assert( mData->mMachineState != MachineState_Aborted
8968 || mSSData->strStateFilePath.isEmpty());
8969
8970 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8971
8972 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8973//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8974 }
8975
8976 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8977 }
8978 catch (...)
8979 {
8980 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8981 }
8982
8983 return rc;
8984}
8985
8986/**
8987 * Ensures that the given medium is added to a media registry. If this machine
8988 * was created with 4.0 or later, then the machine registry is used. Otherwise
8989 * the global VirtualBox media registry is used. If the medium was actually
8990 * added to a registry (because it wasn't in the registry yet), the UUID of
8991 * that registry is added to the given list so that the caller can save the
8992 * registry.
8993 *
8994 * Caller must hold machine read lock!
8995 *
8996 * @param pMedium
8997 * @param llRegistriesThatNeedSaving
8998 * @param puuid Optional buffer that receives the registry UUID that was used.
8999 */
9000void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
9001 GuidList &llRegistriesThatNeedSaving,
9002 Guid *puuid)
9003{
9004 // decide which medium registry to use now that the medium is attached:
9005 Guid uuid;
9006 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
9007 // machine XML is VirtualBox 4.0 or higher:
9008 uuid = getId(); // machine UUID
9009 else
9010 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
9011
9012 AutoCaller autoCaller(pMedium);
9013 if (FAILED(autoCaller.rc())) return;
9014 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9015
9016 if (pMedium->addRegistry(uuid, false /* fRecurse */))
9017 // registry actually changed:
9018 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
9019
9020 if (puuid)
9021 *puuid = uuid;
9022}
9023
9024/**
9025 * Creates differencing hard disks for all normal hard disks attached to this
9026 * machine and a new set of attachments to refer to created disks.
9027 *
9028 * Used when taking a snapshot or when deleting the current state. Gets called
9029 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
9030 *
9031 * This method assumes that mMediaData contains the original hard disk attachments
9032 * it needs to create diffs for. On success, these attachments will be replaced
9033 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
9034 * called to delete created diffs which will also rollback mMediaData and restore
9035 * whatever was backed up before calling this method.
9036 *
9037 * Attachments with non-normal hard disks are left as is.
9038 *
9039 * If @a aOnline is @c false then the original hard disks that require implicit
9040 * diffs will be locked for reading. Otherwise it is assumed that they are
9041 * already locked for writing (when the VM was started). Note that in the latter
9042 * case it is responsibility of the caller to lock the newly created diffs for
9043 * writing if this method succeeds.
9044 *
9045 * @param aProgress Progress object to run (must contain at least as
9046 * many operations left as the number of hard disks
9047 * attached).
9048 * @param aOnline Whether the VM was online prior to this operation.
9049 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9050 *
9051 * @note The progress object is not marked as completed, neither on success nor
9052 * on failure. This is a responsibility of the caller.
9053 *
9054 * @note Locks this object for writing.
9055 */
9056HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
9057 ULONG aWeight,
9058 bool aOnline,
9059 GuidList *pllRegistriesThatNeedSaving)
9060{
9061 LogFlowThisFunc(("aOnline=%d\n", aOnline));
9062
9063 AutoCaller autoCaller(this);
9064 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9065
9066 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9067
9068 /* must be in a protective state because we leave the lock below */
9069 AssertReturn( mData->mMachineState == MachineState_Saving
9070 || mData->mMachineState == MachineState_LiveSnapshotting
9071 || mData->mMachineState == MachineState_RestoringSnapshot
9072 || mData->mMachineState == MachineState_DeletingSnapshot
9073 , E_FAIL);
9074
9075 HRESULT rc = S_OK;
9076
9077 MediumLockListMap lockedMediaOffline;
9078 MediumLockListMap *lockedMediaMap;
9079 if (aOnline)
9080 lockedMediaMap = &mData->mSession.mLockedMedia;
9081 else
9082 lockedMediaMap = &lockedMediaOffline;
9083
9084 try
9085 {
9086 if (!aOnline)
9087 {
9088 /* lock all attached hard disks early to detect "in use"
9089 * situations before creating actual diffs */
9090 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9091 it != mMediaData->mAttachments.end();
9092 ++it)
9093 {
9094 MediumAttachment* pAtt = *it;
9095 if (pAtt->getType() == DeviceType_HardDisk)
9096 {
9097 Medium* pMedium = pAtt->getMedium();
9098 Assert(pMedium);
9099
9100 MediumLockList *pMediumLockList(new MediumLockList());
9101 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
9102 false /* fMediumLockWrite */,
9103 NULL,
9104 *pMediumLockList);
9105 if (FAILED(rc))
9106 {
9107 delete pMediumLockList;
9108 throw rc;
9109 }
9110 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
9111 if (FAILED(rc))
9112 {
9113 throw setError(rc,
9114 tr("Collecting locking information for all attached media failed"));
9115 }
9116 }
9117 }
9118
9119 /* Now lock all media. If this fails, nothing is locked. */
9120 rc = lockedMediaMap->Lock();
9121 if (FAILED(rc))
9122 {
9123 throw setError(rc,
9124 tr("Locking of attached media failed"));
9125 }
9126 }
9127
9128 /* remember the current list (note that we don't use backup() since
9129 * mMediaData may be already backed up) */
9130 MediaData::AttachmentList atts = mMediaData->mAttachments;
9131
9132 /* start from scratch */
9133 mMediaData->mAttachments.clear();
9134
9135 /* go through remembered attachments and create diffs for normal hard
9136 * disks and attach them */
9137 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9138 it != atts.end();
9139 ++it)
9140 {
9141 MediumAttachment* pAtt = *it;
9142
9143 DeviceType_T devType = pAtt->getType();
9144 Medium* pMedium = pAtt->getMedium();
9145
9146 if ( devType != DeviceType_HardDisk
9147 || pMedium == NULL
9148 || pMedium->getType() != MediumType_Normal)
9149 {
9150 /* copy the attachment as is */
9151
9152 /** @todo the progress object created in Console::TakeSnaphot
9153 * only expects operations for hard disks. Later other
9154 * device types need to show up in the progress as well. */
9155 if (devType == DeviceType_HardDisk)
9156 {
9157 if (pMedium == NULL)
9158 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9159 aWeight); // weight
9160 else
9161 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9162 pMedium->getBase()->getName().c_str()).raw(),
9163 aWeight); // weight
9164 }
9165
9166 mMediaData->mAttachments.push_back(pAtt);
9167 continue;
9168 }
9169
9170 /* need a diff */
9171 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9172 pMedium->getBase()->getName().c_str()).raw(),
9173 aWeight); // weight
9174
9175 Utf8Str strFullSnapshotFolder;
9176 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9177
9178 ComObjPtr<Medium> diff;
9179 diff.createObject();
9180 // store the diff in the same registry as the parent
9181 // (this cannot fail here because we can't create implicit diffs for
9182 // unregistered images)
9183 Guid uuidRegistryParent;
9184 bool fInRegistry = pMedium->getFirstRegistryMachineId(uuidRegistryParent);
9185 Assert(fInRegistry); NOREF(fInRegistry);
9186 rc = diff->init(mParent,
9187 pMedium->getPreferredDiffFormat(),
9188 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9189 uuidRegistryParent,
9190 pllRegistriesThatNeedSaving);
9191 if (FAILED(rc)) throw rc;
9192
9193 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9194 * the push_back? Looks like we're going to leave medium with the
9195 * wrong kind of lock (general issue with if we fail anywhere at all)
9196 * and an orphaned VDI in the snapshots folder. */
9197
9198 /* update the appropriate lock list */
9199 MediumLockList *pMediumLockList;
9200 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9201 AssertComRCThrowRC(rc);
9202 if (aOnline)
9203 {
9204 rc = pMediumLockList->Update(pMedium, false);
9205 AssertComRCThrowRC(rc);
9206 }
9207
9208 /* leave the lock before the potentially lengthy operation */
9209 alock.leave();
9210 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9211 pMediumLockList,
9212 NULL /* aProgress */,
9213 true /* aWait */,
9214 pllRegistriesThatNeedSaving);
9215 alock.enter();
9216 if (FAILED(rc)) throw rc;
9217
9218 rc = lockedMediaMap->Unlock();
9219 AssertComRCThrowRC(rc);
9220 rc = pMediumLockList->Append(diff, true);
9221 AssertComRCThrowRC(rc);
9222 rc = lockedMediaMap->Lock();
9223 AssertComRCThrowRC(rc);
9224
9225 rc = diff->addBackReference(mData->mUuid);
9226 AssertComRCThrowRC(rc);
9227
9228 /* add a new attachment */
9229 ComObjPtr<MediumAttachment> attachment;
9230 attachment.createObject();
9231 rc = attachment->init(this,
9232 diff,
9233 pAtt->getControllerName(),
9234 pAtt->getPort(),
9235 pAtt->getDevice(),
9236 DeviceType_HardDisk,
9237 true /* aImplicit */,
9238 pAtt->getBandwidthGroup());
9239 if (FAILED(rc)) throw rc;
9240
9241 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9242 AssertComRCThrowRC(rc);
9243 mMediaData->mAttachments.push_back(attachment);
9244 }
9245 }
9246 catch (HRESULT aRC) { rc = aRC; }
9247
9248 /* unlock all hard disks we locked */
9249 if (!aOnline)
9250 {
9251 ErrorInfoKeeper eik;
9252
9253 HRESULT rc1 = lockedMediaMap->Clear();
9254 AssertComRC(rc1);
9255 }
9256
9257 if (FAILED(rc))
9258 {
9259 MultiResult mrc = rc;
9260
9261 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9262 }
9263
9264 return rc;
9265}
9266
9267/**
9268 * Deletes implicit differencing hard disks created either by
9269 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
9270 *
9271 * Note that to delete hard disks created by #AttachMedium() this method is
9272 * called from #fixupMedia() when the changes are rolled back.
9273 *
9274 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9275 *
9276 * @note Locks this object for writing.
9277 */
9278HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9279{
9280 AutoCaller autoCaller(this);
9281 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9282
9283 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9284 LogFlowThisFuncEnter();
9285
9286 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9287
9288 HRESULT rc = S_OK;
9289
9290 MediaData::AttachmentList implicitAtts;
9291
9292 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9293
9294 /* enumerate new attachments */
9295 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9296 it != mMediaData->mAttachments.end();
9297 ++it)
9298 {
9299 ComObjPtr<Medium> hd = (*it)->getMedium();
9300 if (hd.isNull())
9301 continue;
9302
9303 if ((*it)->isImplicit())
9304 {
9305 /* deassociate and mark for deletion */
9306 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
9307 rc = hd->removeBackReference(mData->mUuid);
9308 AssertComRC(rc);
9309 implicitAtts.push_back(*it);
9310 continue;
9311 }
9312
9313 /* was this hard disk attached before? */
9314 if (!findAttachment(oldAtts, hd))
9315 {
9316 /* no: de-associate */
9317 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9318 rc = hd->removeBackReference(mData->mUuid);
9319 AssertComRC(rc);
9320 continue;
9321 }
9322 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9323 }
9324
9325 /* rollback hard disk changes */
9326 mMediaData.rollback();
9327
9328 MultiResult mrc(S_OK);
9329
9330 /* delete unused implicit diffs */
9331 if (implicitAtts.size() != 0)
9332 {
9333 /* will leave the lock before the potentially lengthy
9334 * operation, so protect with the special state (unless already
9335 * protected) */
9336 MachineState_T oldState = mData->mMachineState;
9337 if ( oldState != MachineState_Saving
9338 && oldState != MachineState_LiveSnapshotting
9339 && oldState != MachineState_RestoringSnapshot
9340 && oldState != MachineState_DeletingSnapshot
9341 && oldState != MachineState_DeletingSnapshotOnline
9342 && oldState != MachineState_DeletingSnapshotPaused
9343 )
9344 setMachineState(MachineState_SettingUp);
9345
9346 alock.leave();
9347
9348 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9349 it != implicitAtts.end();
9350 ++it)
9351 {
9352 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9353 ComObjPtr<Medium> hd = (*it)->getMedium();
9354
9355 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9356 pllRegistriesThatNeedSaving);
9357 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9358 mrc = rc;
9359 }
9360
9361 alock.enter();
9362
9363 if (mData->mMachineState == MachineState_SettingUp)
9364 setMachineState(oldState);
9365 }
9366
9367 return mrc;
9368}
9369
9370/**
9371 * Looks through the given list of media attachments for one with the given parameters
9372 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9373 * can be searched as well if needed.
9374 *
9375 * @param list
9376 * @param aControllerName
9377 * @param aControllerPort
9378 * @param aDevice
9379 * @return
9380 */
9381MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9382 IN_BSTR aControllerName,
9383 LONG aControllerPort,
9384 LONG aDevice)
9385{
9386 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9387 it != ll.end();
9388 ++it)
9389 {
9390 MediumAttachment *pAttach = *it;
9391 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9392 return pAttach;
9393 }
9394
9395 return NULL;
9396}
9397
9398/**
9399 * Looks through the given list of media attachments for one with the given parameters
9400 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9401 * can be searched as well if needed.
9402 *
9403 * @param list
9404 * @param aControllerName
9405 * @param aControllerPort
9406 * @param aDevice
9407 * @return
9408 */
9409MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9410 ComObjPtr<Medium> pMedium)
9411{
9412 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9413 it != ll.end();
9414 ++it)
9415 {
9416 MediumAttachment *pAttach = *it;
9417 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9418 if (pMediumThis == pMedium)
9419 return pAttach;
9420 }
9421
9422 return NULL;
9423}
9424
9425/**
9426 * Looks through the given list of media attachments for one with the given parameters
9427 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9428 * can be searched as well if needed.
9429 *
9430 * @param list
9431 * @param aControllerName
9432 * @param aControllerPort
9433 * @param aDevice
9434 * @return
9435 */
9436MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9437 Guid &id)
9438{
9439 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9440 it != ll.end();
9441 ++it)
9442 {
9443 MediumAttachment *pAttach = *it;
9444 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9445 if (pMediumThis->getId() == id)
9446 return pAttach;
9447 }
9448
9449 return NULL;
9450}
9451
9452/**
9453 * Main implementation for Machine::DetachDevice. This also gets called
9454 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9455 *
9456 * @param pAttach Medium attachment to detach.
9457 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9458 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9459 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9460 * @return
9461 */
9462HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9463 AutoWriteLock &writeLock,
9464 Snapshot *pSnapshot,
9465 GuidList *pllRegistriesThatNeedSaving)
9466{
9467 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9468 DeviceType_T mediumType = pAttach->getType();
9469
9470 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9471
9472 if (pAttach->isImplicit())
9473 {
9474 /* attempt to implicitly delete the implicitly created diff */
9475
9476 /// @todo move the implicit flag from MediumAttachment to Medium
9477 /// and forbid any hard disk operation when it is implicit. Or maybe
9478 /// a special media state for it to make it even more simple.
9479
9480 Assert(mMediaData.isBackedUp());
9481
9482 /* will leave the lock before the potentially lengthy operation, so
9483 * protect with the special state */
9484 MachineState_T oldState = mData->mMachineState;
9485 setMachineState(MachineState_SettingUp);
9486
9487 writeLock.release();
9488
9489 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
9490 true /*aWait*/,
9491 pllRegistriesThatNeedSaving);
9492
9493 writeLock.acquire();
9494
9495 setMachineState(oldState);
9496
9497 if (FAILED(rc)) return rc;
9498 }
9499
9500 setModified(IsModified_Storage);
9501 mMediaData.backup();
9502
9503 // we cannot use erase (it) below because backup() above will create
9504 // a copy of the list and make this copy active, but the iterator
9505 // still refers to the original and is not valid for the copy
9506 mMediaData->mAttachments.remove(pAttach);
9507
9508 if (!oldmedium.isNull())
9509 {
9510 // if this is from a snapshot, do not defer detachment to commitMedia()
9511 if (pSnapshot)
9512 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9513 // else if non-hard disk media, do not defer detachment to commitMedia() either
9514 else if (mediumType != DeviceType_HardDisk)
9515 oldmedium->removeBackReference(mData->mUuid);
9516 }
9517
9518 return S_OK;
9519}
9520
9521/**
9522 * Goes thru all media of the given list and
9523 *
9524 * 1) calls detachDevice() on each of them for this machine and
9525 * 2) adds all Medium objects found in the process to the given list,
9526 * depending on cleanupMode.
9527 *
9528 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
9529 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
9530 * media to the list.
9531 *
9532 * This gets called from Machine::Unregister, both for the actual Machine and
9533 * the SnapshotMachine objects that might be found in the snapshots.
9534 *
9535 * Requires caller and locking. The machine lock must be passed in because it
9536 * will be passed on to detachDevice which needs it for temporary unlocking.
9537 *
9538 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9539 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9540 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9541 * otherwise no media get added.
9542 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9543 * @return
9544 */
9545HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9546 Snapshot *pSnapshot,
9547 CleanupMode_T cleanupMode,
9548 MediaList &llMedia)
9549{
9550 Assert(isWriteLockOnCurrentThread());
9551
9552 HRESULT rc;
9553
9554 // make a temporary list because detachDevice invalidates iterators into
9555 // mMediaData->mAttachments
9556 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9557
9558 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9559 it != llAttachments2.end();
9560 ++it)
9561 {
9562 ComObjPtr<MediumAttachment> &pAttach = *it;
9563 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9564
9565 if (!pMedium.isNull())
9566 {
9567 DeviceType_T devType = pMedium->getDeviceType();
9568 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9569 && devType == DeviceType_HardDisk)
9570 || (cleanupMode == CleanupMode_Full)
9571 )
9572 llMedia.push_back(pMedium);
9573 }
9574
9575 // real machine: then we need to use the proper method
9576 rc = detachDevice(pAttach,
9577 writeLock,
9578 pSnapshot,
9579 NULL /* pfNeedsSaveSettings */);
9580
9581 if (FAILED(rc))
9582 return rc;
9583 }
9584
9585 return S_OK;
9586}
9587
9588/**
9589 * Perform deferred hard disk detachments.
9590 *
9591 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9592 * backed up).
9593 *
9594 * If @a aOnline is @c true then this method will also unlock the old hard disks
9595 * for which the new implicit diffs were created and will lock these new diffs for
9596 * writing.
9597 *
9598 * @param aOnline Whether the VM was online prior to this operation.
9599 *
9600 * @note Locks this object for writing!
9601 */
9602void Machine::commitMedia(bool aOnline /*= false*/)
9603{
9604 AutoCaller autoCaller(this);
9605 AssertComRCReturnVoid(autoCaller.rc());
9606
9607 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9608
9609 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9610
9611 HRESULT rc = S_OK;
9612
9613 /* no attach/detach operations -- nothing to do */
9614 if (!mMediaData.isBackedUp())
9615 return;
9616
9617 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9618 bool fMediaNeedsLocking = false;
9619
9620 /* enumerate new attachments */
9621 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9622 it != mMediaData->mAttachments.end();
9623 ++it)
9624 {
9625 MediumAttachment *pAttach = *it;
9626
9627 pAttach->commit();
9628
9629 Medium* pMedium = pAttach->getMedium();
9630 bool fImplicit = pAttach->isImplicit();
9631
9632 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9633 (pMedium) ? pMedium->getName().c_str() : "NULL",
9634 fImplicit));
9635
9636 /** @todo convert all this Machine-based voodoo to MediumAttachment
9637 * based commit logic. */
9638 if (fImplicit)
9639 {
9640 /* convert implicit attachment to normal */
9641 pAttach->setImplicit(false);
9642
9643 if ( aOnline
9644 && pMedium
9645 && pAttach->getType() == DeviceType_HardDisk
9646 )
9647 {
9648 ComObjPtr<Medium> parent = pMedium->getParent();
9649 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9650
9651 /* update the appropriate lock list */
9652 MediumLockList *pMediumLockList;
9653 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9654 AssertComRC(rc);
9655 if (pMediumLockList)
9656 {
9657 /* unlock if there's a need to change the locking */
9658 if (!fMediaNeedsLocking)
9659 {
9660 rc = mData->mSession.mLockedMedia.Unlock();
9661 AssertComRC(rc);
9662 fMediaNeedsLocking = true;
9663 }
9664 rc = pMediumLockList->Update(parent, false);
9665 AssertComRC(rc);
9666 rc = pMediumLockList->Append(pMedium, true);
9667 AssertComRC(rc);
9668 }
9669 }
9670
9671 continue;
9672 }
9673
9674 if (pMedium)
9675 {
9676 /* was this medium attached before? */
9677 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9678 oldIt != oldAtts.end();
9679 ++oldIt)
9680 {
9681 MediumAttachment *pOldAttach = *oldIt;
9682 if (pOldAttach->getMedium() == pMedium)
9683 {
9684 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9685
9686 /* yes: remove from old to avoid de-association */
9687 oldAtts.erase(oldIt);
9688 break;
9689 }
9690 }
9691 }
9692 }
9693
9694 /* enumerate remaining old attachments and de-associate from the
9695 * current machine state */
9696 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9697 it != oldAtts.end();
9698 ++it)
9699 {
9700 MediumAttachment *pAttach = *it;
9701 Medium* pMedium = pAttach->getMedium();
9702
9703 /* Detach only hard disks, since DVD/floppy media is detached
9704 * instantly in MountMedium. */
9705 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9706 {
9707 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9708
9709 /* now de-associate from the current machine state */
9710 rc = pMedium->removeBackReference(mData->mUuid);
9711 AssertComRC(rc);
9712
9713 if (aOnline)
9714 {
9715 /* unlock since medium is not used anymore */
9716 MediumLockList *pMediumLockList;
9717 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9718 AssertComRC(rc);
9719 if (pMediumLockList)
9720 {
9721 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9722 AssertComRC(rc);
9723 }
9724 }
9725 }
9726 }
9727
9728 /* take media locks again so that the locking state is consistent */
9729 if (fMediaNeedsLocking)
9730 {
9731 Assert(aOnline);
9732 rc = mData->mSession.mLockedMedia.Lock();
9733 AssertComRC(rc);
9734 }
9735
9736 /* commit the hard disk changes */
9737 mMediaData.commit();
9738
9739 if (isSessionMachine())
9740 {
9741 /*
9742 * Update the parent machine to point to the new owner.
9743 * This is necessary because the stored parent will point to the
9744 * session machine otherwise and cause crashes or errors later
9745 * when the session machine gets invalid.
9746 */
9747 /** @todo Change the MediumAttachment class to behave like any other
9748 * class in this regard by creating peer MediumAttachment
9749 * objects for session machines and share the data with the peer
9750 * machine.
9751 */
9752 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9753 it != mMediaData->mAttachments.end();
9754 ++it)
9755 {
9756 (*it)->updateParentMachine(mPeer);
9757 }
9758
9759 /* attach new data to the primary machine and reshare it */
9760 mPeer->mMediaData.attach(mMediaData);
9761 }
9762
9763 return;
9764}
9765
9766/**
9767 * Perform deferred deletion of implicitly created diffs.
9768 *
9769 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9770 * backed up).
9771 *
9772 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9773 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9774 *
9775 * @note Locks this object for writing!
9776 *
9777 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
9778 */
9779void Machine::rollbackMedia()
9780{
9781 AutoCaller autoCaller(this);
9782 AssertComRCReturnVoid (autoCaller.rc());
9783
9784 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9785
9786 LogFlowThisFunc(("Entering\n"));
9787
9788 HRESULT rc = S_OK;
9789
9790 /* no attach/detach operations -- nothing to do */
9791 if (!mMediaData.isBackedUp())
9792 return;
9793
9794 /* enumerate new attachments */
9795 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9796 it != mMediaData->mAttachments.end();
9797 ++it)
9798 {
9799 MediumAttachment *pAttach = *it;
9800 /* Fix up the backrefs for DVD/floppy media. */
9801 if (pAttach->getType() != DeviceType_HardDisk)
9802 {
9803 Medium* pMedium = pAttach->getMedium();
9804 if (pMedium)
9805 {
9806 rc = pMedium->removeBackReference(mData->mUuid);
9807 AssertComRC(rc);
9808 }
9809 }
9810
9811 (*it)->rollback();
9812
9813 pAttach = *it;
9814 /* Fix up the backrefs for DVD/floppy media. */
9815 if (pAttach->getType() != DeviceType_HardDisk)
9816 {
9817 Medium* pMedium = pAttach->getMedium();
9818 if (pMedium)
9819 {
9820 rc = pMedium->addBackReference(mData->mUuid);
9821 AssertComRC(rc);
9822 }
9823 }
9824 }
9825
9826 /** @todo convert all this Machine-based voodoo to MediumAttachment
9827 * based rollback logic. */
9828 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9829 // which gets called if Machine::registeredInit() fails...
9830 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9831
9832 return;
9833}
9834
9835/**
9836 * Returns true if the settings file is located in the directory named exactly
9837 * as the machine; this means, among other things, that the machine directory
9838 * should be auto-renamed.
9839 *
9840 * @param aSettingsDir if not NULL, the full machine settings file directory
9841 * name will be assigned there.
9842 *
9843 * @note Doesn't lock anything.
9844 * @note Not thread safe (must be called from this object's lock).
9845 */
9846bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9847{
9848 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9849 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9850 if (aSettingsDir)
9851 *aSettingsDir = strMachineDirName;
9852 strMachineDirName.stripPath(); // vmname
9853 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9854 strConfigFileOnly.stripPath() // vmname.vbox
9855 .stripExt(); // vmname
9856
9857 AssertReturn(!strMachineDirName.isEmpty(), false);
9858 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9859
9860 return strMachineDirName == strConfigFileOnly;
9861}
9862
9863/**
9864 * Discards all changes to machine settings.
9865 *
9866 * @param aNotify Whether to notify the direct session about changes or not.
9867 *
9868 * @note Locks objects for writing!
9869 */
9870void Machine::rollback(bool aNotify)
9871{
9872 AutoCaller autoCaller(this);
9873 AssertComRCReturn(autoCaller.rc(), (void)0);
9874
9875 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9876
9877 if (!mStorageControllers.isNull())
9878 {
9879 if (mStorageControllers.isBackedUp())
9880 {
9881 /* unitialize all new devices (absent in the backed up list). */
9882 StorageControllerList::const_iterator it = mStorageControllers->begin();
9883 StorageControllerList *backedList = mStorageControllers.backedUpData();
9884 while (it != mStorageControllers->end())
9885 {
9886 if ( std::find(backedList->begin(), backedList->end(), *it)
9887 == backedList->end()
9888 )
9889 {
9890 (*it)->uninit();
9891 }
9892 ++it;
9893 }
9894
9895 /* restore the list */
9896 mStorageControllers.rollback();
9897 }
9898
9899 /* rollback any changes to devices after restoring the list */
9900 if (mData->flModifications & IsModified_Storage)
9901 {
9902 StorageControllerList::const_iterator it = mStorageControllers->begin();
9903 while (it != mStorageControllers->end())
9904 {
9905 (*it)->rollback();
9906 ++it;
9907 }
9908 }
9909 }
9910
9911 mUserData.rollback();
9912
9913 mHWData.rollback();
9914
9915 if (mData->flModifications & IsModified_Storage)
9916 rollbackMedia();
9917
9918 if (mBIOSSettings)
9919 mBIOSSettings->rollback();
9920
9921 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9922 mVRDEServer->rollback();
9923
9924 if (mAudioAdapter)
9925 mAudioAdapter->rollback();
9926
9927 if (mUSBController && (mData->flModifications & IsModified_USB))
9928 mUSBController->rollback();
9929
9930 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
9931 mBandwidthControl->rollback();
9932
9933 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9934 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9935 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9936
9937 if (mData->flModifications & IsModified_NetworkAdapters)
9938 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9939 if ( mNetworkAdapters[slot]
9940 && mNetworkAdapters[slot]->isModified())
9941 {
9942 mNetworkAdapters[slot]->rollback();
9943 networkAdapters[slot] = mNetworkAdapters[slot];
9944 }
9945
9946 if (mData->flModifications & IsModified_SerialPorts)
9947 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9948 if ( mSerialPorts[slot]
9949 && mSerialPorts[slot]->isModified())
9950 {
9951 mSerialPorts[slot]->rollback();
9952 serialPorts[slot] = mSerialPorts[slot];
9953 }
9954
9955 if (mData->flModifications & IsModified_ParallelPorts)
9956 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9957 if ( mParallelPorts[slot]
9958 && mParallelPorts[slot]->isModified())
9959 {
9960 mParallelPorts[slot]->rollback();
9961 parallelPorts[slot] = mParallelPorts[slot];
9962 }
9963
9964 if (aNotify)
9965 {
9966 /* inform the direct session about changes */
9967
9968 ComObjPtr<Machine> that = this;
9969 uint32_t flModifications = mData->flModifications;
9970 alock.leave();
9971
9972 if (flModifications & IsModified_SharedFolders)
9973 that->onSharedFolderChange();
9974
9975 if (flModifications & IsModified_VRDEServer)
9976 that->onVRDEServerChange(/* aRestart */ TRUE);
9977 if (flModifications & IsModified_USB)
9978 that->onUSBControllerChange();
9979
9980 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9981 if (networkAdapters[slot])
9982 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9983 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9984 if (serialPorts[slot])
9985 that->onSerialPortChange(serialPorts[slot]);
9986 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9987 if (parallelPorts[slot])
9988 that->onParallelPortChange(parallelPorts[slot]);
9989
9990 if (flModifications & IsModified_Storage)
9991 that->onStorageControllerChange();
9992
9993#if 0
9994 if (flModifications & IsModified_BandwidthControl)
9995 that->onBandwidthControlChange();
9996#endif
9997 }
9998}
9999
10000/**
10001 * Commits all the changes to machine settings.
10002 *
10003 * Note that this operation is supposed to never fail.
10004 *
10005 * @note Locks this object and children for writing.
10006 */
10007void Machine::commit()
10008{
10009 AutoCaller autoCaller(this);
10010 AssertComRCReturnVoid(autoCaller.rc());
10011
10012 AutoCaller peerCaller(mPeer);
10013 AssertComRCReturnVoid(peerCaller.rc());
10014
10015 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
10016
10017 /*
10018 * use safe commit to ensure Snapshot machines (that share mUserData)
10019 * will still refer to a valid memory location
10020 */
10021 mUserData.commitCopy();
10022
10023 mHWData.commit();
10024
10025 if (mMediaData.isBackedUp())
10026 commitMedia();
10027
10028 mBIOSSettings->commit();
10029 mVRDEServer->commit();
10030 mAudioAdapter->commit();
10031 mUSBController->commit();
10032 mBandwidthControl->commit();
10033
10034 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10035 mNetworkAdapters[slot]->commit();
10036 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10037 mSerialPorts[slot]->commit();
10038 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10039 mParallelPorts[slot]->commit();
10040
10041 bool commitStorageControllers = false;
10042
10043 if (mStorageControllers.isBackedUp())
10044 {
10045 mStorageControllers.commit();
10046
10047 if (mPeer)
10048 {
10049 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
10050
10051 /* Commit all changes to new controllers (this will reshare data with
10052 * peers for those who have peers) */
10053 StorageControllerList *newList = new StorageControllerList();
10054 StorageControllerList::const_iterator it = mStorageControllers->begin();
10055 while (it != mStorageControllers->end())
10056 {
10057 (*it)->commit();
10058
10059 /* look if this controller has a peer device */
10060 ComObjPtr<StorageController> peer = (*it)->getPeer();
10061 if (!peer)
10062 {
10063 /* no peer means the device is a newly created one;
10064 * create a peer owning data this device share it with */
10065 peer.createObject();
10066 peer->init(mPeer, *it, true /* aReshare */);
10067 }
10068 else
10069 {
10070 /* remove peer from the old list */
10071 mPeer->mStorageControllers->remove(peer);
10072 }
10073 /* and add it to the new list */
10074 newList->push_back(peer);
10075
10076 ++it;
10077 }
10078
10079 /* uninit old peer's controllers that are left */
10080 it = mPeer->mStorageControllers->begin();
10081 while (it != mPeer->mStorageControllers->end())
10082 {
10083 (*it)->uninit();
10084 ++it;
10085 }
10086
10087 /* attach new list of controllers to our peer */
10088 mPeer->mStorageControllers.attach(newList);
10089 }
10090 else
10091 {
10092 /* we have no peer (our parent is the newly created machine);
10093 * just commit changes to devices */
10094 commitStorageControllers = true;
10095 }
10096 }
10097 else
10098 {
10099 /* the list of controllers itself is not changed,
10100 * just commit changes to controllers themselves */
10101 commitStorageControllers = true;
10102 }
10103
10104 if (commitStorageControllers)
10105 {
10106 StorageControllerList::const_iterator it = mStorageControllers->begin();
10107 while (it != mStorageControllers->end())
10108 {
10109 (*it)->commit();
10110 ++it;
10111 }
10112 }
10113
10114 if (isSessionMachine())
10115 {
10116 /* attach new data to the primary machine and reshare it */
10117 mPeer->mUserData.attach(mUserData);
10118 mPeer->mHWData.attach(mHWData);
10119 /* mMediaData is reshared by fixupMedia */
10120 // mPeer->mMediaData.attach(mMediaData);
10121 Assert(mPeer->mMediaData.data() == mMediaData.data());
10122 }
10123}
10124
10125/**
10126 * Copies all the hardware data from the given machine.
10127 *
10128 * Currently, only called when the VM is being restored from a snapshot. In
10129 * particular, this implies that the VM is not running during this method's
10130 * call.
10131 *
10132 * @note This method must be called from under this object's lock.
10133 *
10134 * @note This method doesn't call #commit(), so all data remains backed up and
10135 * unsaved.
10136 */
10137void Machine::copyFrom(Machine *aThat)
10138{
10139 AssertReturnVoid(!isSnapshotMachine());
10140 AssertReturnVoid(aThat->isSnapshotMachine());
10141
10142 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
10143
10144 mHWData.assignCopy(aThat->mHWData);
10145
10146 // create copies of all shared folders (mHWData after attaching a copy
10147 // contains just references to original objects)
10148 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10149 it != mHWData->mSharedFolders.end();
10150 ++it)
10151 {
10152 ComObjPtr<SharedFolder> folder;
10153 folder.createObject();
10154 HRESULT rc = folder->initCopy(getMachine(), *it);
10155 AssertComRC(rc);
10156 *it = folder;
10157 }
10158
10159 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
10160 mVRDEServer->copyFrom(aThat->mVRDEServer);
10161 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
10162 mUSBController->copyFrom(aThat->mUSBController);
10163 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10164
10165 /* create private copies of all controllers */
10166 mStorageControllers.backup();
10167 mStorageControllers->clear();
10168 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10169 it != aThat->mStorageControllers->end();
10170 ++it)
10171 {
10172 ComObjPtr<StorageController> ctrl;
10173 ctrl.createObject();
10174 ctrl->initCopy(this, *it);
10175 mStorageControllers->push_back(ctrl);
10176 }
10177
10178 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10179 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10180 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10181 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10182 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10183 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10184}
10185
10186/**
10187 * Returns whether the given storage controller is hotplug capable.
10188 *
10189 * @returns true if the controller supports hotplugging
10190 * false otherwise.
10191 * @param enmCtrlType The controller type to check for.
10192 */
10193bool Machine::isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
10194{
10195 switch (enmCtrlType)
10196 {
10197 case StorageControllerType_IntelAhci:
10198 return true;
10199 case StorageControllerType_LsiLogic:
10200 case StorageControllerType_LsiLogicSas:
10201 case StorageControllerType_BusLogic:
10202 case StorageControllerType_PIIX3:
10203 case StorageControllerType_PIIX4:
10204 case StorageControllerType_ICH6:
10205 case StorageControllerType_I82078:
10206 default:
10207 return false;
10208 }
10209}
10210
10211#ifdef VBOX_WITH_RESOURCE_USAGE_API
10212
10213void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10214{
10215 AssertReturnVoid(isWriteLockOnCurrentThread());
10216 AssertPtrReturnVoid(aCollector);
10217
10218 pm::CollectorHAL *hal = aCollector->getHAL();
10219 /* Create sub metrics */
10220 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10221 "Percentage of processor time spent in user mode by the VM process.");
10222 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10223 "Percentage of processor time spent in kernel mode by the VM process.");
10224 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10225 "Size of resident portion of VM process in memory.");
10226 /* Create and register base metrics */
10227 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10228 cpuLoadUser, cpuLoadKernel);
10229 aCollector->registerBaseMetric(cpuLoad);
10230 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10231 ramUsageUsed);
10232 aCollector->registerBaseMetric(ramUsage);
10233
10234 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10235 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10236 new pm::AggregateAvg()));
10237 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10238 new pm::AggregateMin()));
10239 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10240 new pm::AggregateMax()));
10241 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10242 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10243 new pm::AggregateAvg()));
10244 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10245 new pm::AggregateMin()));
10246 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10247 new pm::AggregateMax()));
10248
10249 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10250 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10251 new pm::AggregateAvg()));
10252 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10253 new pm::AggregateMin()));
10254 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10255 new pm::AggregateMax()));
10256
10257
10258 /* Guest metrics collector */
10259 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10260 aCollector->registerGuest(mCollectorGuest);
10261 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10262 this, __PRETTY_FUNCTION__, mCollectorGuest));
10263
10264 /* Create sub metrics */
10265 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10266 "Percentage of processor time spent in user mode as seen by the guest.");
10267 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10268 "Percentage of processor time spent in kernel mode as seen by the guest.");
10269 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10270 "Percentage of processor time spent idling as seen by the guest.");
10271
10272 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10273 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10274 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10275 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10276 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10277 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10278
10279 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10280
10281 /* Create and register base metrics */
10282 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10283 guestLoadUser, guestLoadKernel, guestLoadIdle);
10284 aCollector->registerBaseMetric(guestCpuLoad);
10285
10286 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10287 guestMemTotal, guestMemFree,
10288 guestMemBalloon, guestMemShared,
10289 guestMemCache, guestPagedTotal);
10290 aCollector->registerBaseMetric(guestCpuMem);
10291
10292 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10293 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10294 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10295 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
10296
10297 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
10298 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
10299 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
10300 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
10301
10302 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
10303 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
10304 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
10305 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
10306
10307 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
10308 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
10309 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
10310 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
10311
10312 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
10313 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
10314 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
10315 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
10316
10317 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
10318 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
10319 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
10320 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
10321
10322 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
10323 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
10324 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
10325 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
10326
10327 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
10328 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
10329 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
10330 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
10331
10332 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
10333 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
10334 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
10335 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
10336}
10337
10338void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
10339{
10340 AssertReturnVoid(isWriteLockOnCurrentThread());
10341
10342 if (aCollector)
10343 {
10344 aCollector->unregisterMetricsFor(aMachine);
10345 aCollector->unregisterBaseMetricsFor(aMachine);
10346 }
10347}
10348
10349#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10350
10351
10352////////////////////////////////////////////////////////////////////////////////
10353
10354DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
10355
10356HRESULT SessionMachine::FinalConstruct()
10357{
10358 LogFlowThisFunc(("\n"));
10359
10360#if defined(RT_OS_WINDOWS)
10361 mIPCSem = NULL;
10362#elif defined(RT_OS_OS2)
10363 mIPCSem = NULLHANDLE;
10364#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10365 mIPCSem = -1;
10366#else
10367# error "Port me!"
10368#endif
10369
10370 return BaseFinalConstruct();
10371}
10372
10373void SessionMachine::FinalRelease()
10374{
10375 LogFlowThisFunc(("\n"));
10376
10377 uninit(Uninit::Unexpected);
10378
10379 BaseFinalRelease();
10380}
10381
10382/**
10383 * @note Must be called only by Machine::openSession() from its own write lock.
10384 */
10385HRESULT SessionMachine::init(Machine *aMachine)
10386{
10387 LogFlowThisFuncEnter();
10388 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10389
10390 AssertReturn(aMachine, E_INVALIDARG);
10391
10392 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10393
10394 /* Enclose the state transition NotReady->InInit->Ready */
10395 AutoInitSpan autoInitSpan(this);
10396 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10397
10398 /* create the interprocess semaphore */
10399#if defined(RT_OS_WINDOWS)
10400 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10401 for (size_t i = 0; i < mIPCSemName.length(); i++)
10402 if (mIPCSemName.raw()[i] == '\\')
10403 mIPCSemName.raw()[i] = '/';
10404 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10405 ComAssertMsgRet(mIPCSem,
10406 ("Cannot create IPC mutex '%ls', err=%d",
10407 mIPCSemName.raw(), ::GetLastError()),
10408 E_FAIL);
10409#elif defined(RT_OS_OS2)
10410 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10411 aMachine->mData->mUuid.raw());
10412 mIPCSemName = ipcSem;
10413 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10414 ComAssertMsgRet(arc == NO_ERROR,
10415 ("Cannot create IPC mutex '%s', arc=%ld",
10416 ipcSem.c_str(), arc),
10417 E_FAIL);
10418#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10419# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10420# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10421 /** @todo Check that this still works correctly. */
10422 AssertCompileSize(key_t, 8);
10423# else
10424 AssertCompileSize(key_t, 4);
10425# endif
10426 key_t key;
10427 mIPCSem = -1;
10428 mIPCKey = "0";
10429 for (uint32_t i = 0; i < 1 << 24; i++)
10430 {
10431 key = ((uint32_t)'V' << 24) | i;
10432 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10433 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10434 {
10435 mIPCSem = sem;
10436 if (sem >= 0)
10437 mIPCKey = BstrFmt("%u", key);
10438 break;
10439 }
10440 }
10441# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10442 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10443 char *pszSemName = NULL;
10444 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10445 key_t key = ::ftok(pszSemName, 'V');
10446 RTStrFree(pszSemName);
10447
10448 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10449# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10450
10451 int errnoSave = errno;
10452 if (mIPCSem < 0 && errnoSave == ENOSYS)
10453 {
10454 setError(E_FAIL,
10455 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10456 "support for SysV IPC. Check the host kernel configuration for "
10457 "CONFIG_SYSVIPC=y"));
10458 return E_FAIL;
10459 }
10460 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10461 * the IPC semaphores */
10462 if (mIPCSem < 0 && errnoSave == ENOSPC)
10463 {
10464#ifdef RT_OS_LINUX
10465 setError(E_FAIL,
10466 tr("Cannot create IPC semaphore because the system limit for the "
10467 "maximum number of semaphore sets (SEMMNI), or the system wide "
10468 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10469 "current set of SysV IPC semaphores can be determined from "
10470 "the file /proc/sysvipc/sem"));
10471#else
10472 setError(E_FAIL,
10473 tr("Cannot create IPC semaphore because the system-imposed limit "
10474 "on the maximum number of allowed semaphores or semaphore "
10475 "identifiers system-wide would be exceeded"));
10476#endif
10477 return E_FAIL;
10478 }
10479 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10480 E_FAIL);
10481 /* set the initial value to 1 */
10482 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10483 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10484 E_FAIL);
10485#else
10486# error "Port me!"
10487#endif
10488
10489 /* memorize the peer Machine */
10490 unconst(mPeer) = aMachine;
10491 /* share the parent pointer */
10492 unconst(mParent) = aMachine->mParent;
10493
10494 /* take the pointers to data to share */
10495 mData.share(aMachine->mData);
10496 mSSData.share(aMachine->mSSData);
10497
10498 mUserData.share(aMachine->mUserData);
10499 mHWData.share(aMachine->mHWData);
10500 mMediaData.share(aMachine->mMediaData);
10501
10502 mStorageControllers.allocate();
10503 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10504 it != aMachine->mStorageControllers->end();
10505 ++it)
10506 {
10507 ComObjPtr<StorageController> ctl;
10508 ctl.createObject();
10509 ctl->init(this, *it);
10510 mStorageControllers->push_back(ctl);
10511 }
10512
10513 unconst(mBIOSSettings).createObject();
10514 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10515 /* create another VRDEServer object that will be mutable */
10516 unconst(mVRDEServer).createObject();
10517 mVRDEServer->init(this, aMachine->mVRDEServer);
10518 /* create another audio adapter object that will be mutable */
10519 unconst(mAudioAdapter).createObject();
10520 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10521 /* create a list of serial ports that will be mutable */
10522 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10523 {
10524 unconst(mSerialPorts[slot]).createObject();
10525 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10526 }
10527 /* create a list of parallel ports that will be mutable */
10528 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10529 {
10530 unconst(mParallelPorts[slot]).createObject();
10531 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10532 }
10533 /* create another USB controller object that will be mutable */
10534 unconst(mUSBController).createObject();
10535 mUSBController->init(this, aMachine->mUSBController);
10536
10537 /* create a list of network adapters that will be mutable */
10538 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10539 {
10540 unconst(mNetworkAdapters[slot]).createObject();
10541 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10542 }
10543
10544 /* create another bandwidth control object that will be mutable */
10545 unconst(mBandwidthControl).createObject();
10546 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10547
10548 /* default is to delete saved state on Saved -> PoweredOff transition */
10549 mRemoveSavedState = true;
10550
10551 /* Confirm a successful initialization when it's the case */
10552 autoInitSpan.setSucceeded();
10553
10554 LogFlowThisFuncLeave();
10555 return S_OK;
10556}
10557
10558/**
10559 * Uninitializes this session object. If the reason is other than
10560 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10561 *
10562 * @param aReason uninitialization reason
10563 *
10564 * @note Locks mParent + this object for writing.
10565 */
10566void SessionMachine::uninit(Uninit::Reason aReason)
10567{
10568 LogFlowThisFuncEnter();
10569 LogFlowThisFunc(("reason=%d\n", aReason));
10570
10571 /*
10572 * Strongly reference ourselves to prevent this object deletion after
10573 * mData->mSession.mMachine.setNull() below (which can release the last
10574 * reference and call the destructor). Important: this must be done before
10575 * accessing any members (and before AutoUninitSpan that does it as well).
10576 * This self reference will be released as the very last step on return.
10577 */
10578 ComObjPtr<SessionMachine> selfRef = this;
10579
10580 /* Enclose the state transition Ready->InUninit->NotReady */
10581 AutoUninitSpan autoUninitSpan(this);
10582 if (autoUninitSpan.uninitDone())
10583 {
10584 LogFlowThisFunc(("Already uninitialized\n"));
10585 LogFlowThisFuncLeave();
10586 return;
10587 }
10588
10589 if (autoUninitSpan.initFailed())
10590 {
10591 /* We've been called by init() because it's failed. It's not really
10592 * necessary (nor it's safe) to perform the regular uninit sequence
10593 * below, the following is enough.
10594 */
10595 LogFlowThisFunc(("Initialization failed.\n"));
10596#if defined(RT_OS_WINDOWS)
10597 if (mIPCSem)
10598 ::CloseHandle(mIPCSem);
10599 mIPCSem = NULL;
10600#elif defined(RT_OS_OS2)
10601 if (mIPCSem != NULLHANDLE)
10602 ::DosCloseMutexSem(mIPCSem);
10603 mIPCSem = NULLHANDLE;
10604#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10605 if (mIPCSem >= 0)
10606 ::semctl(mIPCSem, 0, IPC_RMID);
10607 mIPCSem = -1;
10608# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10609 mIPCKey = "0";
10610# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10611#else
10612# error "Port me!"
10613#endif
10614 uninitDataAndChildObjects();
10615 mData.free();
10616 unconst(mParent) = NULL;
10617 unconst(mPeer) = NULL;
10618 LogFlowThisFuncLeave();
10619 return;
10620 }
10621
10622 MachineState_T lastState;
10623 {
10624 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10625 lastState = mData->mMachineState;
10626 }
10627 NOREF(lastState);
10628
10629#ifdef VBOX_WITH_USB
10630 // release all captured USB devices, but do this before requesting the locks below
10631 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10632 {
10633 /* Console::captureUSBDevices() is called in the VM process only after
10634 * setting the machine state to Starting or Restoring.
10635 * Console::detachAllUSBDevices() will be called upon successful
10636 * termination. So, we need to release USB devices only if there was
10637 * an abnormal termination of a running VM.
10638 *
10639 * This is identical to SessionMachine::DetachAllUSBDevices except
10640 * for the aAbnormal argument. */
10641 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10642 AssertComRC(rc);
10643 NOREF(rc);
10644
10645 USBProxyService *service = mParent->host()->usbProxyService();
10646 if (service)
10647 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10648 }
10649#endif /* VBOX_WITH_USB */
10650
10651 // we need to lock this object in uninit() because the lock is shared
10652 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10653 // and others need mParent lock, and USB needs host lock.
10654 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10655
10656 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10657 this, __PRETTY_FUNCTION__, mCollectorGuest));
10658 if (mCollectorGuest)
10659 {
10660 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
10661 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
10662 mCollectorGuest = NULL;
10663 }
10664#if 0
10665 // Trigger async cleanup tasks, avoid doing things here which are not
10666 // vital to be done immediately and maybe need more locks. This calls
10667 // Machine::unregisterMetrics().
10668 mParent->onMachineUninit(mPeer);
10669#else
10670 /*
10671 * It is safe to call Machine::unregisterMetrics() here because
10672 * PerformanceCollector::samplerCallback no longer accesses guest methods
10673 * holding the lock.
10674 */
10675 unregisterMetrics(mParent->performanceCollector(), mPeer);
10676#endif
10677
10678 if (aReason == Uninit::Abnormal)
10679 {
10680 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10681 Global::IsOnlineOrTransient(lastState)));
10682
10683 /* reset the state to Aborted */
10684 if (mData->mMachineState != MachineState_Aborted)
10685 setMachineState(MachineState_Aborted);
10686 }
10687
10688 // any machine settings modified?
10689 if (mData->flModifications)
10690 {
10691 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10692 rollback(false /* aNotify */);
10693 }
10694
10695 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
10696 || !mConsoleTaskData.mSnapshot);
10697 if (!mConsoleTaskData.strStateFilePath.isEmpty())
10698 {
10699 LogWarningThisFunc(("canceling failed save state request!\n"));
10700 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10701 }
10702 else if (!mConsoleTaskData.mSnapshot.isNull())
10703 {
10704 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10705
10706 /* delete all differencing hard disks created (this will also attach
10707 * their parents back by rolling back mMediaData) */
10708 rollbackMedia();
10709
10710 // delete the saved state file (it might have been already created)
10711 // AFTER killing the snapshot so that releaseSavedStateFile() won't
10712 // think it's still in use
10713 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
10714 mConsoleTaskData.mSnapshot->uninit();
10715 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
10716 }
10717
10718 if (!mData->mSession.mType.isEmpty())
10719 {
10720 /* mType is not null when this machine's process has been started by
10721 * Machine::LaunchVMProcess(), therefore it is our child. We
10722 * need to queue the PID to reap the process (and avoid zombies on
10723 * Linux). */
10724 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10725 mParent->addProcessToReap(mData->mSession.mPid);
10726 }
10727
10728 mData->mSession.mPid = NIL_RTPROCESS;
10729
10730 if (aReason == Uninit::Unexpected)
10731 {
10732 /* Uninitialization didn't come from #checkForDeath(), so tell the
10733 * client watcher thread to update the set of machines that have open
10734 * sessions. */
10735 mParent->updateClientWatcher();
10736 }
10737
10738 /* uninitialize all remote controls */
10739 if (mData->mSession.mRemoteControls.size())
10740 {
10741 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10742 mData->mSession.mRemoteControls.size()));
10743
10744 Data::Session::RemoteControlList::iterator it =
10745 mData->mSession.mRemoteControls.begin();
10746 while (it != mData->mSession.mRemoteControls.end())
10747 {
10748 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10749 HRESULT rc = (*it)->Uninitialize();
10750 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10751 if (FAILED(rc))
10752 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10753 ++it;
10754 }
10755 mData->mSession.mRemoteControls.clear();
10756 }
10757
10758 /*
10759 * An expected uninitialization can come only from #checkForDeath().
10760 * Otherwise it means that something's gone really wrong (for example,
10761 * the Session implementation has released the VirtualBox reference
10762 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10763 * etc). However, it's also possible, that the client releases the IPC
10764 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10765 * but the VirtualBox release event comes first to the server process.
10766 * This case is practically possible, so we should not assert on an
10767 * unexpected uninit, just log a warning.
10768 */
10769
10770 if ((aReason == Uninit::Unexpected))
10771 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10772
10773 if (aReason != Uninit::Normal)
10774 {
10775 mData->mSession.mDirectControl.setNull();
10776 }
10777 else
10778 {
10779 /* this must be null here (see #OnSessionEnd()) */
10780 Assert(mData->mSession.mDirectControl.isNull());
10781 Assert(mData->mSession.mState == SessionState_Unlocking);
10782 Assert(!mData->mSession.mProgress.isNull());
10783 }
10784 if (mData->mSession.mProgress)
10785 {
10786 if (aReason == Uninit::Normal)
10787 mData->mSession.mProgress->notifyComplete(S_OK);
10788 else
10789 mData->mSession.mProgress->notifyComplete(E_FAIL,
10790 COM_IIDOF(ISession),
10791 getComponentName(),
10792 tr("The VM session was aborted"));
10793 mData->mSession.mProgress.setNull();
10794 }
10795
10796 /* remove the association between the peer machine and this session machine */
10797 Assert( (SessionMachine*)mData->mSession.mMachine == this
10798 || aReason == Uninit::Unexpected);
10799
10800 /* reset the rest of session data */
10801 mData->mSession.mMachine.setNull();
10802 mData->mSession.mState = SessionState_Unlocked;
10803 mData->mSession.mType.setNull();
10804
10805 /* close the interprocess semaphore before leaving the exclusive lock */
10806#if defined(RT_OS_WINDOWS)
10807 if (mIPCSem)
10808 ::CloseHandle(mIPCSem);
10809 mIPCSem = NULL;
10810#elif defined(RT_OS_OS2)
10811 if (mIPCSem != NULLHANDLE)
10812 ::DosCloseMutexSem(mIPCSem);
10813 mIPCSem = NULLHANDLE;
10814#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10815 if (mIPCSem >= 0)
10816 ::semctl(mIPCSem, 0, IPC_RMID);
10817 mIPCSem = -1;
10818# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10819 mIPCKey = "0";
10820# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10821#else
10822# error "Port me!"
10823#endif
10824
10825 /* fire an event */
10826 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10827
10828 uninitDataAndChildObjects();
10829
10830 /* free the essential data structure last */
10831 mData.free();
10832
10833#if 1 /** @todo Please review this change! (bird) */
10834 /* drop the exclusive lock before setting the below two to NULL */
10835 multilock.release();
10836#else
10837 /* leave the exclusive lock before setting the below two to NULL */
10838 multilock.leave();
10839#endif
10840
10841 unconst(mParent) = NULL;
10842 unconst(mPeer) = NULL;
10843
10844 LogFlowThisFuncLeave();
10845}
10846
10847// util::Lockable interface
10848////////////////////////////////////////////////////////////////////////////////
10849
10850/**
10851 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10852 * with the primary Machine instance (mPeer).
10853 */
10854RWLockHandle *SessionMachine::lockHandle() const
10855{
10856 AssertReturn(mPeer != NULL, NULL);
10857 return mPeer->lockHandle();
10858}
10859
10860// IInternalMachineControl methods
10861////////////////////////////////////////////////////////////////////////////////
10862
10863/**
10864 * @note Locks this object for writing.
10865 */
10866STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10867{
10868 AutoCaller autoCaller(this);
10869 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10870
10871 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10872
10873 mRemoveSavedState = aRemove;
10874
10875 return S_OK;
10876}
10877
10878/**
10879 * @note Locks the same as #setMachineState() does.
10880 */
10881STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10882{
10883 return setMachineState(aMachineState);
10884}
10885
10886/**
10887 * @note Locks this object for reading.
10888 */
10889STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10890{
10891 AutoCaller autoCaller(this);
10892 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10893
10894 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10895
10896#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10897 mIPCSemName.cloneTo(aId);
10898 return S_OK;
10899#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10900# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10901 mIPCKey.cloneTo(aId);
10902# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10903 mData->m_strConfigFileFull.cloneTo(aId);
10904# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10905 return S_OK;
10906#else
10907# error "Port me!"
10908#endif
10909}
10910
10911/**
10912 * @note Locks this object for writing.
10913 */
10914STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10915{
10916 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10917 AutoCaller autoCaller(this);
10918 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10919
10920 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10921
10922 if (mData->mSession.mState != SessionState_Locked)
10923 return VBOX_E_INVALID_OBJECT_STATE;
10924
10925 if (!mData->mSession.mProgress.isNull())
10926 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10927
10928 LogFlowThisFunc(("returns S_OK.\n"));
10929 return S_OK;
10930}
10931
10932/**
10933 * @note Locks this object for writing.
10934 */
10935STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10936{
10937 AutoCaller autoCaller(this);
10938 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10939
10940 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10941
10942 if (mData->mSession.mState != SessionState_Locked)
10943 return VBOX_E_INVALID_OBJECT_STATE;
10944
10945 /* Finalize the LaunchVMProcess progress object. */
10946 if (mData->mSession.mProgress)
10947 {
10948 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10949 mData->mSession.mProgress.setNull();
10950 }
10951
10952 if (SUCCEEDED((HRESULT)iResult))
10953 {
10954#ifdef VBOX_WITH_RESOURCE_USAGE_API
10955 /* The VM has been powered up successfully, so it makes sense
10956 * now to offer the performance metrics for a running machine
10957 * object. Doing it earlier wouldn't be safe. */
10958 registerMetrics(mParent->performanceCollector(), mPeer,
10959 mData->mSession.mPid);
10960#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10961 }
10962
10963 return S_OK;
10964}
10965
10966/**
10967 * @note Locks this object for writing.
10968 */
10969STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
10970{
10971 LogFlowThisFuncEnter();
10972
10973 CheckComArgOutPointerValid(aProgress);
10974
10975 AutoCaller autoCaller(this);
10976 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10977
10978 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10979
10980 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
10981 E_FAIL);
10982
10983 /* create a progress object to track operation completion */
10984 ComObjPtr<Progress> pProgress;
10985 pProgress.createObject();
10986 pProgress->init(getVirtualBox(),
10987 static_cast<IMachine *>(this) /* aInitiator */,
10988 Bstr(tr("Stopping the virtual machine")).raw(),
10989 FALSE /* aCancelable */);
10990
10991 /* fill in the console task data */
10992 mConsoleTaskData.mLastState = mData->mMachineState;
10993 mConsoleTaskData.mProgress = pProgress;
10994
10995 /* set the state to Stopping (this is expected by Console::PowerDown()) */
10996 setMachineState(MachineState_Stopping);
10997
10998 pProgress.queryInterfaceTo(aProgress);
10999
11000 return S_OK;
11001}
11002
11003/**
11004 * @note Locks this object for writing.
11005 */
11006STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
11007{
11008 LogFlowThisFuncEnter();
11009
11010 AutoCaller autoCaller(this);
11011 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11012
11013 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11014
11015 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
11016 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
11017 && mConsoleTaskData.mLastState != MachineState_Null,
11018 E_FAIL);
11019
11020 /*
11021 * On failure, set the state to the state we had when BeginPoweringDown()
11022 * was called (this is expected by Console::PowerDown() and the associated
11023 * task). On success the VM process already changed the state to
11024 * MachineState_PoweredOff, so no need to do anything.
11025 */
11026 if (FAILED(iResult))
11027 setMachineState(mConsoleTaskData.mLastState);
11028
11029 /* notify the progress object about operation completion */
11030 Assert(mConsoleTaskData.mProgress);
11031 if (SUCCEEDED(iResult))
11032 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11033 else
11034 {
11035 Utf8Str strErrMsg(aErrMsg);
11036 if (strErrMsg.length())
11037 mConsoleTaskData.mProgress->notifyComplete(iResult,
11038 COM_IIDOF(ISession),
11039 getComponentName(),
11040 strErrMsg.c_str());
11041 else
11042 mConsoleTaskData.mProgress->notifyComplete(iResult);
11043 }
11044
11045 /* clear out the temporary saved state data */
11046 mConsoleTaskData.mLastState = MachineState_Null;
11047 mConsoleTaskData.mProgress.setNull();
11048
11049 LogFlowThisFuncLeave();
11050 return S_OK;
11051}
11052
11053
11054/**
11055 * Goes through the USB filters of the given machine to see if the given
11056 * device matches any filter or not.
11057 *
11058 * @note Locks the same as USBController::hasMatchingFilter() does.
11059 */
11060STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
11061 BOOL *aMatched,
11062 ULONG *aMaskedIfs)
11063{
11064 LogFlowThisFunc(("\n"));
11065
11066 CheckComArgNotNull(aUSBDevice);
11067 CheckComArgOutPointerValid(aMatched);
11068
11069 AutoCaller autoCaller(this);
11070 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11071
11072#ifdef VBOX_WITH_USB
11073 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
11074#else
11075 NOREF(aUSBDevice);
11076 NOREF(aMaskedIfs);
11077 *aMatched = FALSE;
11078#endif
11079
11080 return S_OK;
11081}
11082
11083/**
11084 * @note Locks the same as Host::captureUSBDevice() does.
11085 */
11086STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
11087{
11088 LogFlowThisFunc(("\n"));
11089
11090 AutoCaller autoCaller(this);
11091 AssertComRCReturnRC(autoCaller.rc());
11092
11093#ifdef VBOX_WITH_USB
11094 /* if captureDeviceForVM() fails, it must have set extended error info */
11095 clearError();
11096 MultiResult rc = mParent->host()->checkUSBProxyService();
11097 if (FAILED(rc)) return rc;
11098
11099 USBProxyService *service = mParent->host()->usbProxyService();
11100 AssertReturn(service, E_FAIL);
11101 return service->captureDeviceForVM(this, Guid(aId).ref());
11102#else
11103 NOREF(aId);
11104 return E_NOTIMPL;
11105#endif
11106}
11107
11108/**
11109 * @note Locks the same as Host::detachUSBDevice() does.
11110 */
11111STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
11112{
11113 LogFlowThisFunc(("\n"));
11114
11115 AutoCaller autoCaller(this);
11116 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11117
11118#ifdef VBOX_WITH_USB
11119 USBProxyService *service = mParent->host()->usbProxyService();
11120 AssertReturn(service, E_FAIL);
11121 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
11122#else
11123 NOREF(aId);
11124 NOREF(aDone);
11125 return E_NOTIMPL;
11126#endif
11127}
11128
11129/**
11130 * Inserts all machine filters to the USB proxy service and then calls
11131 * Host::autoCaptureUSBDevices().
11132 *
11133 * Called by Console from the VM process upon VM startup.
11134 *
11135 * @note Locks what called methods lock.
11136 */
11137STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
11138{
11139 LogFlowThisFunc(("\n"));
11140
11141 AutoCaller autoCaller(this);
11142 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11143
11144#ifdef VBOX_WITH_USB
11145 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
11146 AssertComRC(rc);
11147 NOREF(rc);
11148
11149 USBProxyService *service = mParent->host()->usbProxyService();
11150 AssertReturn(service, E_FAIL);
11151 return service->autoCaptureDevicesForVM(this);
11152#else
11153 return S_OK;
11154#endif
11155}
11156
11157/**
11158 * Removes all machine filters from the USB proxy service and then calls
11159 * Host::detachAllUSBDevices().
11160 *
11161 * Called by Console from the VM process upon normal VM termination or by
11162 * SessionMachine::uninit() upon abnormal VM termination (from under the
11163 * Machine/SessionMachine lock).
11164 *
11165 * @note Locks what called methods lock.
11166 */
11167STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
11168{
11169 LogFlowThisFunc(("\n"));
11170
11171 AutoCaller autoCaller(this);
11172 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11173
11174#ifdef VBOX_WITH_USB
11175 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11176 AssertComRC(rc);
11177 NOREF(rc);
11178
11179 USBProxyService *service = mParent->host()->usbProxyService();
11180 AssertReturn(service, E_FAIL);
11181 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
11182#else
11183 NOREF(aDone);
11184 return S_OK;
11185#endif
11186}
11187
11188/**
11189 * @note Locks this object for writing.
11190 */
11191STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
11192 IProgress **aProgress)
11193{
11194 LogFlowThisFuncEnter();
11195
11196 AssertReturn(aSession, E_INVALIDARG);
11197 AssertReturn(aProgress, E_INVALIDARG);
11198
11199 AutoCaller autoCaller(this);
11200
11201 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11202 /*
11203 * We don't assert below because it might happen that a non-direct session
11204 * informs us it is closed right after we've been uninitialized -- it's ok.
11205 */
11206 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11207
11208 /* get IInternalSessionControl interface */
11209 ComPtr<IInternalSessionControl> control(aSession);
11210
11211 ComAssertRet(!control.isNull(), E_INVALIDARG);
11212
11213 /* Creating a Progress object requires the VirtualBox lock, and
11214 * thus locking it here is required by the lock order rules. */
11215 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
11216
11217 if (control == mData->mSession.mDirectControl)
11218 {
11219 ComAssertRet(aProgress, E_POINTER);
11220
11221 /* The direct session is being normally closed by the client process
11222 * ----------------------------------------------------------------- */
11223
11224 /* go to the closing state (essential for all open*Session() calls and
11225 * for #checkForDeath()) */
11226 Assert(mData->mSession.mState == SessionState_Locked);
11227 mData->mSession.mState = SessionState_Unlocking;
11228
11229 /* set direct control to NULL to release the remote instance */
11230 mData->mSession.mDirectControl.setNull();
11231 LogFlowThisFunc(("Direct control is set to NULL\n"));
11232
11233 if (mData->mSession.mProgress)
11234 {
11235 /* finalize the progress, someone might wait if a frontend
11236 * closes the session before powering on the VM. */
11237 mData->mSession.mProgress->notifyComplete(E_FAIL,
11238 COM_IIDOF(ISession),
11239 getComponentName(),
11240 tr("The VM session was closed before any attempt to power it on"));
11241 mData->mSession.mProgress.setNull();
11242 }
11243
11244 /* Create the progress object the client will use to wait until
11245 * #checkForDeath() is called to uninitialize this session object after
11246 * it releases the IPC semaphore.
11247 * Note! Because we're "reusing" mProgress here, this must be a proxy
11248 * object just like for LaunchVMProcess. */
11249 Assert(mData->mSession.mProgress.isNull());
11250 ComObjPtr<ProgressProxy> progress;
11251 progress.createObject();
11252 ComPtr<IUnknown> pPeer(mPeer);
11253 progress->init(mParent, pPeer,
11254 Bstr(tr("Closing session")).raw(),
11255 FALSE /* aCancelable */);
11256 progress.queryInterfaceTo(aProgress);
11257 mData->mSession.mProgress = progress;
11258 }
11259 else
11260 {
11261 /* the remote session is being normally closed */
11262 Data::Session::RemoteControlList::iterator it =
11263 mData->mSession.mRemoteControls.begin();
11264 while (it != mData->mSession.mRemoteControls.end())
11265 {
11266 if (control == *it)
11267 break;
11268 ++it;
11269 }
11270 BOOL found = it != mData->mSession.mRemoteControls.end();
11271 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11272 E_INVALIDARG);
11273 mData->mSession.mRemoteControls.remove(*it);
11274 }
11275
11276 LogFlowThisFuncLeave();
11277 return S_OK;
11278}
11279
11280/**
11281 * @note Locks this object for writing.
11282 */
11283STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11284{
11285 LogFlowThisFuncEnter();
11286
11287 CheckComArgOutPointerValid(aProgress);
11288 CheckComArgOutPointerValid(aStateFilePath);
11289
11290 AutoCaller autoCaller(this);
11291 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11292
11293 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11294
11295 AssertReturn( mData->mMachineState == MachineState_Paused
11296 && mConsoleTaskData.mLastState == MachineState_Null
11297 && mConsoleTaskData.strStateFilePath.isEmpty(),
11298 E_FAIL);
11299
11300 /* create a progress object to track operation completion */
11301 ComObjPtr<Progress> pProgress;
11302 pProgress.createObject();
11303 pProgress->init(getVirtualBox(),
11304 static_cast<IMachine *>(this) /* aInitiator */,
11305 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
11306 FALSE /* aCancelable */);
11307
11308 Utf8Str strStateFilePath;
11309 /* stateFilePath is null when the machine is not running */
11310 if (mData->mMachineState == MachineState_Paused)
11311 composeSavedStateFilename(strStateFilePath);
11312
11313 /* fill in the console task data */
11314 mConsoleTaskData.mLastState = mData->mMachineState;
11315 mConsoleTaskData.strStateFilePath = strStateFilePath;
11316 mConsoleTaskData.mProgress = pProgress;
11317
11318 /* set the state to Saving (this is expected by Console::SaveState()) */
11319 setMachineState(MachineState_Saving);
11320
11321 strStateFilePath.cloneTo(aStateFilePath);
11322 pProgress.queryInterfaceTo(aProgress);
11323
11324 return S_OK;
11325}
11326
11327/**
11328 * @note Locks mParent + this object for writing.
11329 */
11330STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
11331{
11332 LogFlowThisFunc(("\n"));
11333
11334 AutoCaller autoCaller(this);
11335 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11336
11337 /* endSavingState() need mParent lock */
11338 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11339
11340 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
11341 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
11342 && mConsoleTaskData.mLastState != MachineState_Null
11343 && !mConsoleTaskData.strStateFilePath.isEmpty(),
11344 E_FAIL);
11345
11346 /*
11347 * On failure, set the state to the state we had when BeginSavingState()
11348 * was called (this is expected by Console::SaveState() and the associated
11349 * task). On success the VM process already changed the state to
11350 * MachineState_Saved, so no need to do anything.
11351 */
11352 if (FAILED(iResult))
11353 setMachineState(mConsoleTaskData.mLastState);
11354
11355 return endSavingState(iResult, aErrMsg);
11356}
11357
11358/**
11359 * @note Locks this object for writing.
11360 */
11361STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
11362{
11363 LogFlowThisFunc(("\n"));
11364
11365 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
11366
11367 AutoCaller autoCaller(this);
11368 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11369
11370 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11371
11372 AssertReturn( mData->mMachineState == MachineState_PoweredOff
11373 || mData->mMachineState == MachineState_Teleported
11374 || mData->mMachineState == MachineState_Aborted
11375 , E_FAIL); /** @todo setError. */
11376
11377 Utf8Str stateFilePathFull = aSavedStateFile;
11378 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
11379 if (RT_FAILURE(vrc))
11380 return setError(VBOX_E_FILE_ERROR,
11381 tr("Invalid saved state file path '%ls' (%Rrc)"),
11382 aSavedStateFile,
11383 vrc);
11384
11385 mSSData->strStateFilePath = stateFilePathFull;
11386
11387 /* The below setMachineState() will detect the state transition and will
11388 * update the settings file */
11389
11390 return setMachineState(MachineState_Saved);
11391}
11392
11393STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
11394 ComSafeArrayOut(BSTR, aValues),
11395 ComSafeArrayOut(LONG64, aTimestamps),
11396 ComSafeArrayOut(BSTR, aFlags))
11397{
11398 LogFlowThisFunc(("\n"));
11399
11400#ifdef VBOX_WITH_GUEST_PROPS
11401 using namespace guestProp;
11402
11403 AutoCaller autoCaller(this);
11404 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11405
11406 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11407
11408 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
11409 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
11410 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
11411 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
11412
11413 size_t cEntries = mHWData->mGuestProperties.size();
11414 com::SafeArray<BSTR> names(cEntries);
11415 com::SafeArray<BSTR> values(cEntries);
11416 com::SafeArray<LONG64> timestamps(cEntries);
11417 com::SafeArray<BSTR> flags(cEntries);
11418 unsigned i = 0;
11419 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
11420 it != mHWData->mGuestProperties.end();
11421 ++it)
11422 {
11423 char szFlags[MAX_FLAGS_LEN + 1];
11424 it->strName.cloneTo(&names[i]);
11425 it->strValue.cloneTo(&values[i]);
11426 timestamps[i] = it->mTimestamp;
11427 /* If it is NULL, keep it NULL. */
11428 if (it->mFlags)
11429 {
11430 writeFlags(it->mFlags, szFlags);
11431 Bstr(szFlags).cloneTo(&flags[i]);
11432 }
11433 else
11434 flags[i] = NULL;
11435 ++i;
11436 }
11437 names.detachTo(ComSafeArrayOutArg(aNames));
11438 values.detachTo(ComSafeArrayOutArg(aValues));
11439 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11440 flags.detachTo(ComSafeArrayOutArg(aFlags));
11441 return S_OK;
11442#else
11443 ReturnComNotImplemented();
11444#endif
11445}
11446
11447STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11448 IN_BSTR aValue,
11449 LONG64 aTimestamp,
11450 IN_BSTR aFlags)
11451{
11452 LogFlowThisFunc(("\n"));
11453
11454#ifdef VBOX_WITH_GUEST_PROPS
11455 using namespace guestProp;
11456
11457 CheckComArgStrNotEmptyOrNull(aName);
11458 CheckComArgMaybeNull(aValue);
11459 CheckComArgMaybeNull(aFlags);
11460
11461 try
11462 {
11463 /*
11464 * Convert input up front.
11465 */
11466 Utf8Str utf8Name(aName);
11467 uint32_t fFlags = NILFLAG;
11468 if (aFlags)
11469 {
11470 Utf8Str utf8Flags(aFlags);
11471 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11472 AssertRCReturn(vrc, E_INVALIDARG);
11473 }
11474
11475 /*
11476 * Now grab the object lock, validate the state and do the update.
11477 */
11478 AutoCaller autoCaller(this);
11479 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11480
11481 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11482
11483 switch (mData->mMachineState)
11484 {
11485 case MachineState_Paused:
11486 case MachineState_Running:
11487 case MachineState_Teleporting:
11488 case MachineState_TeleportingPausedVM:
11489 case MachineState_LiveSnapshotting:
11490 case MachineState_DeletingSnapshotOnline:
11491 case MachineState_DeletingSnapshotPaused:
11492 case MachineState_Saving:
11493 break;
11494
11495 default:
11496#ifndef DEBUG_sunlover
11497 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11498 VBOX_E_INVALID_VM_STATE);
11499#else
11500 return VBOX_E_INVALID_VM_STATE;
11501#endif
11502 }
11503
11504 setModified(IsModified_MachineData);
11505 mHWData.backup();
11506
11507 /** @todo r=bird: The careful memory handling doesn't work out here because
11508 * the catch block won't undo any damage we've done. So, if push_back throws
11509 * bad_alloc then you've lost the value.
11510 *
11511 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11512 * since values that changes actually bubbles to the end of the list. Using
11513 * something that has an efficient lookup and can tolerate a bit of updates
11514 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11515 * combination of RTStrCache (for sharing names and getting uniqueness into
11516 * the bargain) and hash/tree is another. */
11517 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11518 iter != mHWData->mGuestProperties.end();
11519 ++iter)
11520 if (utf8Name == iter->strName)
11521 {
11522 mHWData->mGuestProperties.erase(iter);
11523 mData->mGuestPropertiesModified = TRUE;
11524 break;
11525 }
11526 if (aValue != NULL)
11527 {
11528 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11529 mHWData->mGuestProperties.push_back(property);
11530 mData->mGuestPropertiesModified = TRUE;
11531 }
11532
11533 /*
11534 * Send a callback notification if appropriate
11535 */
11536 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11537 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11538 RTSTR_MAX,
11539 utf8Name.c_str(),
11540 RTSTR_MAX, NULL)
11541 )
11542 {
11543 alock.leave();
11544
11545 mParent->onGuestPropertyChange(mData->mUuid,
11546 aName,
11547 aValue,
11548 aFlags);
11549 }
11550 }
11551 catch (...)
11552 {
11553 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11554 }
11555 return S_OK;
11556#else
11557 ReturnComNotImplemented();
11558#endif
11559}
11560
11561// public methods only for internal purposes
11562/////////////////////////////////////////////////////////////////////////////
11563
11564/**
11565 * Called from the client watcher thread to check for expected or unexpected
11566 * death of the client process that has a direct session to this machine.
11567 *
11568 * On Win32 and on OS/2, this method is called only when we've got the
11569 * mutex (i.e. the client has either died or terminated normally) so it always
11570 * returns @c true (the client is terminated, the session machine is
11571 * uninitialized).
11572 *
11573 * On other platforms, the method returns @c true if the client process has
11574 * terminated normally or abnormally and the session machine was uninitialized,
11575 * and @c false if the client process is still alive.
11576 *
11577 * @note Locks this object for writing.
11578 */
11579bool SessionMachine::checkForDeath()
11580{
11581 Uninit::Reason reason;
11582 bool terminated = false;
11583
11584 /* Enclose autoCaller with a block because calling uninit() from under it
11585 * will deadlock. */
11586 {
11587 AutoCaller autoCaller(this);
11588 if (!autoCaller.isOk())
11589 {
11590 /* return true if not ready, to cause the client watcher to exclude
11591 * the corresponding session from watching */
11592 LogFlowThisFunc(("Already uninitialized!\n"));
11593 return true;
11594 }
11595
11596 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11597
11598 /* Determine the reason of death: if the session state is Closing here,
11599 * everything is fine. Otherwise it means that the client did not call
11600 * OnSessionEnd() before it released the IPC semaphore. This may happen
11601 * either because the client process has abnormally terminated, or
11602 * because it simply forgot to call ISession::Close() before exiting. We
11603 * threat the latter also as an abnormal termination (see
11604 * Session::uninit() for details). */
11605 reason = mData->mSession.mState == SessionState_Unlocking ?
11606 Uninit::Normal :
11607 Uninit::Abnormal;
11608
11609#if defined(RT_OS_WINDOWS)
11610
11611 AssertMsg(mIPCSem, ("semaphore must be created"));
11612
11613 /* release the IPC mutex */
11614 ::ReleaseMutex(mIPCSem);
11615
11616 terminated = true;
11617
11618#elif defined(RT_OS_OS2)
11619
11620 AssertMsg(mIPCSem, ("semaphore must be created"));
11621
11622 /* release the IPC mutex */
11623 ::DosReleaseMutexSem(mIPCSem);
11624
11625 terminated = true;
11626
11627#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11628
11629 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11630
11631 int val = ::semctl(mIPCSem, 0, GETVAL);
11632 if (val > 0)
11633 {
11634 /* the semaphore is signaled, meaning the session is terminated */
11635 terminated = true;
11636 }
11637
11638#else
11639# error "Port me!"
11640#endif
11641
11642 } /* AutoCaller block */
11643
11644 if (terminated)
11645 uninit(reason);
11646
11647 return terminated;
11648}
11649
11650/**
11651 * @note Locks this object for reading.
11652 */
11653HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11654{
11655 LogFlowThisFunc(("\n"));
11656
11657 AutoCaller autoCaller(this);
11658 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11659
11660 ComPtr<IInternalSessionControl> directControl;
11661 {
11662 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11663 directControl = mData->mSession.mDirectControl;
11664 }
11665
11666 /* ignore notifications sent after #OnSessionEnd() is called */
11667 if (!directControl)
11668 return S_OK;
11669
11670 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11671}
11672
11673/**
11674 * @note Locks this object for reading.
11675 */
11676HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11677 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
11678{
11679 LogFlowThisFunc(("\n"));
11680
11681 AutoCaller autoCaller(this);
11682 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11683
11684 ComPtr<IInternalSessionControl> directControl;
11685 {
11686 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11687 directControl = mData->mSession.mDirectControl;
11688 }
11689
11690 /* ignore notifications sent after #OnSessionEnd() is called */
11691 if (!directControl)
11692 return S_OK;
11693 /*
11694 * instead acting like callback we ask IVirtualBox deliver corresponding event
11695 */
11696
11697 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
11698 return S_OK;
11699}
11700
11701/**
11702 * @note Locks this object for reading.
11703 */
11704HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
11705{
11706 LogFlowThisFunc(("\n"));
11707
11708 AutoCaller autoCaller(this);
11709 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11710
11711 ComPtr<IInternalSessionControl> directControl;
11712 {
11713 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11714 directControl = mData->mSession.mDirectControl;
11715 }
11716
11717 /* ignore notifications sent after #OnSessionEnd() is called */
11718 if (!directControl)
11719 return S_OK;
11720
11721 return directControl->OnSerialPortChange(serialPort);
11722}
11723
11724/**
11725 * @note Locks this object for reading.
11726 */
11727HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
11728{
11729 LogFlowThisFunc(("\n"));
11730
11731 AutoCaller autoCaller(this);
11732 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11733
11734 ComPtr<IInternalSessionControl> directControl;
11735 {
11736 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11737 directControl = mData->mSession.mDirectControl;
11738 }
11739
11740 /* ignore notifications sent after #OnSessionEnd() is called */
11741 if (!directControl)
11742 return S_OK;
11743
11744 return directControl->OnParallelPortChange(parallelPort);
11745}
11746
11747/**
11748 * @note Locks this object for reading.
11749 */
11750HRESULT SessionMachine::onStorageControllerChange()
11751{
11752 LogFlowThisFunc(("\n"));
11753
11754 AutoCaller autoCaller(this);
11755 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11756
11757 ComPtr<IInternalSessionControl> directControl;
11758 {
11759 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11760 directControl = mData->mSession.mDirectControl;
11761 }
11762
11763 /* ignore notifications sent after #OnSessionEnd() is called */
11764 if (!directControl)
11765 return S_OK;
11766
11767 return directControl->OnStorageControllerChange();
11768}
11769
11770/**
11771 * @note Locks this object for reading.
11772 */
11773HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11774{
11775 LogFlowThisFunc(("\n"));
11776
11777 AutoCaller autoCaller(this);
11778 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11779
11780 ComPtr<IInternalSessionControl> directControl;
11781 {
11782 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11783 directControl = mData->mSession.mDirectControl;
11784 }
11785
11786 /* ignore notifications sent after #OnSessionEnd() is called */
11787 if (!directControl)
11788 return S_OK;
11789
11790 return directControl->OnMediumChange(aAttachment, aForce);
11791}
11792
11793/**
11794 * @note Locks this object for reading.
11795 */
11796HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11797{
11798 LogFlowThisFunc(("\n"));
11799
11800 AutoCaller autoCaller(this);
11801 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11802
11803 ComPtr<IInternalSessionControl> directControl;
11804 {
11805 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11806 directControl = mData->mSession.mDirectControl;
11807 }
11808
11809 /* ignore notifications sent after #OnSessionEnd() is called */
11810 if (!directControl)
11811 return S_OK;
11812
11813 return directControl->OnCPUChange(aCPU, aRemove);
11814}
11815
11816HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11817{
11818 LogFlowThisFunc(("\n"));
11819
11820 AutoCaller autoCaller(this);
11821 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11822
11823 ComPtr<IInternalSessionControl> directControl;
11824 {
11825 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11826 directControl = mData->mSession.mDirectControl;
11827 }
11828
11829 /* ignore notifications sent after #OnSessionEnd() is called */
11830 if (!directControl)
11831 return S_OK;
11832
11833 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11834}
11835
11836/**
11837 * @note Locks this object for reading.
11838 */
11839HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11840{
11841 LogFlowThisFunc(("\n"));
11842
11843 AutoCaller autoCaller(this);
11844 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11845
11846 ComPtr<IInternalSessionControl> directControl;
11847 {
11848 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11849 directControl = mData->mSession.mDirectControl;
11850 }
11851
11852 /* ignore notifications sent after #OnSessionEnd() is called */
11853 if (!directControl)
11854 return S_OK;
11855
11856 return directControl->OnVRDEServerChange(aRestart);
11857}
11858
11859/**
11860 * @note Locks this object for reading.
11861 */
11862HRESULT SessionMachine::onUSBControllerChange()
11863{
11864 LogFlowThisFunc(("\n"));
11865
11866 AutoCaller autoCaller(this);
11867 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11868
11869 ComPtr<IInternalSessionControl> directControl;
11870 {
11871 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11872 directControl = mData->mSession.mDirectControl;
11873 }
11874
11875 /* ignore notifications sent after #OnSessionEnd() is called */
11876 if (!directControl)
11877 return S_OK;
11878
11879 return directControl->OnUSBControllerChange();
11880}
11881
11882/**
11883 * @note Locks this object for reading.
11884 */
11885HRESULT SessionMachine::onSharedFolderChange()
11886{
11887 LogFlowThisFunc(("\n"));
11888
11889 AutoCaller autoCaller(this);
11890 AssertComRCReturnRC(autoCaller.rc());
11891
11892 ComPtr<IInternalSessionControl> directControl;
11893 {
11894 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11895 directControl = mData->mSession.mDirectControl;
11896 }
11897
11898 /* ignore notifications sent after #OnSessionEnd() is called */
11899 if (!directControl)
11900 return S_OK;
11901
11902 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11903}
11904
11905/**
11906 * @note Locks this object for reading.
11907 */
11908HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
11909{
11910 LogFlowThisFunc(("\n"));
11911
11912 AutoCaller autoCaller(this);
11913 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11914
11915 ComPtr<IInternalSessionControl> directControl;
11916 {
11917 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11918 directControl = mData->mSession.mDirectControl;
11919 }
11920
11921 /* ignore notifications sent after #OnSessionEnd() is called */
11922 if (!directControl)
11923 return S_OK;
11924
11925 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
11926}
11927
11928/**
11929 * @note Locks this object for reading.
11930 */
11931HRESULT SessionMachine::onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove)
11932{
11933 LogFlowThisFunc(("\n"));
11934
11935 AutoCaller autoCaller(this);
11936 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11937
11938 ComPtr<IInternalSessionControl> directControl;
11939 {
11940 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11941 directControl = mData->mSession.mDirectControl;
11942 }
11943
11944 /* ignore notifications sent after #OnSessionEnd() is called */
11945 if (!directControl)
11946 return S_OK;
11947
11948 return directControl->OnStorageDeviceChange(aAttachment, aRemove);
11949}
11950
11951/**
11952 * Returns @c true if this machine's USB controller reports it has a matching
11953 * filter for the given USB device and @c false otherwise.
11954 *
11955 * @note Caller must have requested machine read lock.
11956 */
11957bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11958{
11959 AutoCaller autoCaller(this);
11960 /* silently return if not ready -- this method may be called after the
11961 * direct machine session has been called */
11962 if (!autoCaller.isOk())
11963 return false;
11964
11965
11966#ifdef VBOX_WITH_USB
11967 switch (mData->mMachineState)
11968 {
11969 case MachineState_Starting:
11970 case MachineState_Restoring:
11971 case MachineState_TeleportingIn:
11972 case MachineState_Paused:
11973 case MachineState_Running:
11974 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11975 * elsewhere... */
11976 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11977 default: break;
11978 }
11979#else
11980 NOREF(aDevice);
11981 NOREF(aMaskedIfs);
11982#endif
11983 return false;
11984}
11985
11986/**
11987 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
11988 */
11989HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
11990 IVirtualBoxErrorInfo *aError,
11991 ULONG aMaskedIfs)
11992{
11993 LogFlowThisFunc(("\n"));
11994
11995 AutoCaller autoCaller(this);
11996
11997 /* This notification may happen after the machine object has been
11998 * uninitialized (the session was closed), so don't assert. */
11999 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12000
12001 ComPtr<IInternalSessionControl> directControl;
12002 {
12003 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12004 directControl = mData->mSession.mDirectControl;
12005 }
12006
12007 /* fail on notifications sent after #OnSessionEnd() is called, it is
12008 * expected by the caller */
12009 if (!directControl)
12010 return E_FAIL;
12011
12012 /* No locks should be held at this point. */
12013 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12014 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12015
12016 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
12017}
12018
12019/**
12020 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12021 */
12022HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
12023 IVirtualBoxErrorInfo *aError)
12024{
12025 LogFlowThisFunc(("\n"));
12026
12027 AutoCaller autoCaller(this);
12028
12029 /* This notification may happen after the machine object has been
12030 * uninitialized (the session was closed), so don't assert. */
12031 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12032
12033 ComPtr<IInternalSessionControl> directControl;
12034 {
12035 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12036 directControl = mData->mSession.mDirectControl;
12037 }
12038
12039 /* fail on notifications sent after #OnSessionEnd() is called, it is
12040 * expected by the caller */
12041 if (!directControl)
12042 return E_FAIL;
12043
12044 /* No locks should be held at this point. */
12045 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12046 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12047
12048 return directControl->OnUSBDeviceDetach(aId, aError);
12049}
12050
12051// protected methods
12052/////////////////////////////////////////////////////////////////////////////
12053
12054/**
12055 * Helper method to finalize saving the state.
12056 *
12057 * @note Must be called from under this object's lock.
12058 *
12059 * @param aRc S_OK if the snapshot has been taken successfully
12060 * @param aErrMsg human readable error message for failure
12061 *
12062 * @note Locks mParent + this objects for writing.
12063 */
12064HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
12065{
12066 LogFlowThisFuncEnter();
12067
12068 AutoCaller autoCaller(this);
12069 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12070
12071 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12072
12073 HRESULT rc = S_OK;
12074
12075 if (SUCCEEDED(aRc))
12076 {
12077 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
12078
12079 /* save all VM settings */
12080 rc = saveSettings(NULL);
12081 // no need to check whether VirtualBox.xml needs saving also since
12082 // we can't have a name change pending at this point
12083 }
12084 else
12085 {
12086 // delete the saved state file (it might have been already created);
12087 // we need not check whether this is shared with a snapshot here because
12088 // we certainly created this saved state file here anew
12089 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
12090 }
12091
12092 /* notify the progress object about operation completion */
12093 Assert(mConsoleTaskData.mProgress);
12094 if (SUCCEEDED(aRc))
12095 mConsoleTaskData.mProgress->notifyComplete(S_OK);
12096 else
12097 {
12098 if (aErrMsg.length())
12099 mConsoleTaskData.mProgress->notifyComplete(aRc,
12100 COM_IIDOF(ISession),
12101 getComponentName(),
12102 aErrMsg.c_str());
12103 else
12104 mConsoleTaskData.mProgress->notifyComplete(aRc);
12105 }
12106
12107 /* clear out the temporary saved state data */
12108 mConsoleTaskData.mLastState = MachineState_Null;
12109 mConsoleTaskData.strStateFilePath.setNull();
12110 mConsoleTaskData.mProgress.setNull();
12111
12112 LogFlowThisFuncLeave();
12113 return rc;
12114}
12115
12116/**
12117 * Deletes the given file if it is no longer in use by either the current machine state
12118 * (if the machine is "saved") or any of the machine's snapshots.
12119 *
12120 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
12121 * but is different for each SnapshotMachine. When calling this, the order of calling this
12122 * function on the one hand and changing that variable OR the snapshots tree on the other hand
12123 * is therefore critical. I know, it's all rather messy.
12124 *
12125 * @param strStateFile
12126 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
12127 */
12128void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
12129 Snapshot *pSnapshotToIgnore)
12130{
12131 // it is safe to delete this saved state file if it is not currently in use by the machine ...
12132 if ( (strStateFile.isNotEmpty())
12133 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
12134 )
12135 // ... and it must also not be shared with other snapshots
12136 if ( !mData->mFirstSnapshot
12137 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
12138 // this checks the SnapshotMachine's state file paths
12139 )
12140 RTFileDelete(strStateFile.c_str());
12141}
12142
12143/**
12144 * Locks the attached media.
12145 *
12146 * All attached hard disks are locked for writing and DVD/floppy are locked for
12147 * reading. Parents of attached hard disks (if any) are locked for reading.
12148 *
12149 * This method also performs accessibility check of all media it locks: if some
12150 * media is inaccessible, the method will return a failure and a bunch of
12151 * extended error info objects per each inaccessible medium.
12152 *
12153 * Note that this method is atomic: if it returns a success, all media are
12154 * locked as described above; on failure no media is locked at all (all
12155 * succeeded individual locks will be undone).
12156 *
12157 * This method is intended to be called when the machine is in Starting or
12158 * Restoring state and asserts otherwise.
12159 *
12160 * The locks made by this method must be undone by calling #unlockMedia() when
12161 * no more needed.
12162 */
12163HRESULT SessionMachine::lockMedia()
12164{
12165 AutoCaller autoCaller(this);
12166 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12167
12168 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12169
12170 AssertReturn( mData->mMachineState == MachineState_Starting
12171 || mData->mMachineState == MachineState_Restoring
12172 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
12173 /* bail out if trying to lock things with already set up locking */
12174 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
12175
12176 clearError();
12177 MultiResult mrc(S_OK);
12178
12179 /* Collect locking information for all medium objects attached to the VM. */
12180 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
12181 it != mMediaData->mAttachments.end();
12182 ++it)
12183 {
12184 MediumAttachment* pAtt = *it;
12185 DeviceType_T devType = pAtt->getType();
12186 Medium *pMedium = pAtt->getMedium();
12187
12188 MediumLockList *pMediumLockList(new MediumLockList());
12189 // There can be attachments without a medium (floppy/dvd), and thus
12190 // it's impossible to create a medium lock list. It still makes sense
12191 // to have the empty medium lock list in the map in case a medium is
12192 // attached later.
12193 if (pMedium != NULL)
12194 {
12195 MediumType_T mediumType = pMedium->getType();
12196 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
12197 || mediumType == MediumType_Shareable;
12198 bool fIsVitalImage = (devType == DeviceType_HardDisk);
12199
12200 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
12201 !fIsReadOnlyLock /* fMediumLockWrite */,
12202 NULL,
12203 *pMediumLockList);
12204 if (FAILED(mrc))
12205 {
12206 delete pMediumLockList;
12207 mData->mSession.mLockedMedia.Clear();
12208 break;
12209 }
12210 }
12211
12212 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
12213 if (FAILED(rc))
12214 {
12215 mData->mSession.mLockedMedia.Clear();
12216 mrc = setError(rc,
12217 tr("Collecting locking information for all attached media failed"));
12218 break;
12219 }
12220 }
12221
12222 if (SUCCEEDED(mrc))
12223 {
12224 /* Now lock all media. If this fails, nothing is locked. */
12225 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12226 if (FAILED(rc))
12227 {
12228 mrc = setError(rc,
12229 tr("Locking of attached media failed"));
12230 }
12231 }
12232
12233 return mrc;
12234}
12235
12236/**
12237 * Undoes the locks made by by #lockMedia().
12238 */
12239void SessionMachine::unlockMedia()
12240{
12241 AutoCaller autoCaller(this);
12242 AssertComRCReturnVoid(autoCaller.rc());
12243
12244 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12245
12246 /* we may be holding important error info on the current thread;
12247 * preserve it */
12248 ErrorInfoKeeper eik;
12249
12250 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12251 AssertComRC(rc);
12252}
12253
12254/**
12255 * Helper to change the machine state (reimplementation).
12256 *
12257 * @note Locks this object for writing.
12258 */
12259HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12260{
12261 LogFlowThisFuncEnter();
12262 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12263
12264 AutoCaller autoCaller(this);
12265 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12266
12267 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12268
12269 MachineState_T oldMachineState = mData->mMachineState;
12270
12271 AssertMsgReturn(oldMachineState != aMachineState,
12272 ("oldMachineState=%s, aMachineState=%s\n",
12273 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12274 E_FAIL);
12275
12276 HRESULT rc = S_OK;
12277
12278 int stsFlags = 0;
12279 bool deleteSavedState = false;
12280
12281 /* detect some state transitions */
12282
12283 if ( ( oldMachineState == MachineState_Saved
12284 && aMachineState == MachineState_Restoring)
12285 || ( ( oldMachineState == MachineState_PoweredOff
12286 || oldMachineState == MachineState_Teleported
12287 || oldMachineState == MachineState_Aborted
12288 )
12289 && ( aMachineState == MachineState_TeleportingIn
12290 || aMachineState == MachineState_Starting
12291 )
12292 )
12293 )
12294 {
12295 /* The EMT thread is about to start */
12296
12297 /* Nothing to do here for now... */
12298
12299 /// @todo NEWMEDIA don't let mDVDDrive and other children
12300 /// change anything when in the Starting/Restoring state
12301 }
12302 else if ( ( oldMachineState == MachineState_Running
12303 || oldMachineState == MachineState_Paused
12304 || oldMachineState == MachineState_Teleporting
12305 || oldMachineState == MachineState_LiveSnapshotting
12306 || oldMachineState == MachineState_Stuck
12307 || oldMachineState == MachineState_Starting
12308 || oldMachineState == MachineState_Stopping
12309 || oldMachineState == MachineState_Saving
12310 || oldMachineState == MachineState_Restoring
12311 || oldMachineState == MachineState_TeleportingPausedVM
12312 || oldMachineState == MachineState_TeleportingIn
12313 )
12314 && ( aMachineState == MachineState_PoweredOff
12315 || aMachineState == MachineState_Saved
12316 || aMachineState == MachineState_Teleported
12317 || aMachineState == MachineState_Aborted
12318 )
12319 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
12320 * snapshot */
12321 && ( mConsoleTaskData.mSnapshot.isNull()
12322 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
12323 )
12324 )
12325 {
12326 /* The EMT thread has just stopped, unlock attached media. Note that as
12327 * opposed to locking that is done from Console, we do unlocking here
12328 * because the VM process may have aborted before having a chance to
12329 * properly unlock all media it locked. */
12330
12331 unlockMedia();
12332 }
12333
12334 if (oldMachineState == MachineState_Restoring)
12335 {
12336 if (aMachineState != MachineState_Saved)
12337 {
12338 /*
12339 * delete the saved state file once the machine has finished
12340 * restoring from it (note that Console sets the state from
12341 * Restoring to Saved if the VM couldn't restore successfully,
12342 * to give the user an ability to fix an error and retry --
12343 * we keep the saved state file in this case)
12344 */
12345 deleteSavedState = true;
12346 }
12347 }
12348 else if ( oldMachineState == MachineState_Saved
12349 && ( aMachineState == MachineState_PoweredOff
12350 || aMachineState == MachineState_Aborted
12351 || aMachineState == MachineState_Teleported
12352 )
12353 )
12354 {
12355 /*
12356 * delete the saved state after Console::ForgetSavedState() is called
12357 * or if the VM process (owning a direct VM session) crashed while the
12358 * VM was Saved
12359 */
12360
12361 /// @todo (dmik)
12362 // Not sure that deleting the saved state file just because of the
12363 // client death before it attempted to restore the VM is a good
12364 // thing. But when it crashes we need to go to the Aborted state
12365 // which cannot have the saved state file associated... The only
12366 // way to fix this is to make the Aborted condition not a VM state
12367 // but a bool flag: i.e., when a crash occurs, set it to true and
12368 // change the state to PoweredOff or Saved depending on the
12369 // saved state presence.
12370
12371 deleteSavedState = true;
12372 mData->mCurrentStateModified = TRUE;
12373 stsFlags |= SaveSTS_CurStateModified;
12374 }
12375
12376 if ( aMachineState == MachineState_Starting
12377 || aMachineState == MachineState_Restoring
12378 || aMachineState == MachineState_TeleportingIn
12379 )
12380 {
12381 /* set the current state modified flag to indicate that the current
12382 * state is no more identical to the state in the
12383 * current snapshot */
12384 if (!mData->mCurrentSnapshot.isNull())
12385 {
12386 mData->mCurrentStateModified = TRUE;
12387 stsFlags |= SaveSTS_CurStateModified;
12388 }
12389 }
12390
12391 if (deleteSavedState)
12392 {
12393 if (mRemoveSavedState)
12394 {
12395 Assert(!mSSData->strStateFilePath.isEmpty());
12396
12397 // it is safe to delete the saved state file if ...
12398 if ( !mData->mFirstSnapshot // ... we have no snapshots or
12399 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
12400 // ... none of the snapshots share the saved state file
12401 )
12402 RTFileDelete(mSSData->strStateFilePath.c_str());
12403 }
12404
12405 mSSData->strStateFilePath.setNull();
12406 stsFlags |= SaveSTS_StateFilePath;
12407 }
12408
12409 /* redirect to the underlying peer machine */
12410 mPeer->setMachineState(aMachineState);
12411
12412 if ( aMachineState == MachineState_PoweredOff
12413 || aMachineState == MachineState_Teleported
12414 || aMachineState == MachineState_Aborted
12415 || aMachineState == MachineState_Saved)
12416 {
12417 /* the machine has stopped execution
12418 * (or the saved state file was adopted) */
12419 stsFlags |= SaveSTS_StateTimeStamp;
12420 }
12421
12422 if ( ( oldMachineState == MachineState_PoweredOff
12423 || oldMachineState == MachineState_Aborted
12424 || oldMachineState == MachineState_Teleported
12425 )
12426 && aMachineState == MachineState_Saved)
12427 {
12428 /* the saved state file was adopted */
12429 Assert(!mSSData->strStateFilePath.isEmpty());
12430 stsFlags |= SaveSTS_StateFilePath;
12431 }
12432
12433#ifdef VBOX_WITH_GUEST_PROPS
12434 if ( aMachineState == MachineState_PoweredOff
12435 || aMachineState == MachineState_Aborted
12436 || aMachineState == MachineState_Teleported)
12437 {
12438 /* Make sure any transient guest properties get removed from the
12439 * property store on shutdown. */
12440
12441 HWData::GuestPropertyList::iterator it;
12442 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
12443 if (!fNeedsSaving)
12444 for (it = mHWData->mGuestProperties.begin();
12445 it != mHWData->mGuestProperties.end(); ++it)
12446 if ( (it->mFlags & guestProp::TRANSIENT)
12447 || (it->mFlags & guestProp::TRANSRESET))
12448 {
12449 fNeedsSaving = true;
12450 break;
12451 }
12452 if (fNeedsSaving)
12453 {
12454 mData->mCurrentStateModified = TRUE;
12455 stsFlags |= SaveSTS_CurStateModified;
12456 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
12457 }
12458 }
12459#endif
12460
12461 rc = saveStateSettings(stsFlags);
12462
12463 if ( ( oldMachineState != MachineState_PoweredOff
12464 && oldMachineState != MachineState_Aborted
12465 && oldMachineState != MachineState_Teleported
12466 )
12467 && ( aMachineState == MachineState_PoweredOff
12468 || aMachineState == MachineState_Aborted
12469 || aMachineState == MachineState_Teleported
12470 )
12471 )
12472 {
12473 /* we've been shut down for any reason */
12474 /* no special action so far */
12475 }
12476
12477 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
12478 LogFlowThisFuncLeave();
12479 return rc;
12480}
12481
12482/**
12483 * Sends the current machine state value to the VM process.
12484 *
12485 * @note Locks this object for reading, then calls a client process.
12486 */
12487HRESULT SessionMachine::updateMachineStateOnClient()
12488{
12489 AutoCaller autoCaller(this);
12490 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12491
12492 ComPtr<IInternalSessionControl> directControl;
12493 {
12494 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12495 AssertReturn(!!mData, E_FAIL);
12496 directControl = mData->mSession.mDirectControl;
12497
12498 /* directControl may be already set to NULL here in #OnSessionEnd()
12499 * called too early by the direct session process while there is still
12500 * some operation (like deleting the snapshot) in progress. The client
12501 * process in this case is waiting inside Session::close() for the
12502 * "end session" process object to complete, while #uninit() called by
12503 * #checkForDeath() on the Watcher thread is waiting for the pending
12504 * operation to complete. For now, we accept this inconsistent behavior
12505 * and simply do nothing here. */
12506
12507 if (mData->mSession.mState == SessionState_Unlocking)
12508 return S_OK;
12509
12510 AssertReturn(!directControl.isNull(), E_FAIL);
12511 }
12512
12513 return directControl->UpdateMachineState(mData->mMachineState);
12514}
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