VirtualBox

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

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

Main: Build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 416.3 KB
Line 
1/* $Id: MachineImpl.cpp 37657 2011-06-28 10:44:03Z 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("Controller '%ls' does not support hotplugging"),
3428 aControllerName);
3429
3430 if (fHotplug && aType == DeviceType_DVD)
3431 return setError(VBOX_E_INVALID_VM_STATE,
3432 tr("Attaching a DVD drive while the VM is running is not supported"));
3433
3434 // check that the port and device are not out of range
3435 rc = ctl->checkPortAndDeviceValid(aControllerPort, aDevice);
3436 if (FAILED(rc)) return rc;
3437
3438 /* check if the device slot is already busy */
3439 MediumAttachment *pAttachTemp;
3440 if ((pAttachTemp = findAttachment(mMediaData->mAttachments,
3441 aControllerName,
3442 aControllerPort,
3443 aDevice)))
3444 {
3445 Medium *pMedium = pAttachTemp->getMedium();
3446 if (pMedium)
3447 {
3448 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3449 return setError(VBOX_E_OBJECT_IN_USE,
3450 tr("Medium '%s' is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3451 pMedium->getLocationFull().c_str(),
3452 aControllerPort,
3453 aDevice,
3454 aControllerName);
3455 }
3456 else
3457 return setError(VBOX_E_OBJECT_IN_USE,
3458 tr("Device is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3459 aControllerPort, aDevice, aControllerName);
3460 }
3461
3462 ComObjPtr<Medium> medium = static_cast<Medium*>(aMedium);
3463 if (aMedium && medium.isNull())
3464 return setError(E_INVALIDARG, "The given medium pointer is invalid");
3465
3466 AutoCaller mediumCaller(medium);
3467 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3468
3469 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3470
3471 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
3472 && !medium.isNull()
3473 )
3474 return setError(VBOX_E_OBJECT_IN_USE,
3475 tr("Medium '%s' is already attached to this virtual machine"),
3476 medium->getLocationFull().c_str());
3477
3478 if (!medium.isNull())
3479 {
3480 MediumType_T mtype = medium->getType();
3481 // MediumType_Readonly is also new, but only applies to DVDs and floppies.
3482 // For DVDs it's not written to the config file, so needs no global config
3483 // version bump. For floppies it's a new attribute "type", which is ignored
3484 // by older VirtualBox version, so needs no global config version bump either.
3485 // For hard disks this type is not accepted.
3486 if (mtype == MediumType_MultiAttach)
3487 {
3488 // This type is new with VirtualBox 4.0 and therefore requires settings
3489 // version 1.11 in the settings backend. Unfortunately it is not enough to do
3490 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
3491 // two reasons: The medium type is a property of the media registry tree, which
3492 // can reside in the global config file (for pre-4.0 media); we would therefore
3493 // possibly need to bump the global config version. We don't want to do that though
3494 // because that might make downgrading to pre-4.0 impossible.
3495 // As a result, we can only use these two new types if the medium is NOT in the
3496 // global registry:
3497 const Guid &uuidGlobalRegistry = mParent->getGlobalRegistryId();
3498 if ( medium->isInRegistry(uuidGlobalRegistry)
3499 || !mData->pMachineConfigFile->canHaveOwnMediaRegistry()
3500 )
3501 return setError(VBOX_E_INVALID_OBJECT_STATE,
3502 tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
3503 "to machines that were created with VirtualBox 4.0 or later"),
3504 medium->getLocationFull().c_str());
3505 }
3506 }
3507
3508 bool fIndirect = false;
3509 if (!medium.isNull())
3510 fIndirect = medium->isReadOnly();
3511 bool associate = true;
3512
3513 do
3514 {
3515 if ( aType == DeviceType_HardDisk
3516 && mMediaData.isBackedUp())
3517 {
3518 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3519
3520 /* check if the medium was attached to the VM before we started
3521 * changing attachments in which case the attachment just needs to
3522 * be restored */
3523 if ((pAttachTemp = findAttachment(oldAtts, medium)))
3524 {
3525 AssertReturn(!fIndirect, E_FAIL);
3526
3527 /* see if it's the same bus/channel/device */
3528 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
3529 {
3530 /* the simplest case: restore the whole attachment
3531 * and return, nothing else to do */
3532 mMediaData->mAttachments.push_back(pAttachTemp);
3533 return S_OK;
3534 }
3535
3536 /* bus/channel/device differ; we need a new attachment object,
3537 * but don't try to associate it again */
3538 associate = false;
3539 break;
3540 }
3541 }
3542
3543 /* go further only if the attachment is to be indirect */
3544 if (!fIndirect)
3545 break;
3546
3547 /* perform the so called smart attachment logic for indirect
3548 * attachments. Note that smart attachment is only applicable to base
3549 * hard disks. */
3550
3551 if (medium->getParent().isNull())
3552 {
3553 /* first, investigate the backup copy of the current hard disk
3554 * attachments to make it possible to re-attach existing diffs to
3555 * another device slot w/o losing their contents */
3556 if (mMediaData.isBackedUp())
3557 {
3558 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3559
3560 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
3561 uint32_t foundLevel = 0;
3562
3563 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
3564 it != oldAtts.end();
3565 ++it)
3566 {
3567 uint32_t level = 0;
3568 MediumAttachment *pAttach = *it;
3569 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3570 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3571 if (pMedium.isNull())
3572 continue;
3573
3574 if (pMedium->getBase(&level) == medium)
3575 {
3576 /* skip the hard disk if its currently attached (we
3577 * cannot attach the same hard disk twice) */
3578 if (findAttachment(mMediaData->mAttachments,
3579 pMedium))
3580 continue;
3581
3582 /* matched device, channel and bus (i.e. attached to the
3583 * same place) will win and immediately stop the search;
3584 * otherwise the attachment that has the youngest
3585 * descendant of medium will be used
3586 */
3587 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
3588 {
3589 /* the simplest case: restore the whole attachment
3590 * and return, nothing else to do */
3591 mMediaData->mAttachments.push_back(*it);
3592 return S_OK;
3593 }
3594 else if ( foundIt == oldAtts.end()
3595 || level > foundLevel /* prefer younger */
3596 )
3597 {
3598 foundIt = it;
3599 foundLevel = level;
3600 }
3601 }
3602 }
3603
3604 if (foundIt != oldAtts.end())
3605 {
3606 /* use the previously attached hard disk */
3607 medium = (*foundIt)->getMedium();
3608 mediumCaller.attach(medium);
3609 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3610 mediumLock.attach(medium);
3611 /* not implicit, doesn't require association with this VM */
3612 fIndirect = false;
3613 associate = false;
3614 /* go right to the MediumAttachment creation */
3615 break;
3616 }
3617 }
3618
3619 /* must give up the medium lock and medium tree lock as below we
3620 * go over snapshots, which needs a lock with higher lock order. */
3621 mediumLock.release();
3622 treeLock.release();
3623
3624 /* then, search through snapshots for the best diff in the given
3625 * hard disk's chain to base the new diff on */
3626
3627 ComObjPtr<Medium> base;
3628 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
3629 while (snap)
3630 {
3631 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
3632
3633 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
3634
3635 MediumAttachment *pAttachFound = NULL;
3636 uint32_t foundLevel = 0;
3637
3638 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
3639 it != snapAtts.end();
3640 ++it)
3641 {
3642 MediumAttachment *pAttach = *it;
3643 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3644 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3645 if (pMedium.isNull())
3646 continue;
3647
3648 uint32_t level = 0;
3649 if (pMedium->getBase(&level) == medium)
3650 {
3651 /* matched device, channel and bus (i.e. attached to the
3652 * same place) will win and immediately stop the search;
3653 * otherwise the attachment that has the youngest
3654 * descendant of medium will be used
3655 */
3656 if ( pAttach->getDevice() == aDevice
3657 && pAttach->getPort() == aControllerPort
3658 && pAttach->getControllerName() == aControllerName
3659 )
3660 {
3661 pAttachFound = pAttach;
3662 break;
3663 }
3664 else if ( !pAttachFound
3665 || level > foundLevel /* prefer younger */
3666 )
3667 {
3668 pAttachFound = pAttach;
3669 foundLevel = level;
3670 }
3671 }
3672 }
3673
3674 if (pAttachFound)
3675 {
3676 base = pAttachFound->getMedium();
3677 break;
3678 }
3679
3680 snap = snap->getParent();
3681 }
3682
3683 /* re-lock medium tree and the medium, as we need it below */
3684 treeLock.acquire();
3685 mediumLock.acquire();
3686
3687 /* found a suitable diff, use it as a base */
3688 if (!base.isNull())
3689 {
3690 medium = base;
3691 mediumCaller.attach(medium);
3692 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3693 mediumLock.attach(medium);
3694 }
3695 }
3696
3697 Utf8Str strFullSnapshotFolder;
3698 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
3699
3700 ComObjPtr<Medium> diff;
3701 diff.createObject();
3702 // store this diff in the same registry as the parent
3703 Guid uuidRegistryParent;
3704 if (!medium->getFirstRegistryMachineId(uuidRegistryParent))
3705 {
3706 // parent image has no registry: this can happen if we're attaching a new immutable
3707 // image that has not yet been attached (medium then points to the base and we're
3708 // creating the diff image for the immutable, and the parent is not yet registered);
3709 // put the parent in the machine registry then
3710 addMediumToRegistry(medium, llRegistriesThatNeedSaving, &uuidRegistryParent);
3711 }
3712 rc = diff->init(mParent,
3713 medium->getPreferredDiffFormat(),
3714 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
3715 uuidRegistryParent,
3716 &llRegistriesThatNeedSaving);
3717 if (FAILED(rc)) return rc;
3718
3719 /* Apply the normal locking logic to the entire chain. */
3720 MediumLockList *pMediumLockList(new MediumLockList());
3721 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
3722 true /* fMediumLockWrite */,
3723 medium,
3724 *pMediumLockList);
3725 if (SUCCEEDED(rc))
3726 {
3727 rc = pMediumLockList->Lock();
3728 if (FAILED(rc))
3729 setError(rc,
3730 tr("Could not lock medium when creating diff '%s'"),
3731 diff->getLocationFull().c_str());
3732 else
3733 {
3734 /* will leave the lock before the potentially lengthy operation, so
3735 * protect with the special state */
3736 MachineState_T oldState = mData->mMachineState;
3737 setMachineState(MachineState_SettingUp);
3738
3739 mediumLock.leave();
3740 treeLock.leave();
3741 alock.leave();
3742
3743 rc = medium->createDiffStorage(diff,
3744 MediumVariant_Standard,
3745 pMediumLockList,
3746 NULL /* aProgress */,
3747 true /* aWait */,
3748 &llRegistriesThatNeedSaving);
3749
3750 alock.enter();
3751 treeLock.enter();
3752 mediumLock.enter();
3753
3754 setMachineState(oldState);
3755 }
3756 }
3757
3758 /* Unlock the media and free the associated memory. */
3759 delete pMediumLockList;
3760
3761 if (FAILED(rc)) return rc;
3762
3763 /* use the created diff for the actual attachment */
3764 medium = diff;
3765 mediumCaller.attach(medium);
3766 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3767 mediumLock.attach(medium);
3768 }
3769 while (0);
3770
3771 ComObjPtr<MediumAttachment> attachment;
3772 attachment.createObject();
3773 rc = attachment->init(this,
3774 medium,
3775 aControllerName,
3776 aControllerPort,
3777 aDevice,
3778 aType,
3779 fIndirect,
3780 Utf8Str::Empty);
3781 if (FAILED(rc)) return rc;
3782
3783 if (associate && !medium.isNull())
3784 {
3785 // as the last step, associate the medium to the VM
3786 rc = medium->addBackReference(mData->mUuid);
3787 // here we can fail because of Deleting, or being in process of creating a Diff
3788 if (FAILED(rc)) return rc;
3789
3790 addMediumToRegistry(medium,
3791 llRegistriesThatNeedSaving,
3792 NULL /* Guid *puuid */);
3793 }
3794
3795 /* success: finally remember the attachment */
3796 setModified(IsModified_Storage);
3797 mMediaData.backup();
3798 mMediaData->mAttachments.push_back(attachment);
3799
3800 mediumLock.release();
3801 treeLock.leave();
3802 alock.release();
3803
3804 if (fHotplug)
3805 rc = onStorageDeviceChange(attachment, FALSE /* aRemove */);
3806
3807 mParent->saveRegistries(llRegistriesThatNeedSaving);
3808
3809 return rc;
3810}
3811
3812STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
3813 LONG aDevice)
3814{
3815 CheckComArgStrNotEmptyOrNull(aControllerName);
3816
3817 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3818 aControllerName, aControllerPort, aDevice));
3819
3820 AutoCaller autoCaller(this);
3821 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3822
3823 GuidList llRegistriesThatNeedSaving;
3824
3825 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3826
3827 HRESULT rc = checkStateDependency(MutableStateDep);
3828 if (FAILED(rc)) return rc;
3829
3830 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3831
3832 /* Check for an existing controller. */
3833 ComObjPtr<StorageController> ctl;
3834 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
3835 if (FAILED(rc)) return rc;
3836
3837 StorageControllerType_T ctrlType;
3838 rc = ctl->COMGETTER(ControllerType)(&ctrlType);
3839 if (FAILED(rc))
3840 return setError(E_FAIL,
3841 tr("Could not get type of controller '%ls'"),
3842 aControllerName);
3843
3844 /* Check that the controller can do hotplugging if we detach the device while the VM is running. */
3845 bool fHotplug = false;
3846 if (Global::IsOnlineOrTransient(mData->mMachineState))
3847 fHotplug = true;
3848
3849 if (fHotplug && !isControllerHotplugCapable(ctrlType))
3850 return setError(VBOX_E_INVALID_VM_STATE,
3851 tr("Controller '%ls' does not support hotplugging"),
3852 aControllerName);
3853
3854 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3855 aControllerName,
3856 aControllerPort,
3857 aDevice);
3858 if (!pAttach)
3859 return setError(VBOX_E_OBJECT_NOT_FOUND,
3860 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3861 aDevice, aControllerPort, aControllerName);
3862
3863 if (fHotplug && pAttach->getType() == DeviceType_DVD)
3864 return setError(VBOX_E_INVALID_VM_STATE,
3865 tr("Detaching a DVD drive while the VM is running is not supported"));
3866
3867 /*
3868 * The VM has to detach the device before we delete any implicit diffs.
3869 * If this fails we can roll back without loosing data.
3870 */
3871 if (fHotplug)
3872 {
3873 alock.leave();
3874 rc = onStorageDeviceChange(pAttach, TRUE /* aRemove */);
3875 alock.enter();
3876 }
3877 if (FAILED(rc)) return rc;
3878
3879 /* If we are here everything went well and we can delete the implicit now. */
3880 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */, &llRegistriesThatNeedSaving);
3881
3882 alock.release();
3883
3884 if (SUCCEEDED(rc))
3885 rc = mParent->saveRegistries(llRegistriesThatNeedSaving);
3886
3887 return rc;
3888}
3889
3890STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
3891 LONG aDevice, BOOL aPassthrough)
3892{
3893 CheckComArgStrNotEmptyOrNull(aControllerName);
3894
3895 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aPassthrough=%d\n",
3896 aControllerName, aControllerPort, aDevice, aPassthrough));
3897
3898 AutoCaller autoCaller(this);
3899 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3900
3901 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3902
3903 HRESULT rc = checkStateDependency(MutableStateDep);
3904 if (FAILED(rc)) return rc;
3905
3906 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3907
3908 if (Global::IsOnlineOrTransient(mData->mMachineState))
3909 return setError(VBOX_E_INVALID_VM_STATE,
3910 tr("Invalid machine state: %s"),
3911 Global::stringifyMachineState(mData->mMachineState));
3912
3913 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3914 aControllerName,
3915 aControllerPort,
3916 aDevice);
3917 if (!pAttach)
3918 return setError(VBOX_E_OBJECT_NOT_FOUND,
3919 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3920 aDevice, aControllerPort, aControllerName);
3921
3922
3923 setModified(IsModified_Storage);
3924 mMediaData.backup();
3925
3926 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3927
3928 if (pAttach->getType() != DeviceType_DVD)
3929 return setError(E_INVALIDARG,
3930 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3931 aDevice, aControllerPort, aControllerName);
3932 pAttach->updatePassthrough(!!aPassthrough);
3933
3934 return S_OK;
3935}
3936
3937STDMETHODIMP Machine::SetBandwidthGroupForDevice(IN_BSTR aControllerName, LONG aControllerPort,
3938 LONG aDevice, IBandwidthGroup *aBandwidthGroup)
3939{
3940 CheckComArgStrNotEmptyOrNull(aControllerName);
3941
3942 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3943 aControllerName, aControllerPort, aDevice));
3944
3945 AutoCaller autoCaller(this);
3946 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3947
3948 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3949
3950 HRESULT rc = checkStateDependency(MutableStateDep);
3951 if (FAILED(rc)) return rc;
3952
3953 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3954
3955 if (Global::IsOnlineOrTransient(mData->mMachineState))
3956 return setError(VBOX_E_INVALID_VM_STATE,
3957 tr("Invalid machine state: %s"),
3958 Global::stringifyMachineState(mData->mMachineState));
3959
3960 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3961 aControllerName,
3962 aControllerPort,
3963 aDevice);
3964 if (!pAttach)
3965 return setError(VBOX_E_OBJECT_NOT_FOUND,
3966 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3967 aDevice, aControllerPort, aControllerName);
3968
3969
3970 setModified(IsModified_Storage);
3971 mMediaData.backup();
3972
3973 ComObjPtr<BandwidthGroup> group = static_cast<BandwidthGroup*>(aBandwidthGroup);
3974 if (aBandwidthGroup && group.isNull())
3975 return setError(E_INVALIDARG, "The given bandwidth group pointer is invalid");
3976
3977 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3978
3979 const Utf8Str strBandwidthGroupOld = pAttach->getBandwidthGroup();
3980 if (strBandwidthGroupOld.isNotEmpty())
3981 {
3982 /* Get the bandwidth group object and release it - this must not fail. */
3983 ComObjPtr<BandwidthGroup> pBandwidthGroupOld;
3984 rc = getBandwidthGroup(strBandwidthGroupOld, pBandwidthGroupOld, false);
3985 Assert(SUCCEEDED(rc));
3986
3987 pBandwidthGroupOld->release();
3988 pAttach->updateBandwidthGroup(Utf8Str::Empty);
3989 }
3990
3991 if (!group.isNull())
3992 {
3993 group->reference();
3994 pAttach->updateBandwidthGroup(group->getName());
3995 }
3996
3997 return S_OK;
3998}
3999
4000
4001STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
4002 LONG aControllerPort,
4003 LONG aDevice,
4004 IMedium *aMedium,
4005 BOOL aForce)
4006{
4007 int rc = S_OK;
4008 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aForce=%d\n",
4009 aControllerName, aControllerPort, aDevice, aForce));
4010
4011 CheckComArgStrNotEmptyOrNull(aControllerName);
4012
4013 AutoCaller autoCaller(this);
4014 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4015
4016 // request the host lock first, since might be calling Host methods for getting host drives;
4017 // next, protect the media tree all the while we're in here, as well as our member variables
4018 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
4019 this->lockHandle(),
4020 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4021
4022 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4023 aControllerName,
4024 aControllerPort,
4025 aDevice);
4026 if (pAttach.isNull())
4027 return setError(VBOX_E_OBJECT_NOT_FOUND,
4028 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
4029 aDevice, aControllerPort, aControllerName);
4030
4031 /* Remember previously mounted medium. The medium before taking the
4032 * backup is not necessarily the same thing. */
4033 ComObjPtr<Medium> oldmedium;
4034 oldmedium = pAttach->getMedium();
4035
4036 ComObjPtr<Medium> pMedium = static_cast<Medium*>(aMedium);
4037 if (aMedium && pMedium.isNull())
4038 return setError(E_INVALIDARG, "The given medium pointer is invalid");
4039
4040 AutoCaller mediumCaller(pMedium);
4041 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
4042
4043 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4044 if (pMedium)
4045 {
4046 DeviceType_T mediumType = pAttach->getType();
4047 switch (mediumType)
4048 {
4049 case DeviceType_DVD:
4050 case DeviceType_Floppy:
4051 break;
4052
4053 default:
4054 return setError(VBOX_E_INVALID_OBJECT_STATE,
4055 tr("The device at port %d, device %d of controller '%ls' of this virtual machine is not removeable"),
4056 aControllerPort,
4057 aDevice,
4058 aControllerName);
4059 }
4060 }
4061
4062 setModified(IsModified_Storage);
4063 mMediaData.backup();
4064
4065 GuidList llRegistriesThatNeedSaving;
4066
4067 {
4068 // The backup operation makes the pAttach reference point to the
4069 // old settings. Re-get the correct reference.
4070 pAttach = findAttachment(mMediaData->mAttachments,
4071 aControllerName,
4072 aControllerPort,
4073 aDevice);
4074 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4075 if (!oldmedium.isNull())
4076 oldmedium->removeBackReference(mData->mUuid);
4077 if (!pMedium.isNull())
4078 {
4079 pMedium->addBackReference(mData->mUuid);
4080
4081 addMediumToRegistry(pMedium, llRegistriesThatNeedSaving, NULL /* Guid *puuid */ );
4082 }
4083
4084 pAttach->updateMedium(pMedium);
4085 }
4086
4087 setModified(IsModified_Storage);
4088
4089 mediumLock.release();
4090 multiLock.release();
4091 rc = onMediumChange(pAttach, aForce);
4092 multiLock.acquire();
4093 mediumLock.acquire();
4094
4095 /* On error roll back this change only. */
4096 if (FAILED(rc))
4097 {
4098 if (!pMedium.isNull())
4099 pMedium->removeBackReference(mData->mUuid);
4100 pAttach = findAttachment(mMediaData->mAttachments,
4101 aControllerName,
4102 aControllerPort,
4103 aDevice);
4104 /* If the attachment is gone in the meantime, bail out. */
4105 if (pAttach.isNull())
4106 return rc;
4107 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
4108 if (!oldmedium.isNull())
4109 oldmedium->addBackReference(mData->mUuid);
4110 pAttach->updateMedium(oldmedium);
4111 }
4112
4113 mediumLock.release();
4114 multiLock.release();
4115
4116 mParent->saveRegistries(llRegistriesThatNeedSaving);
4117
4118 return rc;
4119}
4120
4121STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
4122 LONG aControllerPort,
4123 LONG aDevice,
4124 IMedium **aMedium)
4125{
4126 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
4127 aControllerName, aControllerPort, aDevice));
4128
4129 CheckComArgStrNotEmptyOrNull(aControllerName);
4130 CheckComArgOutPointerValid(aMedium);
4131
4132 AutoCaller autoCaller(this);
4133 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4134
4135 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4136
4137 *aMedium = NULL;
4138
4139 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4140 aControllerName,
4141 aControllerPort,
4142 aDevice);
4143 if (pAttach.isNull())
4144 return setError(VBOX_E_OBJECT_NOT_FOUND,
4145 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4146 aDevice, aControllerPort, aControllerName);
4147
4148 pAttach->getMedium().queryInterfaceTo(aMedium);
4149
4150 return S_OK;
4151}
4152
4153STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
4154{
4155 CheckComArgOutPointerValid(port);
4156 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
4157
4158 AutoCaller autoCaller(this);
4159 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4160
4161 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4162
4163 mSerialPorts[slot].queryInterfaceTo(port);
4164
4165 return S_OK;
4166}
4167
4168STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
4169{
4170 CheckComArgOutPointerValid(port);
4171 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
4172
4173 AutoCaller autoCaller(this);
4174 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4175
4176 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4177
4178 mParallelPorts[slot].queryInterfaceTo(port);
4179
4180 return S_OK;
4181}
4182
4183STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
4184{
4185 CheckComArgOutPointerValid(adapter);
4186 CheckComArgExpr(slot, slot < RT_ELEMENTS(mNetworkAdapters));
4187
4188 AutoCaller autoCaller(this);
4189 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4190
4191 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4192
4193 mNetworkAdapters[slot].queryInterfaceTo(adapter);
4194
4195 return S_OK;
4196}
4197
4198STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
4199{
4200 if (ComSafeArrayOutIsNull(aKeys))
4201 return E_POINTER;
4202
4203 AutoCaller autoCaller(this);
4204 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4205
4206 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4207
4208 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
4209 int i = 0;
4210 for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
4211 it != mData->pMachineConfigFile->mapExtraDataItems.end();
4212 ++it, ++i)
4213 {
4214 const Utf8Str &strKey = it->first;
4215 strKey.cloneTo(&saKeys[i]);
4216 }
4217 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
4218
4219 return S_OK;
4220 }
4221
4222 /**
4223 * @note Locks this object for reading.
4224 */
4225STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
4226 BSTR *aValue)
4227{
4228 CheckComArgStrNotEmptyOrNull(aKey);
4229 CheckComArgOutPointerValid(aValue);
4230
4231 AutoCaller autoCaller(this);
4232 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4233
4234 /* start with nothing found */
4235 Bstr bstrResult("");
4236
4237 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4238
4239 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
4240 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4241 // found:
4242 bstrResult = it->second; // source is a Utf8Str
4243
4244 /* return the result to caller (may be empty) */
4245 bstrResult.cloneTo(aValue);
4246
4247 return S_OK;
4248}
4249
4250 /**
4251 * @note Locks mParent for writing + this object for writing.
4252 */
4253STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
4254{
4255 CheckComArgStrNotEmptyOrNull(aKey);
4256
4257 AutoCaller autoCaller(this);
4258 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4259
4260 Utf8Str strKey(aKey);
4261 Utf8Str strValue(aValue);
4262 Utf8Str strOldValue; // empty
4263
4264 // locking note: we only hold the read lock briefly to look up the old value,
4265 // then release it and call the onExtraCanChange callbacks. There is a small
4266 // chance of a race insofar as the callback might be called twice if two callers
4267 // change the same key at the same time, but that's a much better solution
4268 // than the deadlock we had here before. The actual changing of the extradata
4269 // is then performed under the write lock and race-free.
4270
4271 // look up the old value first; if nothing has changed then we need not do anything
4272 {
4273 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
4274 settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
4275 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
4276 strOldValue = it->second;
4277 }
4278
4279 bool fChanged;
4280 if ((fChanged = (strOldValue != strValue)))
4281 {
4282 // ask for permission from all listeners outside the locks;
4283 // onExtraDataCanChange() only briefly requests the VirtualBox
4284 // lock to copy the list of callbacks to invoke
4285 Bstr error;
4286 Bstr bstrValue(aValue);
4287
4288 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue.raw(), error))
4289 {
4290 const char *sep = error.isEmpty() ? "" : ": ";
4291 CBSTR err = error.raw();
4292 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
4293 sep, err));
4294 return setError(E_ACCESSDENIED,
4295 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
4296 aKey,
4297 bstrValue.raw(),
4298 sep,
4299 err);
4300 }
4301
4302 // data is changing and change not vetoed: then write it out under the lock
4303 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4304
4305 if (isSnapshotMachine())
4306 {
4307 HRESULT rc = checkStateDependency(MutableStateDep);
4308 if (FAILED(rc)) return rc;
4309 }
4310
4311 if (strValue.isEmpty())
4312 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
4313 else
4314 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
4315 // creates a new key if needed
4316
4317 bool fNeedsGlobalSaveSettings = false;
4318 saveSettings(&fNeedsGlobalSaveSettings);
4319
4320 if (fNeedsGlobalSaveSettings)
4321 {
4322 // save the global settings; for that we should hold only the VirtualBox lock
4323 alock.release();
4324 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
4325 mParent->saveSettings();
4326 }
4327 }
4328
4329 // fire notification outside the lock
4330 if (fChanged)
4331 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
4332
4333 return S_OK;
4334}
4335
4336STDMETHODIMP Machine::SaveSettings()
4337{
4338 AutoCaller autoCaller(this);
4339 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4340
4341 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
4342
4343 /* when there was auto-conversion, we want to save the file even if
4344 * the VM is saved */
4345 HRESULT rc = checkStateDependency(MutableStateDep);
4346 if (FAILED(rc)) return rc;
4347
4348 /* the settings file path may never be null */
4349 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
4350
4351 /* save all VM data excluding snapshots */
4352 bool fNeedsGlobalSaveSettings = false;
4353 rc = saveSettings(&fNeedsGlobalSaveSettings);
4354 mlock.release();
4355
4356 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
4357 {
4358 // save the global settings; for that we should hold only the VirtualBox lock
4359 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
4360 rc = mParent->saveSettings();
4361 }
4362
4363 return rc;
4364}
4365
4366STDMETHODIMP Machine::DiscardSettings()
4367{
4368 AutoCaller autoCaller(this);
4369 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4370
4371 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4372
4373 HRESULT rc = checkStateDependency(MutableStateDep);
4374 if (FAILED(rc)) return rc;
4375
4376 /*
4377 * during this rollback, the session will be notified if data has
4378 * been actually changed
4379 */
4380 rollback(true /* aNotify */);
4381
4382 return S_OK;
4383}
4384
4385/** @note Locks objects! */
4386STDMETHODIMP Machine::Unregister(CleanupMode_T cleanupMode,
4387 ComSafeArrayOut(IMedium*, aMedia))
4388{
4389 // use AutoLimitedCaller because this call is valid on inaccessible machines as well
4390 AutoLimitedCaller autoCaller(this);
4391 AssertComRCReturnRC(autoCaller.rc());
4392
4393 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4394
4395 Guid id(getId());
4396
4397 if (mData->mSession.mState != SessionState_Unlocked)
4398 return setError(VBOX_E_INVALID_OBJECT_STATE,
4399 tr("Cannot unregister the machine '%s' while it is locked"),
4400 mUserData->s.strName.c_str());
4401
4402 // wait for state dependents to drop to zero
4403 ensureNoStateDependencies();
4404
4405 if (!mData->mAccessible)
4406 {
4407 // inaccessible maschines can only be unregistered; uninitialize ourselves
4408 // here because currently there may be no unregistered that are inaccessible
4409 // (this state combination is not supported). Note releasing the caller and
4410 // leaving the lock before calling uninit()
4411 alock.leave();
4412 autoCaller.release();
4413
4414 uninit();
4415
4416 mParent->unregisterMachine(this, id);
4417 // calls VirtualBox::saveSettings()
4418
4419 return S_OK;
4420 }
4421
4422 HRESULT rc = S_OK;
4423
4424 // discard saved state
4425 if (mData->mMachineState == MachineState_Saved)
4426 {
4427 // add the saved state file to the list of files the caller should delete
4428 Assert(!mSSData->strStateFilePath.isEmpty());
4429 mData->llFilesToDelete.push_back(mSSData->strStateFilePath);
4430
4431 mSSData->strStateFilePath.setNull();
4432
4433 // unconditionally set the machine state to powered off, we now
4434 // know no session has locked the machine
4435 mData->mMachineState = MachineState_PoweredOff;
4436 }
4437
4438 size_t cSnapshots = 0;
4439 if (mData->mFirstSnapshot)
4440 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4441 if (cSnapshots && cleanupMode == CleanupMode_UnregisterOnly)
4442 // fail now before we start detaching media
4443 return setError(VBOX_E_INVALID_OBJECT_STATE,
4444 tr("Cannot unregister the machine '%s' because it has %d snapshots"),
4445 mUserData->s.strName.c_str(), cSnapshots);
4446
4447 // This list collects the medium objects from all medium attachments
4448 // which we will detach from the machine and its snapshots, in a specific
4449 // order which allows for closing all media without getting "media in use"
4450 // errors, simply by going through the list from the front to the back:
4451 // 1) first media from machine attachments (these have the "leaf" attachments with snapshots
4452 // and must be closed before the parent media from the snapshots, or closing the parents
4453 // will fail because they still have children);
4454 // 2) media from the youngest snapshots followed by those from the parent snapshots until
4455 // the root ("first") snapshot of the machine.
4456 MediaList llMedia;
4457
4458 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4459 && mMediaData->mAttachments.size()
4460 )
4461 {
4462 // we have media attachments: detach them all and add the Medium objects to our list
4463 if (cleanupMode != CleanupMode_UnregisterOnly)
4464 detachAllMedia(alock, NULL /* pSnapshot */, cleanupMode, llMedia);
4465 else
4466 return setError(VBOX_E_INVALID_OBJECT_STATE,
4467 tr("Cannot unregister the machine '%s' because it has %d media attachments"),
4468 mUserData->s.strName.c_str(), mMediaData->mAttachments.size());
4469 }
4470
4471 if (cSnapshots)
4472 {
4473 // autoCleanup must be true here, or we would have failed above
4474
4475 // add the media from the medium attachments of the snapshots to llMedia
4476 // as well, after the "main" machine media; Snapshot::uninitRecursively()
4477 // calls Machine::detachAllMedia() for the snapshot machine, recursing
4478 // into the children first
4479
4480 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
4481 MachineState_T oldState = mData->mMachineState;
4482 mData->mMachineState = MachineState_DeletingSnapshot;
4483
4484 // make a copy of the first snapshot so the refcount does not drop to 0
4485 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
4486 // because of the AutoCaller voodoo)
4487 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
4488
4489 // GO!
4490 pFirstSnapshot->uninitRecursively(alock, cleanupMode, llMedia, mData->llFilesToDelete);
4491
4492 mData->mMachineState = oldState;
4493 }
4494
4495 if (FAILED(rc))
4496 {
4497 rollbackMedia();
4498 return rc;
4499 }
4500
4501 // commit all the media changes made above
4502 commitMedia();
4503
4504 mData->mRegistered = false;
4505
4506 // machine lock no longer needed
4507 alock.release();
4508
4509 // return media to caller
4510 SafeIfaceArray<IMedium> sfaMedia(llMedia);
4511 sfaMedia.detachTo(ComSafeArrayOutArg(aMedia));
4512
4513 mParent->unregisterMachine(this, id);
4514 // calls VirtualBox::saveSettings()
4515
4516 return S_OK;
4517}
4518
4519struct Machine::DeleteTask
4520{
4521 ComObjPtr<Machine> pMachine;
4522 std::list<Utf8Str> llFilesToDelete;
4523 ComObjPtr<Progress> pProgress;
4524 GuidList llRegistriesThatNeedSaving;
4525};
4526
4527STDMETHODIMP Machine::Delete(ComSafeArrayIn(IMedium*, aMedia), IProgress **aProgress)
4528{
4529 LogFlowFuncEnter();
4530
4531 AutoCaller autoCaller(this);
4532 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4533
4534 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4535
4536 HRESULT rc = checkStateDependency(MutableStateDep);
4537 if (FAILED(rc)) return rc;
4538
4539 if (mData->mRegistered)
4540 return setError(VBOX_E_INVALID_VM_STATE,
4541 tr("Cannot delete settings of a registered machine"));
4542
4543 DeleteTask *pTask = new DeleteTask;
4544 pTask->pMachine = this;
4545 com::SafeIfaceArray<IMedium> sfaMedia(ComSafeArrayInArg(aMedia));
4546
4547 // collect files to delete
4548 pTask->llFilesToDelete = mData->llFilesToDelete; // saved states pushed here by Unregister()
4549
4550 for (size_t i = 0; i < sfaMedia.size(); ++i)
4551 {
4552 IMedium *pIMedium(sfaMedia[i]);
4553 ComObjPtr<Medium> pMedium = static_cast<Medium*>(pIMedium);
4554 if (pMedium.isNull())
4555 return setError(E_INVALIDARG, "The given medium pointer %d is invalid", i);
4556 AutoCaller mediumAutoCaller(pMedium);
4557 if (FAILED(mediumAutoCaller.rc())) return mediumAutoCaller.rc();
4558
4559 Utf8Str bstrLocation = pMedium->getLocationFull();
4560
4561 bool fDoesMediumNeedFileDeletion = pMedium->isMediumFormatFile();
4562
4563 // close the medium now; if that succeeds, then that means the medium is no longer
4564 // in use and we can add it to the list of files to delete
4565 rc = pMedium->close(&pTask->llRegistriesThatNeedSaving,
4566 mediumAutoCaller);
4567 if (SUCCEEDED(rc) && fDoesMediumNeedFileDeletion)
4568 pTask->llFilesToDelete.push_back(bstrLocation);
4569 }
4570 if (mData->pMachineConfigFile->fileExists())
4571 pTask->llFilesToDelete.push_back(mData->m_strConfigFileFull);
4572
4573 pTask->pProgress.createObject();
4574 pTask->pProgress->init(getVirtualBox(),
4575 static_cast<IMachine*>(this) /* aInitiator */,
4576 Bstr(tr("Deleting files")).raw(),
4577 true /* fCancellable */,
4578 pTask->llFilesToDelete.size() + 1, // cOperations
4579 BstrFmt(tr("Deleting '%s'"), pTask->llFilesToDelete.front().c_str()).raw());
4580
4581 int vrc = RTThreadCreate(NULL,
4582 Machine::deleteThread,
4583 (void*)pTask,
4584 0,
4585 RTTHREADTYPE_MAIN_WORKER,
4586 0,
4587 "MachineDelete");
4588
4589 pTask->pProgress.queryInterfaceTo(aProgress);
4590
4591 if (RT_FAILURE(vrc))
4592 {
4593 delete pTask;
4594 return setError(E_FAIL, "Could not create MachineDelete thread (%Rrc)", vrc);
4595 }
4596
4597 LogFlowFuncLeave();
4598
4599 return S_OK;
4600}
4601
4602/**
4603 * Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
4604 * calls Machine::deleteTaskWorker() on the actual machine object.
4605 * @param Thread
4606 * @param pvUser
4607 * @return
4608 */
4609/*static*/
4610DECLCALLBACK(int) Machine::deleteThread(RTTHREAD Thread, void *pvUser)
4611{
4612 LogFlowFuncEnter();
4613
4614 DeleteTask *pTask = (DeleteTask*)pvUser;
4615 Assert(pTask);
4616 Assert(pTask->pMachine);
4617 Assert(pTask->pProgress);
4618
4619 HRESULT rc = pTask->pMachine->deleteTaskWorker(*pTask);
4620 pTask->pProgress->notifyComplete(rc);
4621
4622 delete pTask;
4623
4624 LogFlowFuncLeave();
4625
4626 NOREF(Thread);
4627
4628 return VINF_SUCCESS;
4629}
4630
4631/**
4632 * Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
4633 * @param task
4634 * @return
4635 */
4636HRESULT Machine::deleteTaskWorker(DeleteTask &task)
4637{
4638 AutoCaller autoCaller(this);
4639 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4640
4641 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4642
4643 ULONG uLogHistoryCount = 3;
4644 ComPtr<ISystemProperties> systemProperties;
4645 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4646 if (!systemProperties.isNull())
4647 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4648
4649 // delete the files pushed on the task list by Machine::Delete()
4650 // (this includes saved states of the machine and snapshots and
4651 // medium storage files from the IMedium list passed in, and the
4652 // machine XML file)
4653 std::list<Utf8Str>::const_iterator it = task.llFilesToDelete.begin();
4654 while (it != task.llFilesToDelete.end())
4655 {
4656 const Utf8Str &strFile = *it;
4657 LogFunc(("Deleting file %s\n", strFile.c_str()));
4658 RTFileDelete(strFile.c_str());
4659
4660 ++it;
4661 if (it == task.llFilesToDelete.end())
4662 {
4663 task.pProgress->SetNextOperation(Bstr(tr("Cleaning up machine directory")).raw(), 1);
4664 break;
4665 }
4666
4667 task.pProgress->SetNextOperation(BstrFmt(tr("Deleting '%s'"), it->c_str()).raw(), 1);
4668 }
4669
4670 /* delete the settings only when the file actually exists */
4671 if (mData->pMachineConfigFile->fileExists())
4672 {
4673 /* Delete any backup or uncommitted XML files. Ignore failures.
4674 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4675 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4676 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4677 RTFileDelete(otherXml.c_str());
4678 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4679 RTFileDelete(otherXml.c_str());
4680
4681 /* delete the Logs folder, nothing important should be left
4682 * there (we don't check for errors because the user might have
4683 * some private files there that we don't want to delete) */
4684 Utf8Str logFolder;
4685 getLogFolder(logFolder);
4686 Assert(logFolder.length());
4687 if (RTDirExists(logFolder.c_str()))
4688 {
4689 /* Delete all VBox.log[.N] files from the Logs folder
4690 * (this must be in sync with the rotation logic in
4691 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4692 * files that may have been created by the GUI. */
4693 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4694 logFolder.c_str(), RTPATH_DELIMITER);
4695 RTFileDelete(log.c_str());
4696 log = Utf8StrFmt("%s%cVBox.png",
4697 logFolder.c_str(), RTPATH_DELIMITER);
4698 RTFileDelete(log.c_str());
4699 for (int i = uLogHistoryCount; i > 0; i--)
4700 {
4701 log = Utf8StrFmt("%s%cVBox.log.%d",
4702 logFolder.c_str(), RTPATH_DELIMITER, i);
4703 RTFileDelete(log.c_str());
4704 log = Utf8StrFmt("%s%cVBox.png.%d",
4705 logFolder.c_str(), RTPATH_DELIMITER, i);
4706 RTFileDelete(log.c_str());
4707 }
4708
4709 RTDirRemove(logFolder.c_str());
4710 }
4711
4712 /* delete the Snapshots folder, nothing important should be left
4713 * there (we don't check for errors because the user might have
4714 * some private files there that we don't want to delete) */
4715 Utf8Str strFullSnapshotFolder;
4716 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
4717 Assert(!strFullSnapshotFolder.isEmpty());
4718 if (RTDirExists(strFullSnapshotFolder.c_str()))
4719 RTDirRemove(strFullSnapshotFolder.c_str());
4720
4721 // delete the directory that contains the settings file, but only
4722 // if it matches the VM name
4723 Utf8Str settingsDir;
4724 if (isInOwnDir(&settingsDir))
4725 RTDirRemove(settingsDir.c_str());
4726 }
4727
4728 alock.release();
4729
4730 mParent->saveRegistries(task.llRegistriesThatNeedSaving);
4731
4732 return S_OK;
4733}
4734
4735STDMETHODIMP Machine::FindSnapshot(IN_BSTR aNameOrId, ISnapshot **aSnapshot)
4736{
4737 CheckComArgOutPointerValid(aSnapshot);
4738
4739 AutoCaller autoCaller(this);
4740 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4741
4742 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4743
4744 ComObjPtr<Snapshot> pSnapshot;
4745 HRESULT rc;
4746
4747 if (!aNameOrId || !*aNameOrId)
4748 // null case (caller wants root snapshot): findSnapshotById() handles this
4749 rc = findSnapshotById(Guid(), pSnapshot, true /* aSetError */);
4750 else
4751 {
4752 Guid uuid(aNameOrId);
4753 if (!uuid.isEmpty())
4754 rc = findSnapshotById(uuid, pSnapshot, true /* aSetError */);
4755 else
4756 rc = findSnapshotByName(Utf8Str(aNameOrId), pSnapshot, true /* aSetError */);
4757 }
4758 pSnapshot.queryInterfaceTo(aSnapshot);
4759
4760 return rc;
4761}
4762
4763STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4764{
4765 CheckComArgStrNotEmptyOrNull(aName);
4766 CheckComArgStrNotEmptyOrNull(aHostPath);
4767
4768 AutoCaller autoCaller(this);
4769 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4770
4771 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4772
4773 HRESULT rc = checkStateDependency(MutableStateDep);
4774 if (FAILED(rc)) return rc;
4775
4776 Utf8Str strName(aName);
4777
4778 ComObjPtr<SharedFolder> sharedFolder;
4779 rc = findSharedFolder(strName, sharedFolder, false /* aSetError */);
4780 if (SUCCEEDED(rc))
4781 return setError(VBOX_E_OBJECT_IN_USE,
4782 tr("Shared folder named '%s' already exists"),
4783 strName.c_str());
4784
4785 sharedFolder.createObject();
4786 rc = sharedFolder->init(getMachine(),
4787 strName,
4788 aHostPath,
4789 !!aWritable,
4790 !!aAutoMount,
4791 true /* fFailOnError */);
4792 if (FAILED(rc)) return rc;
4793
4794 setModified(IsModified_SharedFolders);
4795 mHWData.backup();
4796 mHWData->mSharedFolders.push_back(sharedFolder);
4797
4798 /* inform the direct session if any */
4799 alock.leave();
4800 onSharedFolderChange();
4801
4802 return S_OK;
4803}
4804
4805STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4806{
4807 CheckComArgStrNotEmptyOrNull(aName);
4808
4809 AutoCaller autoCaller(this);
4810 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4811
4812 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4813
4814 HRESULT rc = checkStateDependency(MutableStateDep);
4815 if (FAILED(rc)) return rc;
4816
4817 ComObjPtr<SharedFolder> sharedFolder;
4818 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4819 if (FAILED(rc)) return rc;
4820
4821 setModified(IsModified_SharedFolders);
4822 mHWData.backup();
4823 mHWData->mSharedFolders.remove(sharedFolder);
4824
4825 /* inform the direct session if any */
4826 alock.leave();
4827 onSharedFolderChange();
4828
4829 return S_OK;
4830}
4831
4832STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4833{
4834 CheckComArgOutPointerValid(aCanShow);
4835
4836 /* start with No */
4837 *aCanShow = FALSE;
4838
4839 AutoCaller autoCaller(this);
4840 AssertComRCReturnRC(autoCaller.rc());
4841
4842 ComPtr<IInternalSessionControl> directControl;
4843 {
4844 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4845
4846 if (mData->mSession.mState != SessionState_Locked)
4847 return setError(VBOX_E_INVALID_VM_STATE,
4848 tr("Machine is not locked for session (session state: %s)"),
4849 Global::stringifySessionState(mData->mSession.mState));
4850
4851 directControl = mData->mSession.mDirectControl;
4852 }
4853
4854 /* ignore calls made after #OnSessionEnd() is called */
4855 if (!directControl)
4856 return S_OK;
4857
4858 LONG64 dummy;
4859 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
4860}
4861
4862STDMETHODIMP Machine::ShowConsoleWindow(LONG64 *aWinId)
4863{
4864 CheckComArgOutPointerValid(aWinId);
4865
4866 AutoCaller autoCaller(this);
4867 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4868
4869 ComPtr<IInternalSessionControl> directControl;
4870 {
4871 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4872
4873 if (mData->mSession.mState != SessionState_Locked)
4874 return setError(E_FAIL,
4875 tr("Machine is not locked for session (session state: %s)"),
4876 Global::stringifySessionState(mData->mSession.mState));
4877
4878 directControl = mData->mSession.mDirectControl;
4879 }
4880
4881 /* ignore calls made after #OnSessionEnd() is called */
4882 if (!directControl)
4883 return S_OK;
4884
4885 BOOL dummy;
4886 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
4887}
4888
4889#ifdef VBOX_WITH_GUEST_PROPS
4890/**
4891 * Look up a guest property in VBoxSVC's internal structures.
4892 */
4893HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4894 BSTR *aValue,
4895 LONG64 *aTimestamp,
4896 BSTR *aFlags) const
4897{
4898 using namespace guestProp;
4899
4900 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4901 Utf8Str strName(aName);
4902 HWData::GuestPropertyList::const_iterator it;
4903
4904 for (it = mHWData->mGuestProperties.begin();
4905 it != mHWData->mGuestProperties.end(); ++it)
4906 {
4907 if (it->strName == strName)
4908 {
4909 char szFlags[MAX_FLAGS_LEN + 1];
4910 it->strValue.cloneTo(aValue);
4911 *aTimestamp = it->mTimestamp;
4912 writeFlags(it->mFlags, szFlags);
4913 Bstr(szFlags).cloneTo(aFlags);
4914 break;
4915 }
4916 }
4917 return S_OK;
4918}
4919
4920/**
4921 * Query the VM that a guest property belongs to for the property.
4922 * @returns E_ACCESSDENIED if the VM process is not available or not
4923 * currently handling queries and the lookup should then be done in
4924 * VBoxSVC.
4925 */
4926HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4927 BSTR *aValue,
4928 LONG64 *aTimestamp,
4929 BSTR *aFlags) const
4930{
4931 HRESULT rc;
4932 ComPtr<IInternalSessionControl> directControl;
4933 directControl = mData->mSession.mDirectControl;
4934
4935 /* fail if we were called after #OnSessionEnd() is called. This is a
4936 * silly race condition. */
4937
4938 if (!directControl)
4939 rc = E_ACCESSDENIED;
4940 else
4941 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4942 false /* isSetter */,
4943 aValue, aTimestamp, aFlags);
4944 return rc;
4945}
4946#endif // VBOX_WITH_GUEST_PROPS
4947
4948STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4949 BSTR *aValue,
4950 LONG64 *aTimestamp,
4951 BSTR *aFlags)
4952{
4953#ifndef VBOX_WITH_GUEST_PROPS
4954 ReturnComNotImplemented();
4955#else // VBOX_WITH_GUEST_PROPS
4956 CheckComArgStrNotEmptyOrNull(aName);
4957 CheckComArgOutPointerValid(aValue);
4958 CheckComArgOutPointerValid(aTimestamp);
4959 CheckComArgOutPointerValid(aFlags);
4960
4961 AutoCaller autoCaller(this);
4962 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4963
4964 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4965 if (rc == E_ACCESSDENIED)
4966 /* The VM is not running or the service is not (yet) accessible */
4967 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4968 return rc;
4969#endif // VBOX_WITH_GUEST_PROPS
4970}
4971
4972STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4973{
4974 LONG64 dummyTimestamp;
4975 Bstr dummyFlags;
4976 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
4977}
4978
4979STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, LONG64 *aTimestamp)
4980{
4981 Bstr dummyValue;
4982 Bstr dummyFlags;
4983 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
4984}
4985
4986#ifdef VBOX_WITH_GUEST_PROPS
4987/**
4988 * Set a guest property in VBoxSVC's internal structures.
4989 */
4990HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4991 IN_BSTR aFlags)
4992{
4993 using namespace guestProp;
4994
4995 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4996 HRESULT rc = S_OK;
4997 HWData::GuestProperty property;
4998 property.mFlags = NILFLAG;
4999 bool found = false;
5000
5001 rc = checkStateDependency(MutableStateDep);
5002 if (FAILED(rc)) return rc;
5003
5004 try
5005 {
5006 Utf8Str utf8Name(aName);
5007 Utf8Str utf8Flags(aFlags);
5008 uint32_t fFlags = NILFLAG;
5009 if ( (aFlags != NULL)
5010 && RT_FAILURE(validateFlags(utf8Flags.c_str(), &fFlags))
5011 )
5012 return setError(E_INVALIDARG,
5013 tr("Invalid flag values: '%ls'"),
5014 aFlags);
5015
5016 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
5017 * know, this is simple and do an OK job atm.) */
5018 HWData::GuestPropertyList::iterator it;
5019 for (it = mHWData->mGuestProperties.begin();
5020 it != mHWData->mGuestProperties.end(); ++it)
5021 if (it->strName == utf8Name)
5022 {
5023 property = *it;
5024 if (it->mFlags & (RDONLYHOST))
5025 rc = setError(E_ACCESSDENIED,
5026 tr("The property '%ls' cannot be changed by the host"),
5027 aName);
5028 else
5029 {
5030 setModified(IsModified_MachineData);
5031 mHWData.backup(); // @todo r=dj backup in a loop?!?
5032
5033 /* The backup() operation invalidates our iterator, so
5034 * get a new one. */
5035 for (it = mHWData->mGuestProperties.begin();
5036 it->strName != utf8Name;
5037 ++it)
5038 ;
5039 mHWData->mGuestProperties.erase(it);
5040 }
5041 found = true;
5042 break;
5043 }
5044 if (found && SUCCEEDED(rc))
5045 {
5046 if (*aValue)
5047 {
5048 RTTIMESPEC time;
5049 property.strValue = aValue;
5050 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5051 if (aFlags != NULL)
5052 property.mFlags = fFlags;
5053 mHWData->mGuestProperties.push_back(property);
5054 }
5055 }
5056 else if (SUCCEEDED(rc) && *aValue)
5057 {
5058 RTTIMESPEC time;
5059 setModified(IsModified_MachineData);
5060 mHWData.backup();
5061 property.strName = aName;
5062 property.strValue = aValue;
5063 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
5064 property.mFlags = fFlags;
5065 mHWData->mGuestProperties.push_back(property);
5066 }
5067 if ( SUCCEEDED(rc)
5068 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
5069 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
5070 RTSTR_MAX,
5071 utf8Name.c_str(),
5072 RTSTR_MAX,
5073 NULL)
5074 )
5075 )
5076 {
5077 /** @todo r=bird: Why aren't we leaving the lock here? The
5078 * same code in PushGuestProperty does... */
5079 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
5080 }
5081 }
5082 catch (std::bad_alloc &)
5083 {
5084 rc = E_OUTOFMEMORY;
5085 }
5086
5087 return rc;
5088}
5089
5090/**
5091 * Set a property on the VM that that property belongs to.
5092 * @returns E_ACCESSDENIED if the VM process is not available or not
5093 * currently handling queries and the setting should then be done in
5094 * VBoxSVC.
5095 */
5096HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
5097 IN_BSTR aFlags)
5098{
5099 HRESULT rc;
5100
5101 try
5102 {
5103 ComPtr<IInternalSessionControl> directControl = mData->mSession.mDirectControl;
5104
5105 BSTR dummy = NULL; /* will not be changed (setter) */
5106 LONG64 dummy64;
5107 if (!directControl)
5108 rc = E_ACCESSDENIED;
5109 else
5110 /** @todo Fix when adding DeleteGuestProperty(),
5111 see defect. */
5112 rc = directControl->AccessGuestProperty(aName, aValue, aFlags,
5113 true /* isSetter */,
5114 &dummy, &dummy64, &dummy);
5115 }
5116 catch (std::bad_alloc &)
5117 {
5118 rc = E_OUTOFMEMORY;
5119 }
5120
5121 return rc;
5122}
5123#endif // VBOX_WITH_GUEST_PROPS
5124
5125STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
5126 IN_BSTR aFlags)
5127{
5128#ifndef VBOX_WITH_GUEST_PROPS
5129 ReturnComNotImplemented();
5130#else // VBOX_WITH_GUEST_PROPS
5131 CheckComArgStrNotEmptyOrNull(aName);
5132 CheckComArgMaybeNull(aFlags);
5133 CheckComArgMaybeNull(aValue);
5134
5135 AutoCaller autoCaller(this);
5136 if (FAILED(autoCaller.rc()))
5137 return autoCaller.rc();
5138
5139 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
5140 if (rc == E_ACCESSDENIED)
5141 /* The VM is not running or the service is not (yet) accessible */
5142 rc = setGuestPropertyToService(aName, aValue, aFlags);
5143 return rc;
5144#endif // VBOX_WITH_GUEST_PROPS
5145}
5146
5147STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
5148{
5149 return SetGuestProperty(aName, aValue, NULL);
5150}
5151
5152#ifdef VBOX_WITH_GUEST_PROPS
5153/**
5154 * Enumerate the guest properties in VBoxSVC's internal structures.
5155 */
5156HRESULT Machine::enumerateGuestPropertiesInService
5157 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5158 ComSafeArrayOut(BSTR, aValues),
5159 ComSafeArrayOut(LONG64, aTimestamps),
5160 ComSafeArrayOut(BSTR, aFlags))
5161{
5162 using namespace guestProp;
5163
5164 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5165 Utf8Str strPatterns(aPatterns);
5166
5167 /*
5168 * Look for matching patterns and build up a list.
5169 */
5170 HWData::GuestPropertyList propList;
5171 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
5172 it != mHWData->mGuestProperties.end();
5173 ++it)
5174 if ( strPatterns.isEmpty()
5175 || RTStrSimplePatternMultiMatch(strPatterns.c_str(),
5176 RTSTR_MAX,
5177 it->strName.c_str(),
5178 RTSTR_MAX,
5179 NULL)
5180 )
5181 propList.push_back(*it);
5182
5183 /*
5184 * And build up the arrays for returning the property information.
5185 */
5186 size_t cEntries = propList.size();
5187 SafeArray<BSTR> names(cEntries);
5188 SafeArray<BSTR> values(cEntries);
5189 SafeArray<LONG64> timestamps(cEntries);
5190 SafeArray<BSTR> flags(cEntries);
5191 size_t iProp = 0;
5192 for (HWData::GuestPropertyList::iterator it = propList.begin();
5193 it != propList.end();
5194 ++it)
5195 {
5196 char szFlags[MAX_FLAGS_LEN + 1];
5197 it->strName.cloneTo(&names[iProp]);
5198 it->strValue.cloneTo(&values[iProp]);
5199 timestamps[iProp] = it->mTimestamp;
5200 writeFlags(it->mFlags, szFlags);
5201 Bstr(szFlags).cloneTo(&flags[iProp]);
5202 ++iProp;
5203 }
5204 names.detachTo(ComSafeArrayOutArg(aNames));
5205 values.detachTo(ComSafeArrayOutArg(aValues));
5206 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
5207 flags.detachTo(ComSafeArrayOutArg(aFlags));
5208 return S_OK;
5209}
5210
5211/**
5212 * Enumerate the properties managed by a VM.
5213 * @returns E_ACCESSDENIED if the VM process is not available or not
5214 * currently handling queries and the setting should then be done in
5215 * VBoxSVC.
5216 */
5217HRESULT Machine::enumerateGuestPropertiesOnVM
5218 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
5219 ComSafeArrayOut(BSTR, aValues),
5220 ComSafeArrayOut(LONG64, aTimestamps),
5221 ComSafeArrayOut(BSTR, aFlags))
5222{
5223 HRESULT rc;
5224 ComPtr<IInternalSessionControl> directControl;
5225 directControl = mData->mSession.mDirectControl;
5226
5227 if (!directControl)
5228 rc = E_ACCESSDENIED;
5229 else
5230 rc = directControl->EnumerateGuestProperties
5231 (aPatterns, ComSafeArrayOutArg(aNames),
5232 ComSafeArrayOutArg(aValues),
5233 ComSafeArrayOutArg(aTimestamps),
5234 ComSafeArrayOutArg(aFlags));
5235 return rc;
5236}
5237#endif // VBOX_WITH_GUEST_PROPS
5238
5239STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
5240 ComSafeArrayOut(BSTR, aNames),
5241 ComSafeArrayOut(BSTR, aValues),
5242 ComSafeArrayOut(LONG64, aTimestamps),
5243 ComSafeArrayOut(BSTR, aFlags))
5244{
5245#ifndef VBOX_WITH_GUEST_PROPS
5246 ReturnComNotImplemented();
5247#else // VBOX_WITH_GUEST_PROPS
5248 CheckComArgMaybeNull(aPatterns);
5249 CheckComArgOutSafeArrayPointerValid(aNames);
5250 CheckComArgOutSafeArrayPointerValid(aValues);
5251 CheckComArgOutSafeArrayPointerValid(aTimestamps);
5252 CheckComArgOutSafeArrayPointerValid(aFlags);
5253
5254 AutoCaller autoCaller(this);
5255 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5256
5257 HRESULT rc = enumerateGuestPropertiesOnVM
5258 (aPatterns, ComSafeArrayOutArg(aNames),
5259 ComSafeArrayOutArg(aValues),
5260 ComSafeArrayOutArg(aTimestamps),
5261 ComSafeArrayOutArg(aFlags));
5262 if (rc == E_ACCESSDENIED)
5263 /* The VM is not running or the service is not (yet) accessible */
5264 rc = enumerateGuestPropertiesInService
5265 (aPatterns, ComSafeArrayOutArg(aNames),
5266 ComSafeArrayOutArg(aValues),
5267 ComSafeArrayOutArg(aTimestamps),
5268 ComSafeArrayOutArg(aFlags));
5269 return rc;
5270#endif // VBOX_WITH_GUEST_PROPS
5271}
5272
5273STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
5274 ComSafeArrayOut(IMediumAttachment*, aAttachments))
5275{
5276 MediaData::AttachmentList atts;
5277
5278 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
5279 if (FAILED(rc)) return rc;
5280
5281 SafeIfaceArray<IMediumAttachment> attachments(atts);
5282 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
5283
5284 return S_OK;
5285}
5286
5287STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
5288 LONG aControllerPort,
5289 LONG aDevice,
5290 IMediumAttachment **aAttachment)
5291{
5292 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
5293 aControllerName, aControllerPort, aDevice));
5294
5295 CheckComArgStrNotEmptyOrNull(aControllerName);
5296 CheckComArgOutPointerValid(aAttachment);
5297
5298 AutoCaller autoCaller(this);
5299 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5300
5301 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5302
5303 *aAttachment = NULL;
5304
5305 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
5306 aControllerName,
5307 aControllerPort,
5308 aDevice);
5309 if (pAttach.isNull())
5310 return setError(VBOX_E_OBJECT_NOT_FOUND,
5311 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
5312 aDevice, aControllerPort, aControllerName);
5313
5314 pAttach.queryInterfaceTo(aAttachment);
5315
5316 return S_OK;
5317}
5318
5319STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
5320 StorageBus_T aConnectionType,
5321 IStorageController **controller)
5322{
5323 CheckComArgStrNotEmptyOrNull(aName);
5324
5325 if ( (aConnectionType <= StorageBus_Null)
5326 || (aConnectionType > StorageBus_SAS))
5327 return setError(E_INVALIDARG,
5328 tr("Invalid connection type: %d"),
5329 aConnectionType);
5330
5331 AutoCaller autoCaller(this);
5332 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5333
5334 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5335
5336 HRESULT rc = checkStateDependency(MutableStateDep);
5337 if (FAILED(rc)) return rc;
5338
5339 /* try to find one with the name first. */
5340 ComObjPtr<StorageController> ctrl;
5341
5342 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
5343 if (SUCCEEDED(rc))
5344 return setError(VBOX_E_OBJECT_IN_USE,
5345 tr("Storage controller named '%ls' already exists"),
5346 aName);
5347
5348 ctrl.createObject();
5349
5350 /* get a new instance number for the storage controller */
5351 ULONG ulInstance = 0;
5352 bool fBootable = true;
5353 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5354 it != mStorageControllers->end();
5355 ++it)
5356 {
5357 if ((*it)->getStorageBus() == aConnectionType)
5358 {
5359 ULONG ulCurInst = (*it)->getInstance();
5360
5361 if (ulCurInst >= ulInstance)
5362 ulInstance = ulCurInst + 1;
5363
5364 /* Only one controller of each type can be marked as bootable. */
5365 if ((*it)->getBootable())
5366 fBootable = false;
5367 }
5368 }
5369
5370 rc = ctrl->init(this, aName, aConnectionType, ulInstance, fBootable);
5371 if (FAILED(rc)) return rc;
5372
5373 setModified(IsModified_Storage);
5374 mStorageControllers.backup();
5375 mStorageControllers->push_back(ctrl);
5376
5377 ctrl.queryInterfaceTo(controller);
5378
5379 /* inform the direct session if any */
5380 alock.leave();
5381 onStorageControllerChange();
5382
5383 return S_OK;
5384}
5385
5386STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
5387 IStorageController **aStorageController)
5388{
5389 CheckComArgStrNotEmptyOrNull(aName);
5390
5391 AutoCaller autoCaller(this);
5392 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5393
5394 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5395
5396 ComObjPtr<StorageController> ctrl;
5397
5398 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5399 if (SUCCEEDED(rc))
5400 ctrl.queryInterfaceTo(aStorageController);
5401
5402 return rc;
5403}
5404
5405STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
5406 IStorageController **aStorageController)
5407{
5408 AutoCaller autoCaller(this);
5409 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5410
5411 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5412
5413 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5414 it != mStorageControllers->end();
5415 ++it)
5416 {
5417 if ((*it)->getInstance() == aInstance)
5418 {
5419 (*it).queryInterfaceTo(aStorageController);
5420 return S_OK;
5421 }
5422 }
5423
5424 return setError(VBOX_E_OBJECT_NOT_FOUND,
5425 tr("Could not find a storage controller with instance number '%lu'"),
5426 aInstance);
5427}
5428
5429STDMETHODIMP Machine::SetStorageControllerBootable(IN_BSTR aName, BOOL fBootable)
5430{
5431 AutoCaller autoCaller(this);
5432 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5433
5434 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5435
5436 HRESULT rc = checkStateDependency(MutableStateDep);
5437 if (FAILED(rc)) return rc;
5438
5439 ComObjPtr<StorageController> ctrl;
5440
5441 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5442 if (SUCCEEDED(rc))
5443 {
5444 /* Ensure that only one controller of each type is marked as bootable. */
5445 if (fBootable == TRUE)
5446 {
5447 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5448 it != mStorageControllers->end();
5449 ++it)
5450 {
5451 ComObjPtr<StorageController> aCtrl = (*it);
5452
5453 if ( (aCtrl->getName() != Utf8Str(aName))
5454 && aCtrl->getBootable() == TRUE
5455 && aCtrl->getStorageBus() == ctrl->getStorageBus()
5456 && aCtrl->getControllerType() == ctrl->getControllerType())
5457 {
5458 aCtrl->setBootable(FALSE);
5459 break;
5460 }
5461 }
5462 }
5463
5464 if (SUCCEEDED(rc))
5465 {
5466 ctrl->setBootable(fBootable);
5467 setModified(IsModified_Storage);
5468 }
5469 }
5470
5471 if (SUCCEEDED(rc))
5472 {
5473 /* inform the direct session if any */
5474 alock.leave();
5475 onStorageControllerChange();
5476 }
5477
5478 return rc;
5479}
5480
5481STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
5482{
5483 CheckComArgStrNotEmptyOrNull(aName);
5484
5485 AutoCaller autoCaller(this);
5486 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5487
5488 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5489
5490 HRESULT rc = checkStateDependency(MutableStateDep);
5491 if (FAILED(rc)) return rc;
5492
5493 ComObjPtr<StorageController> ctrl;
5494 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5495 if (FAILED(rc)) return rc;
5496
5497 /* We can remove the controller only if there is no device attached. */
5498 /* check if the device slot is already busy */
5499 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5500 it != mMediaData->mAttachments.end();
5501 ++it)
5502 {
5503 if ((*it)->getControllerName() == aName)
5504 return setError(VBOX_E_OBJECT_IN_USE,
5505 tr("Storage controller named '%ls' has still devices attached"),
5506 aName);
5507 }
5508
5509 /* We can remove it now. */
5510 setModified(IsModified_Storage);
5511 mStorageControllers.backup();
5512
5513 ctrl->unshare();
5514
5515 mStorageControllers->remove(ctrl);
5516
5517 /* inform the direct session if any */
5518 alock.leave();
5519 onStorageControllerChange();
5520
5521 return S_OK;
5522}
5523
5524STDMETHODIMP Machine::QuerySavedGuestSize(ULONG uScreenId, ULONG *puWidth, ULONG *puHeight)
5525{
5526 LogFlowThisFunc(("\n"));
5527
5528 CheckComArgNotNull(puWidth);
5529 CheckComArgNotNull(puHeight);
5530
5531 uint32_t u32Width = 0;
5532 uint32_t u32Height = 0;
5533
5534 int vrc = readSavedGuestSize(mSSData->strStateFilePath, uScreenId, &u32Width, &u32Height);
5535 if (RT_FAILURE(vrc))
5536 return setError(VBOX_E_IPRT_ERROR,
5537 tr("Saved guest size is not available (%Rrc)"),
5538 vrc);
5539
5540 *puWidth = u32Width;
5541 *puHeight = u32Height;
5542
5543 return S_OK;
5544}
5545
5546STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5547{
5548 LogFlowThisFunc(("\n"));
5549
5550 CheckComArgNotNull(aSize);
5551 CheckComArgNotNull(aWidth);
5552 CheckComArgNotNull(aHeight);
5553
5554 if (aScreenId != 0)
5555 return E_NOTIMPL;
5556
5557 AutoCaller autoCaller(this);
5558 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5559
5560 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5561
5562 uint8_t *pu8Data = NULL;
5563 uint32_t cbData = 0;
5564 uint32_t u32Width = 0;
5565 uint32_t u32Height = 0;
5566
5567 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5568
5569 if (RT_FAILURE(vrc))
5570 return setError(VBOX_E_IPRT_ERROR,
5571 tr("Saved screenshot data is not available (%Rrc)"),
5572 vrc);
5573
5574 *aSize = cbData;
5575 *aWidth = u32Width;
5576 *aHeight = u32Height;
5577
5578 freeSavedDisplayScreenshot(pu8Data);
5579
5580 return S_OK;
5581}
5582
5583STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5584{
5585 LogFlowThisFunc(("\n"));
5586
5587 CheckComArgNotNull(aWidth);
5588 CheckComArgNotNull(aHeight);
5589 CheckComArgOutSafeArrayPointerValid(aData);
5590
5591 if (aScreenId != 0)
5592 return E_NOTIMPL;
5593
5594 AutoCaller autoCaller(this);
5595 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5596
5597 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5598
5599 uint8_t *pu8Data = NULL;
5600 uint32_t cbData = 0;
5601 uint32_t u32Width = 0;
5602 uint32_t u32Height = 0;
5603
5604 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5605
5606 if (RT_FAILURE(vrc))
5607 return setError(VBOX_E_IPRT_ERROR,
5608 tr("Saved screenshot data is not available (%Rrc)"),
5609 vrc);
5610
5611 *aWidth = u32Width;
5612 *aHeight = u32Height;
5613
5614 com::SafeArray<BYTE> bitmap(cbData);
5615 /* Convert pixels to format expected by the API caller. */
5616 if (aBGR)
5617 {
5618 /* [0] B, [1] G, [2] R, [3] A. */
5619 for (unsigned i = 0; i < cbData; i += 4)
5620 {
5621 bitmap[i] = pu8Data[i];
5622 bitmap[i + 1] = pu8Data[i + 1];
5623 bitmap[i + 2] = pu8Data[i + 2];
5624 bitmap[i + 3] = 0xff;
5625 }
5626 }
5627 else
5628 {
5629 /* [0] R, [1] G, [2] B, [3] A. */
5630 for (unsigned i = 0; i < cbData; i += 4)
5631 {
5632 bitmap[i] = pu8Data[i + 2];
5633 bitmap[i + 1] = pu8Data[i + 1];
5634 bitmap[i + 2] = pu8Data[i];
5635 bitmap[i + 3] = 0xff;
5636 }
5637 }
5638 bitmap.detachTo(ComSafeArrayOutArg(aData));
5639
5640 freeSavedDisplayScreenshot(pu8Data);
5641
5642 return S_OK;
5643}
5644
5645
5646STDMETHODIMP Machine::ReadSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5647{
5648 LogFlowThisFunc(("\n"));
5649
5650 CheckComArgNotNull(aWidth);
5651 CheckComArgNotNull(aHeight);
5652 CheckComArgOutSafeArrayPointerValid(aData);
5653
5654 if (aScreenId != 0)
5655 return E_NOTIMPL;
5656
5657 AutoCaller autoCaller(this);
5658 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5659
5660 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5661
5662 uint8_t *pu8Data = NULL;
5663 uint32_t cbData = 0;
5664 uint32_t u32Width = 0;
5665 uint32_t u32Height = 0;
5666
5667 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5668
5669 if (RT_FAILURE(vrc))
5670 return setError(VBOX_E_IPRT_ERROR,
5671 tr("Saved screenshot data is not available (%Rrc)"),
5672 vrc);
5673
5674 *aWidth = u32Width;
5675 *aHeight = u32Height;
5676
5677 uint8_t *pu8PNG = NULL;
5678 uint32_t cbPNG = 0;
5679 uint32_t cxPNG = 0;
5680 uint32_t cyPNG = 0;
5681
5682 DisplayMakePNG(pu8Data, u32Width, u32Height, &pu8PNG, &cbPNG, &cxPNG, &cyPNG, 0);
5683
5684 com::SafeArray<BYTE> screenData(cbPNG);
5685 screenData.initFrom(pu8PNG, cbPNG);
5686 RTMemFree(pu8PNG);
5687
5688 screenData.detachTo(ComSafeArrayOutArg(aData));
5689
5690 freeSavedDisplayScreenshot(pu8Data);
5691
5692 return S_OK;
5693}
5694
5695STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5696{
5697 LogFlowThisFunc(("\n"));
5698
5699 CheckComArgNotNull(aSize);
5700 CheckComArgNotNull(aWidth);
5701 CheckComArgNotNull(aHeight);
5702
5703 if (aScreenId != 0)
5704 return E_NOTIMPL;
5705
5706 AutoCaller autoCaller(this);
5707 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5708
5709 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5710
5711 uint8_t *pu8Data = NULL;
5712 uint32_t cbData = 0;
5713 uint32_t u32Width = 0;
5714 uint32_t u32Height = 0;
5715
5716 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5717
5718 if (RT_FAILURE(vrc))
5719 return setError(VBOX_E_IPRT_ERROR,
5720 tr("Saved screenshot data is not available (%Rrc)"),
5721 vrc);
5722
5723 *aSize = cbData;
5724 *aWidth = u32Width;
5725 *aHeight = u32Height;
5726
5727 freeSavedDisplayScreenshot(pu8Data);
5728
5729 return S_OK;
5730}
5731
5732STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5733{
5734 LogFlowThisFunc(("\n"));
5735
5736 CheckComArgNotNull(aWidth);
5737 CheckComArgNotNull(aHeight);
5738 CheckComArgOutSafeArrayPointerValid(aData);
5739
5740 if (aScreenId != 0)
5741 return E_NOTIMPL;
5742
5743 AutoCaller autoCaller(this);
5744 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5745
5746 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5747
5748 uint8_t *pu8Data = NULL;
5749 uint32_t cbData = 0;
5750 uint32_t u32Width = 0;
5751 uint32_t u32Height = 0;
5752
5753 int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5754
5755 if (RT_FAILURE(vrc))
5756 return setError(VBOX_E_IPRT_ERROR,
5757 tr("Saved screenshot thumbnail data is not available (%Rrc)"),
5758 vrc);
5759
5760 *aWidth = u32Width;
5761 *aHeight = u32Height;
5762
5763 com::SafeArray<BYTE> png(cbData);
5764 png.initFrom(pu8Data, cbData);
5765 png.detachTo(ComSafeArrayOutArg(aData));
5766
5767 freeSavedDisplayScreenshot(pu8Data);
5768
5769 return S_OK;
5770}
5771
5772STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5773{
5774 HRESULT rc = S_OK;
5775 LogFlowThisFunc(("\n"));
5776
5777 AutoCaller autoCaller(this);
5778 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5779
5780 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5781
5782 if (!mHWData->mCPUHotPlugEnabled)
5783 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5784
5785 if (aCpu >= mHWData->mCPUCount)
5786 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5787
5788 if (mHWData->mCPUAttached[aCpu])
5789 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5790
5791 alock.release();
5792 rc = onCPUChange(aCpu, false);
5793 alock.acquire();
5794 if (FAILED(rc)) return rc;
5795
5796 setModified(IsModified_MachineData);
5797 mHWData.backup();
5798 mHWData->mCPUAttached[aCpu] = true;
5799
5800 /* Save settings if online */
5801 if (Global::IsOnline(mData->mMachineState))
5802 saveSettings(NULL);
5803
5804 return S_OK;
5805}
5806
5807STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5808{
5809 HRESULT rc = S_OK;
5810 LogFlowThisFunc(("\n"));
5811
5812 AutoCaller autoCaller(this);
5813 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5814
5815 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5816
5817 if (!mHWData->mCPUHotPlugEnabled)
5818 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5819
5820 if (aCpu >= SchemaDefs::MaxCPUCount)
5821 return setError(E_INVALIDARG,
5822 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5823 SchemaDefs::MaxCPUCount);
5824
5825 if (!mHWData->mCPUAttached[aCpu])
5826 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5827
5828 /* CPU 0 can't be detached */
5829 if (aCpu == 0)
5830 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5831
5832 alock.release();
5833 rc = onCPUChange(aCpu, true);
5834 alock.acquire();
5835 if (FAILED(rc)) return rc;
5836
5837 setModified(IsModified_MachineData);
5838 mHWData.backup();
5839 mHWData->mCPUAttached[aCpu] = false;
5840
5841 /* Save settings if online */
5842 if (Global::IsOnline(mData->mMachineState))
5843 saveSettings(NULL);
5844
5845 return S_OK;
5846}
5847
5848STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5849{
5850 LogFlowThisFunc(("\n"));
5851
5852 CheckComArgNotNull(aCpuAttached);
5853
5854 *aCpuAttached = false;
5855
5856 AutoCaller autoCaller(this);
5857 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5858
5859 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5860
5861 /* If hotplug is enabled the CPU is always enabled. */
5862 if (!mHWData->mCPUHotPlugEnabled)
5863 {
5864 if (aCpu < mHWData->mCPUCount)
5865 *aCpuAttached = true;
5866 }
5867 else
5868 {
5869 if (aCpu < SchemaDefs::MaxCPUCount)
5870 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5871 }
5872
5873 return S_OK;
5874}
5875
5876STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5877{
5878 CheckComArgOutPointerValid(aName);
5879
5880 AutoCaller autoCaller(this);
5881 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5882
5883 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5884
5885 Utf8Str log = queryLogFilename(aIdx);
5886 if (!RTFileExists(log.c_str()))
5887 log.setNull();
5888 log.cloneTo(aName);
5889
5890 return S_OK;
5891}
5892
5893STDMETHODIMP Machine::ReadLog(ULONG aIdx, LONG64 aOffset, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
5894{
5895 LogFlowThisFunc(("\n"));
5896 CheckComArgOutSafeArrayPointerValid(aData);
5897 if (aSize < 0)
5898 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
5899
5900 AutoCaller autoCaller(this);
5901 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5902
5903 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5904
5905 HRESULT rc = S_OK;
5906 Utf8Str log = queryLogFilename(aIdx);
5907
5908 /* do not unnecessarily hold the lock while doing something which does
5909 * not need the lock and potentially takes a long time. */
5910 alock.release();
5911
5912 /* Limit the chunk size to 32K for now, as that gives better performance
5913 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5914 * One byte expands to approx. 25 bytes of breathtaking XML. */
5915 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5916 com::SafeArray<BYTE> logData(cbData);
5917
5918 RTFILE LogFile;
5919 int vrc = RTFileOpen(&LogFile, log.c_str(),
5920 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5921 if (RT_SUCCESS(vrc))
5922 {
5923 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5924 if (RT_SUCCESS(vrc))
5925 logData.resize(cbData);
5926 else
5927 rc = setError(VBOX_E_IPRT_ERROR,
5928 tr("Could not read log file '%s' (%Rrc)"),
5929 log.c_str(), vrc);
5930 RTFileClose(LogFile);
5931 }
5932 else
5933 rc = setError(VBOX_E_IPRT_ERROR,
5934 tr("Could not open log file '%s' (%Rrc)"),
5935 log.c_str(), vrc);
5936
5937 if (FAILED(rc))
5938 logData.resize(0);
5939 logData.detachTo(ComSafeArrayOutArg(aData));
5940
5941 return rc;
5942}
5943
5944
5945/**
5946 * Currently this method doesn't attach device to the running VM,
5947 * just makes sure it's plugged on next VM start.
5948 */
5949STDMETHODIMP Machine::AttachHostPciDevice(LONG hostAddress, LONG desiredGuestAddress, BOOL /*tryToUnbind*/)
5950{
5951 AutoCaller autoCaller(this);
5952 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5953
5954 // lock scope
5955 {
5956 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5957
5958 HRESULT rc = checkStateDependency(MutableStateDep);
5959 if (FAILED(rc)) return rc;
5960
5961 ChipsetType_T aChipset = ChipsetType_PIIX3;
5962 COMGETTER(ChipsetType)(&aChipset);
5963
5964 if (aChipset != ChipsetType_ICH9)
5965 {
5966 return setError(E_INVALIDARG,
5967 tr("Host PCI attachment only supported with ICH9 chipset"));
5968 }
5969
5970 // check if device with this host PCI address already attached
5971 for (HWData::PciDeviceAssignmentList::iterator it = mHWData->mPciDeviceAssignments.begin();
5972 it != mHWData->mPciDeviceAssignments.end();
5973 ++it)
5974 {
5975 LONG iHostAddress = -1;
5976 ComPtr<PciDeviceAttachment> pAttach;
5977 pAttach = *it;
5978 pAttach->COMGETTER(HostAddress)(&iHostAddress);
5979 if (iHostAddress == hostAddress)
5980 return setError(E_INVALIDARG,
5981 tr("Device with host PCI address already attached to this VM"));
5982 }
5983
5984 ComObjPtr<PciDeviceAttachment> pda;
5985 char name[32];
5986
5987 RTStrPrintf(name, sizeof(name), "host%02x:%02x.%x", (hostAddress>>8) & 0xff, (hostAddress & 0xf8) >> 3, hostAddress & 7);
5988 Bstr bname(name);
5989 pda.createObject();
5990 pda->init(this, bname, hostAddress, desiredGuestAddress, TRUE);
5991 setModified(IsModified_MachineData);
5992 mHWData.backup();
5993 mHWData->mPciDeviceAssignments.push_back(pda);
5994 }
5995
5996 return S_OK;
5997}
5998
5999/**
6000 * Currently this method doesn't detach device from the running VM,
6001 * just makes sure it's not plugged on next VM start.
6002 */
6003STDMETHODIMP Machine::DetachHostPciDevice(LONG hostAddress)
6004{
6005 AutoCaller autoCaller(this);
6006 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6007
6008 ComObjPtr<PciDeviceAttachment> pAttach;
6009 bool fRemoved = false;
6010 HRESULT rc;
6011
6012 // lock scope
6013 {
6014 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6015
6016 rc = checkStateDependency(MutableStateDep);
6017 if (FAILED(rc)) return rc;
6018
6019 for (HWData::PciDeviceAssignmentList::iterator it = mHWData->mPciDeviceAssignments.begin();
6020 it != mHWData->mPciDeviceAssignments.end();
6021 ++it)
6022 {
6023 LONG iHostAddress = -1;
6024 pAttach = *it;
6025 pAttach->COMGETTER(HostAddress)(&iHostAddress);
6026 if (iHostAddress != -1 && iHostAddress == hostAddress)
6027 {
6028 setModified(IsModified_MachineData);
6029 mHWData.backup();
6030 mHWData->mPciDeviceAssignments.remove(pAttach);
6031 fRemoved = true;
6032 break;
6033 }
6034 }
6035 }
6036
6037
6038 /* Fire event outside of the lock */
6039 if (fRemoved)
6040 {
6041 Assert(!pAttach.isNull());
6042 ComPtr<IEventSource> es;
6043 rc = mParent->COMGETTER(EventSource)(es.asOutParam());
6044 Assert(SUCCEEDED(rc));
6045 Bstr mid;
6046 rc = this->COMGETTER(Id)(mid.asOutParam());
6047 Assert(SUCCEEDED(rc));
6048 fireHostPciDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
6049 }
6050
6051 return fRemoved ? S_OK : setError(VBOX_E_OBJECT_NOT_FOUND,
6052 tr("No host PCI device %08x attached"),
6053 hostAddress
6054 );
6055}
6056
6057STDMETHODIMP Machine::COMGETTER(PciDeviceAssignments)(ComSafeArrayOut(IPciDeviceAttachment *, aAssignments))
6058{
6059 CheckComArgOutSafeArrayPointerValid(aAssignments);
6060
6061 AutoCaller autoCaller(this);
6062 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6063
6064 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6065
6066 SafeIfaceArray<IPciDeviceAttachment> assignments(mHWData->mPciDeviceAssignments);
6067 assignments.detachTo(ComSafeArrayOutArg(aAssignments));
6068
6069 return S_OK;
6070}
6071
6072STDMETHODIMP Machine::COMGETTER(BandwidthControl)(IBandwidthControl **aBandwidthControl)
6073{
6074 CheckComArgOutPointerValid(aBandwidthControl);
6075
6076 AutoCaller autoCaller(this);
6077 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6078
6079 mBandwidthControl.queryInterfaceTo(aBandwidthControl);
6080
6081 return S_OK;
6082}
6083
6084STDMETHODIMP Machine::CloneTo(IMachine *pTarget, CloneMode_T mode, ComSafeArrayIn(CloneOptions_T, options), IProgress **pProgress)
6085{
6086 LogFlowFuncEnter();
6087
6088 CheckComArgNotNull(pTarget);
6089 CheckComArgOutPointerValid(pProgress);
6090
6091 /* Convert the options. */
6092 RTCList<CloneOptions_T> optList;
6093 if (options != NULL)
6094 optList = com::SafeArray<CloneOptions_T>(ComSafeArrayInArg(options)).toList();
6095
6096 AssertReturn(!optList.contains(CloneOptions_Link), E_NOTIMPL);
6097 AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_FAIL);
6098
6099 AutoCaller autoCaller(this);
6100 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6101
6102 MachineCloneVM *pWorker = new MachineCloneVM(this, static_cast<Machine*>(pTarget), mode, optList);
6103
6104 HRESULT rc = pWorker->start(pProgress);
6105
6106 LogFlowFuncLeave();
6107
6108 return rc;
6109}
6110
6111// public methods for internal purposes
6112/////////////////////////////////////////////////////////////////////////////
6113
6114/**
6115 * Adds the given IsModified_* flag to the dirty flags of the machine.
6116 * This must be called either during loadSettings or under the machine write lock.
6117 * @param fl
6118 */
6119void Machine::setModified(uint32_t fl)
6120{
6121 mData->flModifications |= fl;
6122}
6123
6124/**
6125 * Adds the given IsModified_* flag to the dirty flags of the machine, taking
6126 * care of the write locking.
6127 *
6128 * @param fModifications The flag to add.
6129 */
6130void Machine::setModifiedLock(uint32_t fModification)
6131{
6132 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6133 mData->flModifications |= fModification;
6134}
6135
6136/**
6137 * Saves the registry entry of this machine to the given configuration node.
6138 *
6139 * @param aEntryNode Node to save the registry entry to.
6140 *
6141 * @note locks this object for reading.
6142 */
6143HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
6144{
6145 AutoLimitedCaller autoCaller(this);
6146 AssertComRCReturnRC(autoCaller.rc());
6147
6148 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6149
6150 data.uuid = mData->mUuid;
6151 data.strSettingsFile = mData->m_strConfigFile;
6152
6153 return S_OK;
6154}
6155
6156/**
6157 * Calculates the absolute path of the given path taking the directory of the
6158 * machine settings file as the current directory.
6159 *
6160 * @param aPath Path to calculate the absolute path for.
6161 * @param aResult Where to put the result (used only on success, can be the
6162 * same Utf8Str instance as passed in @a aPath).
6163 * @return IPRT result.
6164 *
6165 * @note Locks this object for reading.
6166 */
6167int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
6168{
6169 AutoCaller autoCaller(this);
6170 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6171
6172 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6173
6174 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
6175
6176 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
6177
6178 strSettingsDir.stripFilename();
6179 char folder[RTPATH_MAX];
6180 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
6181 if (RT_SUCCESS(vrc))
6182 aResult = folder;
6183
6184 return vrc;
6185}
6186
6187/**
6188 * Copies strSource to strTarget, making it relative to the machine folder
6189 * if it is a subdirectory thereof, or simply copying it otherwise.
6190 *
6191 * @param strSource Path to evaluate and copy.
6192 * @param strTarget Buffer to receive target path.
6193 *
6194 * @note Locks this object for reading.
6195 */
6196void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
6197 Utf8Str &strTarget)
6198{
6199 AutoCaller autoCaller(this);
6200 AssertComRCReturn(autoCaller.rc(), (void)0);
6201
6202 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6203
6204 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
6205 // use strTarget as a temporary buffer to hold the machine settings dir
6206 strTarget = mData->m_strConfigFileFull;
6207 strTarget.stripFilename();
6208 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
6209 {
6210 // is relative: then append what's left
6211 strTarget = strSource.substr(strTarget.length() + 1); // skip '/'
6212 // for empty paths (only possible for subdirs) use "." to avoid
6213 // triggering default settings for not present config attributes.
6214 if (strTarget.isEmpty())
6215 strTarget = ".";
6216 }
6217 else
6218 // is not relative: then overwrite
6219 strTarget = strSource;
6220}
6221
6222/**
6223 * Returns the full path to the machine's log folder in the
6224 * \a aLogFolder argument.
6225 */
6226void Machine::getLogFolder(Utf8Str &aLogFolder)
6227{
6228 AutoCaller autoCaller(this);
6229 AssertComRCReturnVoid(autoCaller.rc());
6230
6231 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6232
6233 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6234 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6235 aLogFolder.append(RTPATH_DELIMITER);
6236 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6237}
6238
6239/**
6240 * Returns the full path to the machine's log file for an given index.
6241 */
6242Utf8Str Machine::queryLogFilename(ULONG idx)
6243{
6244 Utf8Str logFolder;
6245 getLogFolder(logFolder);
6246 Assert(logFolder.length());
6247 Utf8Str log;
6248 if (idx == 0)
6249 log = Utf8StrFmt("%s%cVBox.log",
6250 logFolder.c_str(), RTPATH_DELIMITER);
6251 else
6252 log = Utf8StrFmt("%s%cVBox.log.%d",
6253 logFolder.c_str(), RTPATH_DELIMITER, idx);
6254 return log;
6255}
6256
6257/**
6258 * Composes a unique saved state filename based on the current system time. The filename is
6259 * granular to the second so this will work so long as no more than one snapshot is taken on
6260 * a machine per second.
6261 *
6262 * Before version 4.1, we used this formula for saved state files:
6263 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6264 * which no longer works because saved state files can now be shared between the saved state of the
6265 * "saved" machine and an online snapshot, and the following would cause problems:
6266 * 1) save machine
6267 * 2) create online snapshot from that machine state --> reusing saved state file
6268 * 3) save machine again --> filename would be reused, breaking the online snapshot
6269 *
6270 * So instead we now use a timestamp.
6271 *
6272 * @param str
6273 */
6274void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6275{
6276 AutoCaller autoCaller(this);
6277 AssertComRCReturnVoid(autoCaller.rc());
6278
6279 {
6280 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6281 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6282 }
6283
6284 RTTIMESPEC ts;
6285 RTTimeNow(&ts);
6286 RTTIME time;
6287 RTTimeExplode(&time, &ts);
6288
6289 strStateFilePath += RTPATH_DELIMITER;
6290 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
6291 time.i32Year, time.u8Month, time.u8MonthDay,
6292 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
6293}
6294
6295/**
6296 * @note Locks this object for writing, calls the client process
6297 * (inside the lock).
6298 */
6299HRESULT Machine::launchVMProcess(IInternalSessionControl *aControl,
6300 const Utf8Str &strType,
6301 const Utf8Str &strEnvironment,
6302 ProgressProxy *aProgress)
6303{
6304 LogFlowThisFuncEnter();
6305
6306 AssertReturn(aControl, E_FAIL);
6307 AssertReturn(aProgress, E_FAIL);
6308
6309 AutoCaller autoCaller(this);
6310 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6311
6312 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6313
6314 if (!mData->mRegistered)
6315 return setError(E_UNEXPECTED,
6316 tr("The machine '%s' is not registered"),
6317 mUserData->s.strName.c_str());
6318
6319 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6320
6321 if ( mData->mSession.mState == SessionState_Locked
6322 || mData->mSession.mState == SessionState_Spawning
6323 || mData->mSession.mState == SessionState_Unlocking)
6324 return setError(VBOX_E_INVALID_OBJECT_STATE,
6325 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6326 mUserData->s.strName.c_str());
6327
6328 /* may not be busy */
6329 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6330
6331 /* get the path to the executable */
6332 char szPath[RTPATH_MAX];
6333 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6334 size_t sz = strlen(szPath);
6335 szPath[sz++] = RTPATH_DELIMITER;
6336 szPath[sz] = 0;
6337 char *cmd = szPath + sz;
6338 sz = RTPATH_MAX - sz;
6339
6340 int vrc = VINF_SUCCESS;
6341 RTPROCESS pid = NIL_RTPROCESS;
6342
6343 RTENV env = RTENV_DEFAULT;
6344
6345 if (!strEnvironment.isEmpty())
6346 {
6347 char *newEnvStr = NULL;
6348
6349 do
6350 {
6351 /* clone the current environment */
6352 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6353 AssertRCBreakStmt(vrc2, vrc = vrc2);
6354
6355 newEnvStr = RTStrDup(strEnvironment.c_str());
6356 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6357
6358 /* put new variables to the environment
6359 * (ignore empty variable names here since RTEnv API
6360 * intentionally doesn't do that) */
6361 char *var = newEnvStr;
6362 for (char *p = newEnvStr; *p; ++p)
6363 {
6364 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6365 {
6366 *p = '\0';
6367 if (*var)
6368 {
6369 char *val = strchr(var, '=');
6370 if (val)
6371 {
6372 *val++ = '\0';
6373 vrc2 = RTEnvSetEx(env, var, val);
6374 }
6375 else
6376 vrc2 = RTEnvUnsetEx(env, var);
6377 if (RT_FAILURE(vrc2))
6378 break;
6379 }
6380 var = p + 1;
6381 }
6382 }
6383 if (RT_SUCCESS(vrc2) && *var)
6384 vrc2 = RTEnvPutEx(env, var);
6385
6386 AssertRCBreakStmt(vrc2, vrc = vrc2);
6387 }
6388 while (0);
6389
6390 if (newEnvStr != NULL)
6391 RTStrFree(newEnvStr);
6392 }
6393
6394 /* Qt is default */
6395#ifdef VBOX_WITH_QTGUI
6396 if (strType == "gui" || strType == "GUI/Qt")
6397 {
6398# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6399 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6400# else
6401 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6402# endif
6403 Assert(sz >= sizeof(VirtualBox_exe));
6404 strcpy(cmd, VirtualBox_exe);
6405
6406 Utf8Str idStr = mData->mUuid.toString();
6407 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6408 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6409 }
6410#else /* !VBOX_WITH_QTGUI */
6411 if (0)
6412 ;
6413#endif /* VBOX_WITH_QTGUI */
6414
6415 else
6416
6417#ifdef VBOX_WITH_VBOXSDL
6418 if (strType == "sdl" || strType == "GUI/SDL")
6419 {
6420 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6421 Assert(sz >= sizeof(VBoxSDL_exe));
6422 strcpy(cmd, VBoxSDL_exe);
6423
6424 Utf8Str idStr = mData->mUuid.toString();
6425 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6426 fprintf(stderr, "SDL=%s\n", szPath);
6427 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6428 }
6429#else /* !VBOX_WITH_VBOXSDL */
6430 if (0)
6431 ;
6432#endif /* !VBOX_WITH_VBOXSDL */
6433
6434 else
6435
6436#ifdef VBOX_WITH_HEADLESS
6437 if ( strType == "headless"
6438 || strType == "capture"
6439 || strType == "vrdp" /* Deprecated. Same as headless. */
6440 )
6441 {
6442 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6443 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6444 * and a VM works even if the server has not been installed.
6445 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6446 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6447 * differently in 4.0 and 3.x.
6448 */
6449 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6450 Assert(sz >= sizeof(VBoxHeadless_exe));
6451 strcpy(cmd, VBoxHeadless_exe);
6452
6453 Utf8Str idStr = mData->mUuid.toString();
6454 /* Leave space for "--capture" arg. */
6455 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
6456 "--startvm", idStr.c_str(),
6457 "--vrde", "config",
6458 0, /* For "--capture". */
6459 0 };
6460 if (strType == "capture")
6461 {
6462 unsigned pos = RT_ELEMENTS(args) - 2;
6463 args[pos] = "--capture";
6464 }
6465 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6466 }
6467#else /* !VBOX_WITH_HEADLESS */
6468 if (0)
6469 ;
6470#endif /* !VBOX_WITH_HEADLESS */
6471 else
6472 {
6473 RTEnvDestroy(env);
6474 return setError(E_INVALIDARG,
6475 tr("Invalid session type: '%s'"),
6476 strType.c_str());
6477 }
6478
6479 RTEnvDestroy(env);
6480
6481 if (RT_FAILURE(vrc))
6482 return setError(VBOX_E_IPRT_ERROR,
6483 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6484 mUserData->s.strName.c_str(), vrc);
6485
6486 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6487
6488 /*
6489 * Note that we don't leave the lock here before calling the client,
6490 * because it doesn't need to call us back if called with a NULL argument.
6491 * Leaving the lock here is dangerous because we didn't prepare the
6492 * launch data yet, but the client we've just started may happen to be
6493 * too fast and call openSession() that will fail (because of PID, etc.),
6494 * so that the Machine will never get out of the Spawning session state.
6495 */
6496
6497 /* inform the session that it will be a remote one */
6498 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6499 HRESULT rc = aControl->AssignMachine(NULL);
6500 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6501
6502 if (FAILED(rc))
6503 {
6504 /* restore the session state */
6505 mData->mSession.mState = SessionState_Unlocked;
6506 /* The failure may occur w/o any error info (from RPC), so provide one */
6507 return setError(VBOX_E_VM_ERROR,
6508 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6509 }
6510
6511 /* attach launch data to the machine */
6512 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6513 mData->mSession.mRemoteControls.push_back (aControl);
6514 mData->mSession.mProgress = aProgress;
6515 mData->mSession.mPid = pid;
6516 mData->mSession.mState = SessionState_Spawning;
6517 mData->mSession.mType = strType;
6518
6519 LogFlowThisFuncLeave();
6520 return S_OK;
6521}
6522
6523/**
6524 * Returns @c true if the given machine has an open direct session and returns
6525 * the session machine instance and additional session data (on some platforms)
6526 * if so.
6527 *
6528 * Note that when the method returns @c false, the arguments remain unchanged.
6529 *
6530 * @param aMachine Session machine object.
6531 * @param aControl Direct session control object (optional).
6532 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6533 *
6534 * @note locks this object for reading.
6535 */
6536#if defined(RT_OS_WINDOWS)
6537bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6538 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6539 HANDLE *aIPCSem /*= NULL*/,
6540 bool aAllowClosing /*= false*/)
6541#elif defined(RT_OS_OS2)
6542bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6543 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6544 HMTX *aIPCSem /*= NULL*/,
6545 bool aAllowClosing /*= false*/)
6546#else
6547bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6548 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6549 bool aAllowClosing /*= false*/)
6550#endif
6551{
6552 AutoLimitedCaller autoCaller(this);
6553 AssertComRCReturn(autoCaller.rc(), false);
6554
6555 /* just return false for inaccessible machines */
6556 if (autoCaller.state() != Ready)
6557 return false;
6558
6559 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6560
6561 if ( mData->mSession.mState == SessionState_Locked
6562 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6563 )
6564 {
6565 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6566
6567 aMachine = mData->mSession.mMachine;
6568
6569 if (aControl != NULL)
6570 *aControl = mData->mSession.mDirectControl;
6571
6572#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6573 /* Additional session data */
6574 if (aIPCSem != NULL)
6575 *aIPCSem = aMachine->mIPCSem;
6576#endif
6577 return true;
6578 }
6579
6580 return false;
6581}
6582
6583/**
6584 * Returns @c true if the given machine has an spawning direct session and
6585 * returns and additional session data (on some platforms) if so.
6586 *
6587 * Note that when the method returns @c false, the arguments remain unchanged.
6588 *
6589 * @param aPID PID of the spawned direct session process.
6590 *
6591 * @note locks this object for reading.
6592 */
6593#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6594bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6595#else
6596bool Machine::isSessionSpawning()
6597#endif
6598{
6599 AutoLimitedCaller autoCaller(this);
6600 AssertComRCReturn(autoCaller.rc(), false);
6601
6602 /* just return false for inaccessible machines */
6603 if (autoCaller.state() != Ready)
6604 return false;
6605
6606 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6607
6608 if (mData->mSession.mState == SessionState_Spawning)
6609 {
6610#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6611 /* Additional session data */
6612 if (aPID != NULL)
6613 {
6614 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6615 *aPID = mData->mSession.mPid;
6616 }
6617#endif
6618 return true;
6619 }
6620
6621 return false;
6622}
6623
6624/**
6625 * Called from the client watcher thread to check for unexpected client process
6626 * death during Session_Spawning state (e.g. before it successfully opened a
6627 * direct session).
6628 *
6629 * On Win32 and on OS/2, this method is called only when we've got the
6630 * direct client's process termination notification, so it always returns @c
6631 * true.
6632 *
6633 * On other platforms, this method returns @c true if the client process is
6634 * terminated and @c false if it's still alive.
6635 *
6636 * @note Locks this object for writing.
6637 */
6638bool Machine::checkForSpawnFailure()
6639{
6640 AutoCaller autoCaller(this);
6641 if (!autoCaller.isOk())
6642 {
6643 /* nothing to do */
6644 LogFlowThisFunc(("Already uninitialized!\n"));
6645 return true;
6646 }
6647
6648 /* VirtualBox::addProcessToReap() needs a write lock */
6649 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6650
6651 if (mData->mSession.mState != SessionState_Spawning)
6652 {
6653 /* nothing to do */
6654 LogFlowThisFunc(("Not spawning any more!\n"));
6655 return true;
6656 }
6657
6658 HRESULT rc = S_OK;
6659
6660#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6661
6662 /* the process was already unexpectedly terminated, we just need to set an
6663 * error and finalize session spawning */
6664 rc = setError(E_FAIL,
6665 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6666 getName().c_str());
6667#else
6668
6669 /* PID not yet initialized, skip check. */
6670 if (mData->mSession.mPid == NIL_RTPROCESS)
6671 return false;
6672
6673 RTPROCSTATUS status;
6674 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6675 &status);
6676
6677 if (vrc != VERR_PROCESS_RUNNING)
6678 {
6679 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6680 rc = setError(E_FAIL,
6681 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6682 getName().c_str(), status.iStatus);
6683 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6684 rc = setError(E_FAIL,
6685 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6686 getName().c_str(), status.iStatus);
6687 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6688 rc = setError(E_FAIL,
6689 tr("The virtual machine '%s' has terminated abnormally"),
6690 getName().c_str(), status.iStatus);
6691 else
6692 rc = setError(E_FAIL,
6693 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6694 getName().c_str(), rc);
6695 }
6696
6697#endif
6698
6699 if (FAILED(rc))
6700 {
6701 /* Close the remote session, remove the remote control from the list
6702 * and reset session state to Closed (@note keep the code in sync with
6703 * the relevant part in checkForSpawnFailure()). */
6704
6705 Assert(mData->mSession.mRemoteControls.size() == 1);
6706 if (mData->mSession.mRemoteControls.size() == 1)
6707 {
6708 ErrorInfoKeeper eik;
6709 mData->mSession.mRemoteControls.front()->Uninitialize();
6710 }
6711
6712 mData->mSession.mRemoteControls.clear();
6713 mData->mSession.mState = SessionState_Unlocked;
6714
6715 /* finalize the progress after setting the state */
6716 if (!mData->mSession.mProgress.isNull())
6717 {
6718 mData->mSession.mProgress->notifyComplete(rc);
6719 mData->mSession.mProgress.setNull();
6720 }
6721
6722 mParent->addProcessToReap(mData->mSession.mPid);
6723 mData->mSession.mPid = NIL_RTPROCESS;
6724
6725 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6726 return true;
6727 }
6728
6729 return false;
6730}
6731
6732/**
6733 * Checks whether the machine can be registered. If so, commits and saves
6734 * all settings.
6735 *
6736 * @note Must be called from mParent's write lock. Locks this object and
6737 * children for writing.
6738 */
6739HRESULT Machine::prepareRegister()
6740{
6741 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6742
6743 AutoLimitedCaller autoCaller(this);
6744 AssertComRCReturnRC(autoCaller.rc());
6745
6746 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6747
6748 /* wait for state dependents to drop to zero */
6749 ensureNoStateDependencies();
6750
6751 if (!mData->mAccessible)
6752 return setError(VBOX_E_INVALID_OBJECT_STATE,
6753 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
6754 mUserData->s.strName.c_str(),
6755 mData->mUuid.toString().c_str());
6756
6757 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6758
6759 if (mData->mRegistered)
6760 return setError(VBOX_E_INVALID_OBJECT_STATE,
6761 tr("The machine '%s' with UUID {%s} is already registered"),
6762 mUserData->s.strName.c_str(),
6763 mData->mUuid.toString().c_str());
6764
6765 HRESULT rc = S_OK;
6766
6767 // Ensure the settings are saved. If we are going to be registered and
6768 // no config file exists yet, create it by calling saveSettings() too.
6769 if ( (mData->flModifications)
6770 || (!mData->pMachineConfigFile->fileExists())
6771 )
6772 {
6773 rc = saveSettings(NULL);
6774 // no need to check whether VirtualBox.xml needs saving too since
6775 // we can't have a machine XML file rename pending
6776 if (FAILED(rc)) return rc;
6777 }
6778
6779 /* more config checking goes here */
6780
6781 if (SUCCEEDED(rc))
6782 {
6783 /* we may have had implicit modifications we want to fix on success */
6784 commit();
6785
6786 mData->mRegistered = true;
6787 }
6788 else
6789 {
6790 /* we may have had implicit modifications we want to cancel on failure*/
6791 rollback(false /* aNotify */);
6792 }
6793
6794 return rc;
6795}
6796
6797/**
6798 * Increases the number of objects dependent on the machine state or on the
6799 * registered state. Guarantees that these two states will not change at least
6800 * until #releaseStateDependency() is called.
6801 *
6802 * Depending on the @a aDepType value, additional state checks may be made.
6803 * These checks will set extended error info on failure. See
6804 * #checkStateDependency() for more info.
6805 *
6806 * If this method returns a failure, the dependency is not added and the caller
6807 * is not allowed to rely on any particular machine state or registration state
6808 * value and may return the failed result code to the upper level.
6809 *
6810 * @param aDepType Dependency type to add.
6811 * @param aState Current machine state (NULL if not interested).
6812 * @param aRegistered Current registered state (NULL if not interested).
6813 *
6814 * @note Locks this object for writing.
6815 */
6816HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6817 MachineState_T *aState /* = NULL */,
6818 BOOL *aRegistered /* = NULL */)
6819{
6820 AutoCaller autoCaller(this);
6821 AssertComRCReturnRC(autoCaller.rc());
6822
6823 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6824
6825 HRESULT rc = checkStateDependency(aDepType);
6826 if (FAILED(rc)) return rc;
6827
6828 {
6829 if (mData->mMachineStateChangePending != 0)
6830 {
6831 /* ensureNoStateDependencies() is waiting for state dependencies to
6832 * drop to zero so don't add more. It may make sense to wait a bit
6833 * and retry before reporting an error (since the pending state
6834 * transition should be really quick) but let's just assert for
6835 * now to see if it ever happens on practice. */
6836
6837 AssertFailed();
6838
6839 return setError(E_ACCESSDENIED,
6840 tr("Machine state change is in progress. Please retry the operation later."));
6841 }
6842
6843 ++mData->mMachineStateDeps;
6844 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6845 }
6846
6847 if (aState)
6848 *aState = mData->mMachineState;
6849 if (aRegistered)
6850 *aRegistered = mData->mRegistered;
6851
6852 return S_OK;
6853}
6854
6855/**
6856 * Decreases the number of objects dependent on the machine state.
6857 * Must always complete the #addStateDependency() call after the state
6858 * dependency is no more necessary.
6859 */
6860void Machine::releaseStateDependency()
6861{
6862 AutoCaller autoCaller(this);
6863 AssertComRCReturnVoid(autoCaller.rc());
6864
6865 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6866
6867 /* releaseStateDependency() w/o addStateDependency()? */
6868 AssertReturnVoid(mData->mMachineStateDeps != 0);
6869 -- mData->mMachineStateDeps;
6870
6871 if (mData->mMachineStateDeps == 0)
6872 {
6873 /* inform ensureNoStateDependencies() that there are no more deps */
6874 if (mData->mMachineStateChangePending != 0)
6875 {
6876 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6877 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6878 }
6879 }
6880}
6881
6882// protected methods
6883/////////////////////////////////////////////////////////////////////////////
6884
6885/**
6886 * Performs machine state checks based on the @a aDepType value. If a check
6887 * fails, this method will set extended error info, otherwise it will return
6888 * S_OK. It is supposed, that on failure, the caller will immediately return
6889 * the return value of this method to the upper level.
6890 *
6891 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6892 *
6893 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6894 * current state of this machine object allows to change settings of the
6895 * machine (i.e. the machine is not registered, or registered but not running
6896 * and not saved). It is useful to call this method from Machine setters
6897 * before performing any change.
6898 *
6899 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6900 * as for MutableStateDep except that if the machine is saved, S_OK is also
6901 * returned. This is useful in setters which allow changing machine
6902 * properties when it is in the saved state.
6903 *
6904 * @param aDepType Dependency type to check.
6905 *
6906 * @note Non Machine based classes should use #addStateDependency() and
6907 * #releaseStateDependency() methods or the smart AutoStateDependency
6908 * template.
6909 *
6910 * @note This method must be called from under this object's read or write
6911 * lock.
6912 */
6913HRESULT Machine::checkStateDependency(StateDependency aDepType)
6914{
6915 switch (aDepType)
6916 {
6917 case AnyStateDep:
6918 {
6919 break;
6920 }
6921 case MutableStateDep:
6922 {
6923 if ( mData->mRegistered
6924 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6925 || ( mData->mMachineState != MachineState_Paused
6926 && mData->mMachineState != MachineState_Running
6927 && mData->mMachineState != MachineState_Aborted
6928 && mData->mMachineState != MachineState_Teleported
6929 && mData->mMachineState != MachineState_PoweredOff
6930 )
6931 )
6932 )
6933 return setError(VBOX_E_INVALID_VM_STATE,
6934 tr("The machine is not mutable (state is %s)"),
6935 Global::stringifyMachineState(mData->mMachineState));
6936 break;
6937 }
6938 case MutableOrSavedStateDep:
6939 {
6940 if ( mData->mRegistered
6941 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
6942 || ( mData->mMachineState != MachineState_Paused
6943 && mData->mMachineState != MachineState_Running
6944 && mData->mMachineState != MachineState_Aborted
6945 && mData->mMachineState != MachineState_Teleported
6946 && mData->mMachineState != MachineState_Saved
6947 && mData->mMachineState != MachineState_PoweredOff
6948 )
6949 )
6950 )
6951 return setError(VBOX_E_INVALID_VM_STATE,
6952 tr("The machine is not mutable (state is %s)"),
6953 Global::stringifyMachineState(mData->mMachineState));
6954 break;
6955 }
6956 }
6957
6958 return S_OK;
6959}
6960
6961/**
6962 * Helper to initialize all associated child objects and allocate data
6963 * structures.
6964 *
6965 * This method must be called as a part of the object's initialization procedure
6966 * (usually done in the #init() method).
6967 *
6968 * @note Must be called only from #init() or from #registeredInit().
6969 */
6970HRESULT Machine::initDataAndChildObjects()
6971{
6972 AutoCaller autoCaller(this);
6973 AssertComRCReturnRC(autoCaller.rc());
6974 AssertComRCReturn(autoCaller.state() == InInit ||
6975 autoCaller.state() == Limited, E_FAIL);
6976
6977 AssertReturn(!mData->mAccessible, E_FAIL);
6978
6979 /* allocate data structures */
6980 mSSData.allocate();
6981 mUserData.allocate();
6982 mHWData.allocate();
6983 mMediaData.allocate();
6984 mStorageControllers.allocate();
6985
6986 /* initialize mOSTypeId */
6987 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
6988
6989 /* create associated BIOS settings object */
6990 unconst(mBIOSSettings).createObject();
6991 mBIOSSettings->init(this);
6992
6993 /* create an associated VRDE object (default is disabled) */
6994 unconst(mVRDEServer).createObject();
6995 mVRDEServer->init(this);
6996
6997 /* create associated serial port objects */
6998 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6999 {
7000 unconst(mSerialPorts[slot]).createObject();
7001 mSerialPorts[slot]->init(this, slot);
7002 }
7003
7004 /* create associated parallel port objects */
7005 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7006 {
7007 unconst(mParallelPorts[slot]).createObject();
7008 mParallelPorts[slot]->init(this, slot);
7009 }
7010
7011 /* create the audio adapter object (always present, default is disabled) */
7012 unconst(mAudioAdapter).createObject();
7013 mAudioAdapter->init(this);
7014
7015 /* create the USB controller object (always present, default is disabled) */
7016 unconst(mUSBController).createObject();
7017 mUSBController->init(this);
7018
7019 /* create associated network adapter objects */
7020 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
7021 {
7022 unconst(mNetworkAdapters[slot]).createObject();
7023 mNetworkAdapters[slot]->init(this, slot);
7024 }
7025
7026 /* create the bandwidth control */
7027 unconst(mBandwidthControl).createObject();
7028 mBandwidthControl->init(this);
7029
7030 return S_OK;
7031}
7032
7033/**
7034 * Helper to uninitialize all associated child objects and to free all data
7035 * structures.
7036 *
7037 * This method must be called as a part of the object's uninitialization
7038 * procedure (usually done in the #uninit() method).
7039 *
7040 * @note Must be called only from #uninit() or from #registeredInit().
7041 */
7042void Machine::uninitDataAndChildObjects()
7043{
7044 AutoCaller autoCaller(this);
7045 AssertComRCReturnVoid(autoCaller.rc());
7046 AssertComRCReturnVoid( autoCaller.state() == InUninit
7047 || autoCaller.state() == Limited);
7048
7049 /* tell all our other child objects we've been uninitialized */
7050 if (mBandwidthControl)
7051 {
7052 mBandwidthControl->uninit();
7053 unconst(mBandwidthControl).setNull();
7054 }
7055
7056 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
7057 {
7058 if (mNetworkAdapters[slot])
7059 {
7060 mNetworkAdapters[slot]->uninit();
7061 unconst(mNetworkAdapters[slot]).setNull();
7062 }
7063 }
7064
7065 if (mUSBController)
7066 {
7067 mUSBController->uninit();
7068 unconst(mUSBController).setNull();
7069 }
7070
7071 if (mAudioAdapter)
7072 {
7073 mAudioAdapter->uninit();
7074 unconst(mAudioAdapter).setNull();
7075 }
7076
7077 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7078 {
7079 if (mParallelPorts[slot])
7080 {
7081 mParallelPorts[slot]->uninit();
7082 unconst(mParallelPorts[slot]).setNull();
7083 }
7084 }
7085
7086 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7087 {
7088 if (mSerialPorts[slot])
7089 {
7090 mSerialPorts[slot]->uninit();
7091 unconst(mSerialPorts[slot]).setNull();
7092 }
7093 }
7094
7095 if (mVRDEServer)
7096 {
7097 mVRDEServer->uninit();
7098 unconst(mVRDEServer).setNull();
7099 }
7100
7101 if (mBIOSSettings)
7102 {
7103 mBIOSSettings->uninit();
7104 unconst(mBIOSSettings).setNull();
7105 }
7106
7107 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
7108 * instance is uninitialized; SessionMachine instances refer to real
7109 * Machine hard disks). This is necessary for a clean re-initialization of
7110 * the VM after successfully re-checking the accessibility state. Note
7111 * that in case of normal Machine or SnapshotMachine uninitialization (as
7112 * a result of unregistering or deleting the snapshot), outdated hard
7113 * disk attachments will already be uninitialized and deleted, so this
7114 * code will not affect them. */
7115 if ( !!mMediaData
7116 && (!isSessionMachine())
7117 )
7118 {
7119 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7120 it != mMediaData->mAttachments.end();
7121 ++it)
7122 {
7123 ComObjPtr<Medium> hd = (*it)->getMedium();
7124 if (hd.isNull())
7125 continue;
7126 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
7127 AssertComRC(rc);
7128 }
7129 }
7130
7131 if (!isSessionMachine() && !isSnapshotMachine())
7132 {
7133 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
7134 if (mData->mFirstSnapshot)
7135 {
7136 // snapshots tree is protected by media write lock; strictly
7137 // this isn't necessary here since we're deleting the entire
7138 // machine, but otherwise we assert in Snapshot::uninit()
7139 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7140 mData->mFirstSnapshot->uninit();
7141 mData->mFirstSnapshot.setNull();
7142 }
7143
7144 mData->mCurrentSnapshot.setNull();
7145 }
7146
7147 /* free data structures (the essential mData structure is not freed here
7148 * since it may be still in use) */
7149 mMediaData.free();
7150 mStorageControllers.free();
7151 mHWData.free();
7152 mUserData.free();
7153 mSSData.free();
7154}
7155
7156/**
7157 * Returns a pointer to the Machine object for this machine that acts like a
7158 * parent for complex machine data objects such as shared folders, etc.
7159 *
7160 * For primary Machine objects and for SnapshotMachine objects, returns this
7161 * object's pointer itself. For SessionMachine objects, returns the peer
7162 * (primary) machine pointer.
7163 */
7164Machine* Machine::getMachine()
7165{
7166 if (isSessionMachine())
7167 return (Machine*)mPeer;
7168 return this;
7169}
7170
7171/**
7172 * Makes sure that there are no machine state dependents. If necessary, waits
7173 * for the number of dependents to drop to zero.
7174 *
7175 * Make sure this method is called from under this object's write lock to
7176 * guarantee that no new dependents may be added when this method returns
7177 * control to the caller.
7178 *
7179 * @note Locks this object for writing. The lock will be released while waiting
7180 * (if necessary).
7181 *
7182 * @warning To be used only in methods that change the machine state!
7183 */
7184void Machine::ensureNoStateDependencies()
7185{
7186 AssertReturnVoid(isWriteLockOnCurrentThread());
7187
7188 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7189
7190 /* Wait for all state dependents if necessary */
7191 if (mData->mMachineStateDeps != 0)
7192 {
7193 /* lazy semaphore creation */
7194 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
7195 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
7196
7197 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
7198 mData->mMachineStateDeps));
7199
7200 ++mData->mMachineStateChangePending;
7201
7202 /* reset the semaphore before waiting, the last dependent will signal
7203 * it */
7204 RTSemEventMultiReset(mData->mMachineStateDepsSem);
7205
7206 alock.leave();
7207
7208 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
7209
7210 alock.enter();
7211
7212 -- mData->mMachineStateChangePending;
7213 }
7214}
7215
7216/**
7217 * Changes the machine state and informs callbacks.
7218 *
7219 * This method is not intended to fail so it either returns S_OK or asserts (and
7220 * returns a failure).
7221 *
7222 * @note Locks this object for writing.
7223 */
7224HRESULT Machine::setMachineState(MachineState_T aMachineState)
7225{
7226 LogFlowThisFuncEnter();
7227 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
7228
7229 AutoCaller autoCaller(this);
7230 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7231
7232 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7233
7234 /* wait for state dependents to drop to zero */
7235 ensureNoStateDependencies();
7236
7237 if (mData->mMachineState != aMachineState)
7238 {
7239 mData->mMachineState = aMachineState;
7240
7241 RTTimeNow(&mData->mLastStateChange);
7242
7243 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7244 }
7245
7246 LogFlowThisFuncLeave();
7247 return S_OK;
7248}
7249
7250/**
7251 * Searches for a shared folder with the given logical name
7252 * in the collection of shared folders.
7253 *
7254 * @param aName logical name of the shared folder
7255 * @param aSharedFolder where to return the found object
7256 * @param aSetError whether to set the error info if the folder is
7257 * not found
7258 * @return
7259 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7260 *
7261 * @note
7262 * must be called from under the object's lock!
7263 */
7264HRESULT Machine::findSharedFolder(const Utf8Str &aName,
7265 ComObjPtr<SharedFolder> &aSharedFolder,
7266 bool aSetError /* = false */)
7267{
7268 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
7269 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7270 it != mHWData->mSharedFolders.end();
7271 ++it)
7272 {
7273 SharedFolder *pSF = *it;
7274 AutoCaller autoCaller(pSF);
7275 if (pSF->getName() == aName)
7276 {
7277 aSharedFolder = pSF;
7278 rc = S_OK;
7279 break;
7280 }
7281 }
7282
7283 if (aSetError && FAILED(rc))
7284 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
7285
7286 return rc;
7287}
7288
7289/**
7290 * Initializes all machine instance data from the given settings structures
7291 * from XML. The exception is the machine UUID which needs special handling
7292 * depending on the caller's use case, so the caller needs to set that herself.
7293 *
7294 * This gets called in several contexts during machine initialization:
7295 *
7296 * -- When machine XML exists on disk already and needs to be loaded into memory,
7297 * for example, from registeredInit() to load all registered machines on
7298 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7299 * attached to the machine should be part of some media registry already.
7300 *
7301 * -- During OVF import, when a machine config has been constructed from an
7302 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7303 * ensure that the media listed as attachments in the config (which have
7304 * been imported from the OVF) receive the correct registry ID.
7305 *
7306 * -- During VM cloning.
7307 *
7308 * @param config Machine settings from XML.
7309 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7310 * @return
7311 */
7312HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7313 const Guid *puuidRegistry)
7314{
7315 // copy name, description, OS type, teleporter, UTC etc.
7316 mUserData->s = config.machineUserData;
7317
7318 // look up the object by Id to check it is valid
7319 ComPtr<IGuestOSType> guestOSType;
7320 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7321 guestOSType.asOutParam());
7322 if (FAILED(rc)) return rc;
7323
7324 // stateFile (optional)
7325 if (config.strStateFile.isEmpty())
7326 mSSData->strStateFilePath.setNull();
7327 else
7328 {
7329 Utf8Str stateFilePathFull(config.strStateFile);
7330 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7331 if (RT_FAILURE(vrc))
7332 return setError(E_FAIL,
7333 tr("Invalid saved state file path '%s' (%Rrc)"),
7334 config.strStateFile.c_str(),
7335 vrc);
7336 mSSData->strStateFilePath = stateFilePathFull;
7337 }
7338
7339 // snapshot folder needs special processing so set it again
7340 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7341 if (FAILED(rc)) return rc;
7342
7343 /* currentStateModified (optional, default is true) */
7344 mData->mCurrentStateModified = config.fCurrentStateModified;
7345
7346 mData->mLastStateChange = config.timeLastStateChange;
7347
7348 /*
7349 * note: all mUserData members must be assigned prior this point because
7350 * we need to commit changes in order to let mUserData be shared by all
7351 * snapshot machine instances.
7352 */
7353 mUserData.commitCopy();
7354
7355 // machine registry, if present (must be loaded before snapshots)
7356 if (config.canHaveOwnMediaRegistry())
7357 {
7358 // determine machine folder
7359 Utf8Str strMachineFolder = getSettingsFileFull();
7360 strMachineFolder.stripFilename();
7361 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7362 config.mediaRegistry,
7363 strMachineFolder);
7364 if (FAILED(rc)) return rc;
7365 }
7366
7367 /* Snapshot node (optional) */
7368 size_t cRootSnapshots;
7369 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7370 {
7371 // there must be only one root snapshot
7372 Assert(cRootSnapshots == 1);
7373
7374 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7375
7376 rc = loadSnapshot(snap,
7377 config.uuidCurrentSnapshot,
7378 NULL); // no parent == first snapshot
7379 if (FAILED(rc)) return rc;
7380 }
7381
7382 // hardware data
7383 rc = loadHardware(config.hardwareMachine);
7384 if (FAILED(rc)) return rc;
7385
7386 // load storage controllers
7387 rc = loadStorageControllers(config.storageMachine,
7388 puuidRegistry,
7389 NULL /* puuidSnapshot */);
7390 if (FAILED(rc)) return rc;
7391
7392 /*
7393 * NOTE: the assignment below must be the last thing to do,
7394 * otherwise it will be not possible to change the settings
7395 * somewhere in the code above because all setters will be
7396 * blocked by checkStateDependency(MutableStateDep).
7397 */
7398
7399 /* set the machine state to Aborted or Saved when appropriate */
7400 if (config.fAborted)
7401 {
7402 mSSData->strStateFilePath.setNull();
7403
7404 /* no need to use setMachineState() during init() */
7405 mData->mMachineState = MachineState_Aborted;
7406 }
7407 else if (!mSSData->strStateFilePath.isEmpty())
7408 {
7409 /* no need to use setMachineState() during init() */
7410 mData->mMachineState = MachineState_Saved;
7411 }
7412
7413 // after loading settings, we are no longer different from the XML on disk
7414 mData->flModifications = 0;
7415
7416 return S_OK;
7417}
7418
7419/**
7420 * Recursively loads all snapshots starting from the given.
7421 *
7422 * @param aNode <Snapshot> node.
7423 * @param aCurSnapshotId Current snapshot ID from the settings file.
7424 * @param aParentSnapshot Parent snapshot.
7425 */
7426HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7427 const Guid &aCurSnapshotId,
7428 Snapshot *aParentSnapshot)
7429{
7430 AssertReturn(!isSnapshotMachine(), E_FAIL);
7431 AssertReturn(!isSessionMachine(), E_FAIL);
7432
7433 HRESULT rc = S_OK;
7434
7435 Utf8Str strStateFile;
7436 if (!data.strStateFile.isEmpty())
7437 {
7438 /* optional */
7439 strStateFile = data.strStateFile;
7440 int vrc = calculateFullPath(strStateFile, strStateFile);
7441 if (RT_FAILURE(vrc))
7442 return setError(E_FAIL,
7443 tr("Invalid saved state file path '%s' (%Rrc)"),
7444 strStateFile.c_str(),
7445 vrc);
7446 }
7447
7448 /* create a snapshot machine object */
7449 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7450 pSnapshotMachine.createObject();
7451 rc = pSnapshotMachine->init(this,
7452 data.hardware,
7453 data.storage,
7454 data.uuid.ref(),
7455 strStateFile);
7456 if (FAILED(rc)) return rc;
7457
7458 /* create a snapshot object */
7459 ComObjPtr<Snapshot> pSnapshot;
7460 pSnapshot.createObject();
7461 /* initialize the snapshot */
7462 rc = pSnapshot->init(mParent, // VirtualBox object
7463 data.uuid,
7464 data.strName,
7465 data.strDescription,
7466 data.timestamp,
7467 pSnapshotMachine,
7468 aParentSnapshot);
7469 if (FAILED(rc)) return rc;
7470
7471 /* memorize the first snapshot if necessary */
7472 if (!mData->mFirstSnapshot)
7473 mData->mFirstSnapshot = pSnapshot;
7474
7475 /* memorize the current snapshot when appropriate */
7476 if ( !mData->mCurrentSnapshot
7477 && pSnapshot->getId() == aCurSnapshotId
7478 )
7479 mData->mCurrentSnapshot = pSnapshot;
7480
7481 // now create the children
7482 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7483 it != data.llChildSnapshots.end();
7484 ++it)
7485 {
7486 const settings::Snapshot &childData = *it;
7487 // recurse
7488 rc = loadSnapshot(childData,
7489 aCurSnapshotId,
7490 pSnapshot); // parent = the one we created above
7491 if (FAILED(rc)) return rc;
7492 }
7493
7494 return rc;
7495}
7496
7497/**
7498 * @param aNode <Hardware> node.
7499 */
7500HRESULT Machine::loadHardware(const settings::Hardware &data)
7501{
7502 AssertReturn(!isSessionMachine(), E_FAIL);
7503
7504 HRESULT rc = S_OK;
7505
7506 try
7507 {
7508 /* The hardware version attribute (optional). */
7509 mHWData->mHWVersion = data.strVersion;
7510 mHWData->mHardwareUUID = data.uuid;
7511
7512 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7513 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7514 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7515 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7516 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7517 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7518 mHWData->mPAEEnabled = data.fPAE;
7519 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7520
7521 mHWData->mCPUCount = data.cCPUs;
7522 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7523 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7524
7525 // cpu
7526 if (mHWData->mCPUHotPlugEnabled)
7527 {
7528 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7529 it != data.llCpus.end();
7530 ++it)
7531 {
7532 const settings::Cpu &cpu = *it;
7533
7534 mHWData->mCPUAttached[cpu.ulId] = true;
7535 }
7536 }
7537
7538 // cpuid leafs
7539 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7540 it != data.llCpuIdLeafs.end();
7541 ++it)
7542 {
7543 const settings::CpuIdLeaf &leaf = *it;
7544
7545 switch (leaf.ulId)
7546 {
7547 case 0x0:
7548 case 0x1:
7549 case 0x2:
7550 case 0x3:
7551 case 0x4:
7552 case 0x5:
7553 case 0x6:
7554 case 0x7:
7555 case 0x8:
7556 case 0x9:
7557 case 0xA:
7558 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7559 break;
7560
7561 case 0x80000000:
7562 case 0x80000001:
7563 case 0x80000002:
7564 case 0x80000003:
7565 case 0x80000004:
7566 case 0x80000005:
7567 case 0x80000006:
7568 case 0x80000007:
7569 case 0x80000008:
7570 case 0x80000009:
7571 case 0x8000000A:
7572 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7573 break;
7574
7575 default:
7576 /* just ignore */
7577 break;
7578 }
7579 }
7580
7581 mHWData->mMemorySize = data.ulMemorySizeMB;
7582 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7583
7584 // boot order
7585 for (size_t i = 0;
7586 i < RT_ELEMENTS(mHWData->mBootOrder);
7587 i++)
7588 {
7589 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7590 if (it == data.mapBootOrder.end())
7591 mHWData->mBootOrder[i] = DeviceType_Null;
7592 else
7593 mHWData->mBootOrder[i] = it->second;
7594 }
7595
7596 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7597 mHWData->mMonitorCount = data.cMonitors;
7598 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7599 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7600 mHWData->mFirmwareType = data.firmwareType;
7601 mHWData->mPointingHidType = data.pointingHidType;
7602 mHWData->mKeyboardHidType = data.keyboardHidType;
7603 mHWData->mChipsetType = data.chipsetType;
7604 mHWData->mHpetEnabled = data.fHpetEnabled;
7605
7606 /* VRDEServer */
7607 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7608 if (FAILED(rc)) return rc;
7609
7610 /* BIOS */
7611 rc = mBIOSSettings->loadSettings(data.biosSettings);
7612 if (FAILED(rc)) return rc;
7613
7614 // Bandwidth control (must come before network adapters)
7615 rc = mBandwidthControl->loadSettings(data.ioSettings);
7616 if (FAILED(rc)) return rc;
7617
7618 /* USB Controller */
7619 rc = mUSBController->loadSettings(data.usbController);
7620 if (FAILED(rc)) return rc;
7621
7622 // network adapters
7623 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7624 it != data.llNetworkAdapters.end();
7625 ++it)
7626 {
7627 const settings::NetworkAdapter &nic = *it;
7628
7629 /* slot unicity is guaranteed by XML Schema */
7630 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7631 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
7632 if (FAILED(rc)) return rc;
7633 }
7634
7635 // serial ports
7636 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7637 it != data.llSerialPorts.end();
7638 ++it)
7639 {
7640 const settings::SerialPort &s = *it;
7641
7642 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7643 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7644 if (FAILED(rc)) return rc;
7645 }
7646
7647 // parallel ports (optional)
7648 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7649 it != data.llParallelPorts.end();
7650 ++it)
7651 {
7652 const settings::ParallelPort &p = *it;
7653
7654 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7655 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7656 if (FAILED(rc)) return rc;
7657 }
7658
7659 /* AudioAdapter */
7660 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7661 if (FAILED(rc)) return rc;
7662
7663 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7664 it != data.llSharedFolders.end();
7665 ++it)
7666 {
7667 const settings::SharedFolder &sf = *it;
7668 rc = CreateSharedFolder(Bstr(sf.strName).raw(),
7669 Bstr(sf.strHostPath).raw(),
7670 sf.fWritable, sf.fAutoMount);
7671 if (FAILED(rc)) return rc;
7672 }
7673
7674 // Clipboard
7675 mHWData->mClipboardMode = data.clipboardMode;
7676
7677 // guest settings
7678 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7679
7680 // IO settings
7681 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7682 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7683
7684 // Host PCI devices
7685 for (settings::HostPciDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
7686 it != data.pciAttachments.end();
7687 ++it)
7688 {
7689 const settings::HostPciDeviceAttachment &hpda = *it;
7690 ComObjPtr<PciDeviceAttachment> pda;
7691
7692 pda.createObject();
7693 pda->loadSettings(this, hpda);
7694 mHWData->mPciDeviceAssignments.push_back(pda);
7695 }
7696
7697#ifdef VBOX_WITH_GUEST_PROPS
7698 /* Guest properties (optional) */
7699 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7700 it != data.llGuestProperties.end();
7701 ++it)
7702 {
7703 const settings::GuestProperty &prop = *it;
7704 uint32_t fFlags = guestProp::NILFLAG;
7705 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7706 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7707 mHWData->mGuestProperties.push_back(property);
7708 }
7709
7710 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7711#endif /* VBOX_WITH_GUEST_PROPS defined */
7712 }
7713 catch(std::bad_alloc &)
7714 {
7715 return E_OUTOFMEMORY;
7716 }
7717
7718 AssertComRC(rc);
7719 return rc;
7720}
7721
7722/**
7723 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7724 *
7725 * @param data
7726 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7727 * @param puuidSnapshot
7728 * @return
7729 */
7730HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7731 const Guid *puuidRegistry,
7732 const Guid *puuidSnapshot)
7733{
7734 AssertReturn(!isSessionMachine(), E_FAIL);
7735
7736 HRESULT rc = S_OK;
7737
7738 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7739 it != data.llStorageControllers.end();
7740 ++it)
7741 {
7742 const settings::StorageController &ctlData = *it;
7743
7744 ComObjPtr<StorageController> pCtl;
7745 /* Try to find one with the name first. */
7746 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7747 if (SUCCEEDED(rc))
7748 return setError(VBOX_E_OBJECT_IN_USE,
7749 tr("Storage controller named '%s' already exists"),
7750 ctlData.strName.c_str());
7751
7752 pCtl.createObject();
7753 rc = pCtl->init(this,
7754 ctlData.strName,
7755 ctlData.storageBus,
7756 ctlData.ulInstance,
7757 ctlData.fBootable);
7758 if (FAILED(rc)) return rc;
7759
7760 mStorageControllers->push_back(pCtl);
7761
7762 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7763 if (FAILED(rc)) return rc;
7764
7765 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7766 if (FAILED(rc)) return rc;
7767
7768 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7769 if (FAILED(rc)) return rc;
7770
7771 /* Set IDE emulation settings (only for AHCI controller). */
7772 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7773 {
7774 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7775 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7776 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7777 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7778 )
7779 return rc;
7780 }
7781
7782 /* Load the attached devices now. */
7783 rc = loadStorageDevices(pCtl,
7784 ctlData,
7785 puuidRegistry,
7786 puuidSnapshot);
7787 if (FAILED(rc)) return rc;
7788 }
7789
7790 return S_OK;
7791}
7792
7793/**
7794 * Called from loadStorageControllers for a controller's devices.
7795 *
7796 * @param aStorageController
7797 * @param data
7798 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7799 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7800 * @return
7801 */
7802HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7803 const settings::StorageController &data,
7804 const Guid *puuidRegistry,
7805 const Guid *puuidSnapshot)
7806{
7807 HRESULT rc = S_OK;
7808
7809 /* paranoia: detect duplicate attachments */
7810 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7811 it != data.llAttachedDevices.end();
7812 ++it)
7813 {
7814 const settings::AttachedDevice &ad = *it;
7815
7816 for (settings::AttachedDevicesList::const_iterator it2 = it;
7817 it2 != data.llAttachedDevices.end();
7818 ++it2)
7819 {
7820 if (it == it2)
7821 continue;
7822
7823 const settings::AttachedDevice &ad2 = *it2;
7824
7825 if ( ad.lPort == ad2.lPort
7826 && ad.lDevice == ad2.lDevice)
7827 {
7828 return setError(E_FAIL,
7829 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
7830 aStorageController->getName().c_str(),
7831 ad.lPort,
7832 ad.lDevice,
7833 mUserData->s.strName.c_str());
7834 }
7835 }
7836 }
7837
7838 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7839 it != data.llAttachedDevices.end();
7840 ++it)
7841 {
7842 const settings::AttachedDevice &dev = *it;
7843 ComObjPtr<Medium> medium;
7844
7845 switch (dev.deviceType)
7846 {
7847 case DeviceType_Floppy:
7848 case DeviceType_DVD:
7849 if (dev.strHostDriveSrc.isNotEmpty())
7850 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
7851 else
7852 rc = mParent->findRemoveableMedium(dev.deviceType,
7853 dev.uuid,
7854 false /* fRefresh */,
7855 false /* aSetError */,
7856 medium);
7857 if (rc == VBOX_E_OBJECT_NOT_FOUND)
7858 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
7859 rc = S_OK;
7860 break;
7861
7862 case DeviceType_HardDisk:
7863 {
7864 /* find a hard disk by UUID */
7865 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
7866 if (FAILED(rc))
7867 {
7868 if (isSnapshotMachine())
7869 {
7870 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7871 // so the user knows that the bad disk is in a snapshot somewhere
7872 com::ErrorInfo info;
7873 return setError(E_FAIL,
7874 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7875 puuidSnapshot->raw(),
7876 info.getText().raw());
7877 }
7878 else
7879 return rc;
7880 }
7881
7882 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7883
7884 if (medium->getType() == MediumType_Immutable)
7885 {
7886 if (isSnapshotMachine())
7887 return setError(E_FAIL,
7888 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7889 "of the virtual machine '%s' ('%s')"),
7890 medium->getLocationFull().c_str(),
7891 dev.uuid.raw(),
7892 puuidSnapshot->raw(),
7893 mUserData->s.strName.c_str(),
7894 mData->m_strConfigFileFull.c_str());
7895
7896 return setError(E_FAIL,
7897 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7898 medium->getLocationFull().c_str(),
7899 dev.uuid.raw(),
7900 mUserData->s.strName.c_str(),
7901 mData->m_strConfigFileFull.c_str());
7902 }
7903
7904 if (medium->getType() == MediumType_MultiAttach)
7905 {
7906 if (isSnapshotMachine())
7907 return setError(E_FAIL,
7908 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7909 "of the virtual machine '%s' ('%s')"),
7910 medium->getLocationFull().c_str(),
7911 dev.uuid.raw(),
7912 puuidSnapshot->raw(),
7913 mUserData->s.strName.c_str(),
7914 mData->m_strConfigFileFull.c_str());
7915
7916 return setError(E_FAIL,
7917 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
7918 medium->getLocationFull().c_str(),
7919 dev.uuid.raw(),
7920 mUserData->s.strName.c_str(),
7921 mData->m_strConfigFileFull.c_str());
7922 }
7923
7924 if ( !isSnapshotMachine()
7925 && medium->getChildren().size() != 0
7926 )
7927 return setError(E_FAIL,
7928 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
7929 "because it has %d differencing child hard disks"),
7930 medium->getLocationFull().c_str(),
7931 dev.uuid.raw(),
7932 mUserData->s.strName.c_str(),
7933 mData->m_strConfigFileFull.c_str(),
7934 medium->getChildren().size());
7935
7936 if (findAttachment(mMediaData->mAttachments,
7937 medium))
7938 return setError(E_FAIL,
7939 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
7940 medium->getLocationFull().c_str(),
7941 dev.uuid.raw(),
7942 mUserData->s.strName.c_str(),
7943 mData->m_strConfigFileFull.c_str());
7944
7945 break;
7946 }
7947
7948 default:
7949 return setError(E_FAIL,
7950 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
7951 medium->getLocationFull().c_str(),
7952 mUserData->s.strName.c_str(),
7953 mData->m_strConfigFileFull.c_str());
7954 }
7955
7956 if (FAILED(rc))
7957 break;
7958
7959 /* Bandwidth groups are loaded at this point. */
7960 ComObjPtr<BandwidthGroup> pBwGroup;
7961
7962 if (!dev.strBwGroup.isEmpty())
7963 {
7964 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
7965 if (FAILED(rc))
7966 return setError(E_FAIL,
7967 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
7968 medium->getLocationFull().c_str(),
7969 dev.strBwGroup.c_str(),
7970 mUserData->s.strName.c_str(),
7971 mData->m_strConfigFileFull.c_str());
7972 pBwGroup->reference();
7973 }
7974
7975 const Bstr controllerName = aStorageController->getName();
7976 ComObjPtr<MediumAttachment> pAttachment;
7977 pAttachment.createObject();
7978 rc = pAttachment->init(this,
7979 medium,
7980 controllerName,
7981 dev.lPort,
7982 dev.lDevice,
7983 dev.deviceType,
7984 dev.fPassThrough,
7985 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
7986 if (FAILED(rc)) break;
7987
7988 /* associate the medium with this machine and snapshot */
7989 if (!medium.isNull())
7990 {
7991 AutoCaller medCaller(medium);
7992 if (FAILED(medCaller.rc())) return medCaller.rc();
7993 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
7994
7995 if (isSnapshotMachine())
7996 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
7997 else
7998 rc = medium->addBackReference(mData->mUuid);
7999 /* If the medium->addBackReference fails it sets an appropriate
8000 * error message, so no need to do any guesswork here. */
8001
8002 if (puuidRegistry)
8003 // caller wants registry ID to be set on all attached media (OVF import case)
8004 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
8005 }
8006
8007 if (FAILED(rc))
8008 break;
8009
8010 /* back up mMediaData to let registeredInit() properly rollback on failure
8011 * (= limited accessibility) */
8012 setModified(IsModified_Storage);
8013 mMediaData.backup();
8014 mMediaData->mAttachments.push_back(pAttachment);
8015 }
8016
8017 return rc;
8018}
8019
8020/**
8021 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
8022 *
8023 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
8024 * @param aSnapshot where to return the found snapshot
8025 * @param aSetError true to set extended error info on failure
8026 */
8027HRESULT Machine::findSnapshotById(const Guid &aId,
8028 ComObjPtr<Snapshot> &aSnapshot,
8029 bool aSetError /* = false */)
8030{
8031 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8032
8033 if (!mData->mFirstSnapshot)
8034 {
8035 if (aSetError)
8036 return setError(E_FAIL, tr("This machine does not have any snapshots"));
8037 return E_FAIL;
8038 }
8039
8040 if (aId.isEmpty())
8041 aSnapshot = mData->mFirstSnapshot;
8042 else
8043 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
8044
8045 if (!aSnapshot)
8046 {
8047 if (aSetError)
8048 return setError(E_FAIL,
8049 tr("Could not find a snapshot with UUID {%s}"),
8050 aId.toString().c_str());
8051 return E_FAIL;
8052 }
8053
8054 return S_OK;
8055}
8056
8057/**
8058 * Returns the snapshot with the given name or fails of no such snapshot.
8059 *
8060 * @param aName snapshot name to find
8061 * @param aSnapshot where to return the found snapshot
8062 * @param aSetError true to set extended error info on failure
8063 */
8064HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
8065 ComObjPtr<Snapshot> &aSnapshot,
8066 bool aSetError /* = false */)
8067{
8068 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
8069
8070 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8071
8072 if (!mData->mFirstSnapshot)
8073 {
8074 if (aSetError)
8075 return setError(VBOX_E_OBJECT_NOT_FOUND,
8076 tr("This machine does not have any snapshots"));
8077 return VBOX_E_OBJECT_NOT_FOUND;
8078 }
8079
8080 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
8081
8082 if (!aSnapshot)
8083 {
8084 if (aSetError)
8085 return setError(VBOX_E_OBJECT_NOT_FOUND,
8086 tr("Could not find a snapshot named '%s'"), strName.c_str());
8087 return VBOX_E_OBJECT_NOT_FOUND;
8088 }
8089
8090 return S_OK;
8091}
8092
8093/**
8094 * Returns a storage controller object with the given name.
8095 *
8096 * @param aName storage controller name to find
8097 * @param aStorageController where to return the found storage controller
8098 * @param aSetError true to set extended error info on failure
8099 */
8100HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
8101 ComObjPtr<StorageController> &aStorageController,
8102 bool aSetError /* = false */)
8103{
8104 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
8105
8106 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8107 it != mStorageControllers->end();
8108 ++it)
8109 {
8110 if ((*it)->getName() == aName)
8111 {
8112 aStorageController = (*it);
8113 return S_OK;
8114 }
8115 }
8116
8117 if (aSetError)
8118 return setError(VBOX_E_OBJECT_NOT_FOUND,
8119 tr("Could not find a storage controller named '%s'"),
8120 aName.c_str());
8121 return VBOX_E_OBJECT_NOT_FOUND;
8122}
8123
8124HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
8125 MediaData::AttachmentList &atts)
8126{
8127 AutoCaller autoCaller(this);
8128 if (FAILED(autoCaller.rc())) return autoCaller.rc();
8129
8130 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8131
8132 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
8133 it != mMediaData->mAttachments.end();
8134 ++it)
8135 {
8136 const ComObjPtr<MediumAttachment> &pAtt = *it;
8137
8138 // should never happen, but deal with NULL pointers in the list.
8139 AssertStmt(!pAtt.isNull(), continue);
8140
8141 // getControllerName() needs caller+read lock
8142 AutoCaller autoAttCaller(pAtt);
8143 if (FAILED(autoAttCaller.rc()))
8144 {
8145 atts.clear();
8146 return autoAttCaller.rc();
8147 }
8148 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
8149
8150 if (pAtt->getControllerName() == aName)
8151 atts.push_back(pAtt);
8152 }
8153
8154 return S_OK;
8155}
8156
8157/**
8158 * Helper for #saveSettings. Cares about renaming the settings directory and
8159 * file if the machine name was changed and about creating a new settings file
8160 * if this is a new machine.
8161 *
8162 * @note Must be never called directly but only from #saveSettings().
8163 */
8164HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
8165{
8166 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8167
8168 HRESULT rc = S_OK;
8169
8170 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
8171
8172 /* attempt to rename the settings file if machine name is changed */
8173 if ( mUserData->s.fNameSync
8174 && mUserData.isBackedUp()
8175 && mUserData.backedUpData()->s.strName != mUserData->s.strName
8176 )
8177 {
8178 bool dirRenamed = false;
8179 bool fileRenamed = false;
8180
8181 Utf8Str configFile, newConfigFile;
8182 Utf8Str configFilePrev, newConfigFilePrev;
8183 Utf8Str configDir, newConfigDir;
8184
8185 do
8186 {
8187 int vrc = VINF_SUCCESS;
8188
8189 Utf8Str name = mUserData.backedUpData()->s.strName;
8190 Utf8Str newName = mUserData->s.strName;
8191
8192 configFile = mData->m_strConfigFileFull;
8193
8194 /* first, rename the directory if it matches the machine name */
8195 configDir = configFile;
8196 configDir.stripFilename();
8197 newConfigDir = configDir;
8198 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8199 {
8200 newConfigDir.stripFilename();
8201 newConfigDir.append(RTPATH_DELIMITER);
8202 newConfigDir.append(newName);
8203 /* new dir and old dir cannot be equal here because of 'if'
8204 * above and because name != newName */
8205 Assert(configDir != newConfigDir);
8206 if (!fSettingsFileIsNew)
8207 {
8208 /* perform real rename only if the machine is not new */
8209 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8210 if (RT_FAILURE(vrc))
8211 {
8212 rc = setError(E_FAIL,
8213 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8214 configDir.c_str(),
8215 newConfigDir.c_str(),
8216 vrc);
8217 break;
8218 }
8219 dirRenamed = true;
8220 }
8221 }
8222
8223 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8224 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8225
8226 /* then try to rename the settings file itself */
8227 if (newConfigFile != configFile)
8228 {
8229 /* get the path to old settings file in renamed directory */
8230 configFile = Utf8StrFmt("%s%c%s",
8231 newConfigDir.c_str(),
8232 RTPATH_DELIMITER,
8233 RTPathFilename(configFile.c_str()));
8234 if (!fSettingsFileIsNew)
8235 {
8236 /* perform real rename only if the machine is not new */
8237 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8238 if (RT_FAILURE(vrc))
8239 {
8240 rc = setError(E_FAIL,
8241 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8242 configFile.c_str(),
8243 newConfigFile.c_str(),
8244 vrc);
8245 break;
8246 }
8247 fileRenamed = true;
8248 configFilePrev = configFile;
8249 configFilePrev += "-prev";
8250 newConfigFilePrev = newConfigFile;
8251 newConfigFilePrev += "-prev";
8252 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
8253 }
8254 }
8255
8256 // update m_strConfigFileFull amd mConfigFile
8257 mData->m_strConfigFileFull = newConfigFile;
8258 // compute the relative path too
8259 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8260
8261 // store the old and new so that VirtualBox::saveSettings() can update
8262 // the media registry
8263 if ( mData->mRegistered
8264 && configDir != newConfigDir)
8265 {
8266 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8267
8268 if (pfNeedsGlobalSaveSettings)
8269 *pfNeedsGlobalSaveSettings = true;
8270 }
8271
8272 // in the saved state file path, replace the old directory with the new directory
8273 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8274 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8275
8276 // and do the same thing for the saved state file paths of all the online snapshots
8277 if (mData->mFirstSnapshot)
8278 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8279 newConfigDir.c_str());
8280 }
8281 while (0);
8282
8283 if (FAILED(rc))
8284 {
8285 /* silently try to rename everything back */
8286 if (fileRenamed)
8287 {
8288 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
8289 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8290 }
8291 if (dirRenamed)
8292 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8293 }
8294
8295 if (FAILED(rc)) return rc;
8296 }
8297
8298 if (fSettingsFileIsNew)
8299 {
8300 /* create a virgin config file */
8301 int vrc = VINF_SUCCESS;
8302
8303 /* ensure the settings directory exists */
8304 Utf8Str path(mData->m_strConfigFileFull);
8305 path.stripFilename();
8306 if (!RTDirExists(path.c_str()))
8307 {
8308 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8309 if (RT_FAILURE(vrc))
8310 {
8311 return setError(E_FAIL,
8312 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8313 path.c_str(),
8314 vrc);
8315 }
8316 }
8317
8318 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8319 path = Utf8Str(mData->m_strConfigFileFull);
8320 RTFILE f = NIL_RTFILE;
8321 vrc = RTFileOpen(&f, path.c_str(),
8322 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8323 if (RT_FAILURE(vrc))
8324 return setError(E_FAIL,
8325 tr("Could not create the settings file '%s' (%Rrc)"),
8326 path.c_str(),
8327 vrc);
8328 RTFileClose(f);
8329 }
8330
8331 return rc;
8332}
8333
8334/**
8335 * Saves and commits machine data, user data and hardware data.
8336 *
8337 * Note that on failure, the data remains uncommitted.
8338 *
8339 * @a aFlags may combine the following flags:
8340 *
8341 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8342 * Used when saving settings after an operation that makes them 100%
8343 * correspond to the settings from the current snapshot.
8344 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8345 * #isReallyModified() returns false. This is necessary for cases when we
8346 * change machine data directly, not through the backup()/commit() mechanism.
8347 * - SaveS_Force: settings will be saved without doing a deep compare of the
8348 * settings structures. This is used when this is called because snapshots
8349 * have changed to avoid the overhead of the deep compare.
8350 *
8351 * @note Must be called from under this object's write lock. Locks children for
8352 * writing.
8353 *
8354 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8355 * initialized to false and that will be set to true by this function if
8356 * the caller must invoke VirtualBox::saveSettings() because the global
8357 * settings have changed. This will happen if a machine rename has been
8358 * saved and the global machine and media registries will therefore need
8359 * updating.
8360 */
8361HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8362 int aFlags /*= 0*/)
8363{
8364 LogFlowThisFuncEnter();
8365
8366 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8367
8368 /* make sure child objects are unable to modify the settings while we are
8369 * saving them */
8370 ensureNoStateDependencies();
8371
8372 AssertReturn(!isSnapshotMachine(),
8373 E_FAIL);
8374
8375 HRESULT rc = S_OK;
8376 bool fNeedsWrite = false;
8377
8378 /* First, prepare to save settings. It will care about renaming the
8379 * settings directory and file if the machine name was changed and about
8380 * creating a new settings file if this is a new machine. */
8381 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8382 if (FAILED(rc)) return rc;
8383
8384 // keep a pointer to the current settings structures
8385 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8386 settings::MachineConfigFile *pNewConfig = NULL;
8387
8388 try
8389 {
8390 // make a fresh one to have everyone write stuff into
8391 pNewConfig = new settings::MachineConfigFile(NULL);
8392 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8393
8394 // now go and copy all the settings data from COM to the settings structures
8395 // (this calles saveSettings() on all the COM objects in the machine)
8396 copyMachineDataToSettings(*pNewConfig);
8397
8398 if (aFlags & SaveS_ResetCurStateModified)
8399 {
8400 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8401 mData->mCurrentStateModified = FALSE;
8402 fNeedsWrite = true; // always, no need to compare
8403 }
8404 else if (aFlags & SaveS_Force)
8405 {
8406 fNeedsWrite = true; // always, no need to compare
8407 }
8408 else
8409 {
8410 if (!mData->mCurrentStateModified)
8411 {
8412 // do a deep compare of the settings that we just saved with the settings
8413 // previously stored in the config file; this invokes MachineConfigFile::operator==
8414 // which does a deep compare of all the settings, which is expensive but less expensive
8415 // than writing out XML in vain
8416 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
8417
8418 // could still be modified if any settings changed
8419 mData->mCurrentStateModified = fAnySettingsChanged;
8420
8421 fNeedsWrite = fAnySettingsChanged;
8422 }
8423 else
8424 fNeedsWrite = true;
8425 }
8426
8427 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8428
8429 if (fNeedsWrite)
8430 // now spit it all out!
8431 pNewConfig->write(mData->m_strConfigFileFull);
8432
8433 mData->pMachineConfigFile = pNewConfig;
8434 delete pOldConfig;
8435 commit();
8436
8437 // after saving settings, we are no longer different from the XML on disk
8438 mData->flModifications = 0;
8439 }
8440 catch (HRESULT err)
8441 {
8442 // we assume that error info is set by the thrower
8443 rc = err;
8444
8445 // restore old config
8446 delete pNewConfig;
8447 mData->pMachineConfigFile = pOldConfig;
8448 }
8449 catch (...)
8450 {
8451 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8452 }
8453
8454 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8455 {
8456 /* Fire the data change event, even on failure (since we've already
8457 * committed all data). This is done only for SessionMachines because
8458 * mutable Machine instances are always not registered (i.e. private
8459 * to the client process that creates them) and thus don't need to
8460 * inform callbacks. */
8461 if (isSessionMachine())
8462 mParent->onMachineDataChange(mData->mUuid);
8463 }
8464
8465 LogFlowThisFunc(("rc=%08X\n", rc));
8466 LogFlowThisFuncLeave();
8467 return rc;
8468}
8469
8470/**
8471 * Implementation for saving the machine settings into the given
8472 * settings::MachineConfigFile instance. This copies machine extradata
8473 * from the previous machine config file in the instance data, if any.
8474 *
8475 * This gets called from two locations:
8476 *
8477 * -- Machine::saveSettings(), during the regular XML writing;
8478 *
8479 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8480 * exported to OVF and we write the VirtualBox proprietary XML
8481 * into a <vbox:Machine> tag.
8482 *
8483 * This routine fills all the fields in there, including snapshots, *except*
8484 * for the following:
8485 *
8486 * -- fCurrentStateModified. There is some special logic associated with that.
8487 *
8488 * The caller can then call MachineConfigFile::write() or do something else
8489 * with it.
8490 *
8491 * Caller must hold the machine lock!
8492 *
8493 * This throws XML errors and HRESULT, so the caller must have a catch block!
8494 */
8495void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8496{
8497 // deep copy extradata
8498 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8499
8500 config.uuid = mData->mUuid;
8501
8502 // copy name, description, OS type, teleport, UTC etc.
8503 config.machineUserData = mUserData->s;
8504
8505 if ( mData->mMachineState == MachineState_Saved
8506 || mData->mMachineState == MachineState_Restoring
8507 // when deleting a snapshot we may or may not have a saved state in the current state,
8508 // so let's not assert here please
8509 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8510 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8511 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8512 && (!mSSData->strStateFilePath.isEmpty())
8513 )
8514 )
8515 {
8516 Assert(!mSSData->strStateFilePath.isEmpty());
8517 /* try to make the file name relative to the settings file dir */
8518 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
8519 }
8520 else
8521 {
8522 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
8523 config.strStateFile.setNull();
8524 }
8525
8526 if (mData->mCurrentSnapshot)
8527 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8528 else
8529 config.uuidCurrentSnapshot.clear();
8530
8531 config.timeLastStateChange = mData->mLastStateChange;
8532 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8533 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8534
8535 HRESULT rc = saveHardware(config.hardwareMachine);
8536 if (FAILED(rc)) throw rc;
8537
8538 rc = saveStorageControllers(config.storageMachine);
8539 if (FAILED(rc)) throw rc;
8540
8541 // save machine's media registry if this is VirtualBox 4.0 or later
8542 if (config.canHaveOwnMediaRegistry())
8543 {
8544 // determine machine folder
8545 Utf8Str strMachineFolder = getSettingsFileFull();
8546 strMachineFolder.stripFilename();
8547 mParent->saveMediaRegistry(config.mediaRegistry,
8548 getId(), // only media with registry ID == machine UUID
8549 strMachineFolder);
8550 // this throws HRESULT
8551 }
8552
8553 // save snapshots
8554 rc = saveAllSnapshots(config);
8555 if (FAILED(rc)) throw rc;
8556}
8557
8558/**
8559 * Saves all snapshots of the machine into the given machine config file. Called
8560 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8561 * @param config
8562 * @return
8563 */
8564HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8565{
8566 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8567
8568 HRESULT rc = S_OK;
8569
8570 try
8571 {
8572 config.llFirstSnapshot.clear();
8573
8574 if (mData->mFirstSnapshot)
8575 {
8576 settings::Snapshot snapNew;
8577 config.llFirstSnapshot.push_back(snapNew);
8578
8579 // get reference to the fresh copy of the snapshot on the list and
8580 // work on that copy directly to avoid excessive copying later
8581 settings::Snapshot &snap = config.llFirstSnapshot.front();
8582
8583 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8584 if (FAILED(rc)) throw rc;
8585 }
8586
8587// if (mType == IsSessionMachine)
8588// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8589
8590 }
8591 catch (HRESULT err)
8592 {
8593 /* we assume that error info is set by the thrower */
8594 rc = err;
8595 }
8596 catch (...)
8597 {
8598 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8599 }
8600
8601 return rc;
8602}
8603
8604/**
8605 * Saves the VM hardware configuration. It is assumed that the
8606 * given node is empty.
8607 *
8608 * @param aNode <Hardware> node to save the VM hardware configuration to.
8609 */
8610HRESULT Machine::saveHardware(settings::Hardware &data)
8611{
8612 HRESULT rc = S_OK;
8613
8614 try
8615 {
8616 /* The hardware version attribute (optional).
8617 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8618 if ( mHWData->mHWVersion == "1"
8619 && mSSData->strStateFilePath.isEmpty()
8620 )
8621 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. */
8622
8623 data.strVersion = mHWData->mHWVersion;
8624 data.uuid = mHWData->mHardwareUUID;
8625
8626 // CPU
8627 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8628 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8629 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8630 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8631 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8632 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8633 data.fPAE = !!mHWData->mPAEEnabled;
8634 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8635
8636 /* Standard and Extended CPUID leafs. */
8637 data.llCpuIdLeafs.clear();
8638 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8639 {
8640 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8641 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8642 }
8643 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8644 {
8645 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8646 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8647 }
8648
8649 data.cCPUs = mHWData->mCPUCount;
8650 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8651 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8652
8653 data.llCpus.clear();
8654 if (data.fCpuHotPlug)
8655 {
8656 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8657 {
8658 if (mHWData->mCPUAttached[idx])
8659 {
8660 settings::Cpu cpu;
8661 cpu.ulId = idx;
8662 data.llCpus.push_back(cpu);
8663 }
8664 }
8665 }
8666
8667 // memory
8668 data.ulMemorySizeMB = mHWData->mMemorySize;
8669 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8670
8671 // firmware
8672 data.firmwareType = mHWData->mFirmwareType;
8673
8674 // HID
8675 data.pointingHidType = mHWData->mPointingHidType;
8676 data.keyboardHidType = mHWData->mKeyboardHidType;
8677
8678 // chipset
8679 data.chipsetType = mHWData->mChipsetType;
8680
8681 // HPET
8682 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8683
8684 // boot order
8685 data.mapBootOrder.clear();
8686 for (size_t i = 0;
8687 i < RT_ELEMENTS(mHWData->mBootOrder);
8688 ++i)
8689 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8690
8691 // display
8692 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8693 data.cMonitors = mHWData->mMonitorCount;
8694 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8695 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8696
8697 /* VRDEServer settings (optional) */
8698 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8699 if (FAILED(rc)) throw rc;
8700
8701 /* BIOS (required) */
8702 rc = mBIOSSettings->saveSettings(data.biosSettings);
8703 if (FAILED(rc)) throw rc;
8704
8705 /* USB Controller (required) */
8706 rc = mUSBController->saveSettings(data.usbController);
8707 if (FAILED(rc)) throw rc;
8708
8709 /* Network adapters (required) */
8710 data.llNetworkAdapters.clear();
8711 for (ULONG slot = 0;
8712 slot < RT_ELEMENTS(mNetworkAdapters);
8713 ++slot)
8714 {
8715 settings::NetworkAdapter nic;
8716 nic.ulSlot = slot;
8717 rc = mNetworkAdapters[slot]->saveSettings(nic);
8718 if (FAILED(rc)) throw rc;
8719
8720 data.llNetworkAdapters.push_back(nic);
8721 }
8722
8723 /* Serial ports */
8724 data.llSerialPorts.clear();
8725 for (ULONG slot = 0;
8726 slot < RT_ELEMENTS(mSerialPorts);
8727 ++slot)
8728 {
8729 settings::SerialPort s;
8730 s.ulSlot = slot;
8731 rc = mSerialPorts[slot]->saveSettings(s);
8732 if (FAILED(rc)) return rc;
8733
8734 data.llSerialPorts.push_back(s);
8735 }
8736
8737 /* Parallel ports */
8738 data.llParallelPorts.clear();
8739 for (ULONG slot = 0;
8740 slot < RT_ELEMENTS(mParallelPorts);
8741 ++slot)
8742 {
8743 settings::ParallelPort p;
8744 p.ulSlot = slot;
8745 rc = mParallelPorts[slot]->saveSettings(p);
8746 if (FAILED(rc)) return rc;
8747
8748 data.llParallelPorts.push_back(p);
8749 }
8750
8751 /* Audio adapter */
8752 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8753 if (FAILED(rc)) return rc;
8754
8755 /* Shared folders */
8756 data.llSharedFolders.clear();
8757 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8758 it != mHWData->mSharedFolders.end();
8759 ++it)
8760 {
8761 SharedFolder *pSF = *it;
8762 AutoCaller sfCaller(pSF);
8763 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8764 settings::SharedFolder sf;
8765 sf.strName = pSF->getName();
8766 sf.strHostPath = pSF->getHostPath();
8767 sf.fWritable = !!pSF->isWritable();
8768 sf.fAutoMount = !!pSF->isAutoMounted();
8769
8770 data.llSharedFolders.push_back(sf);
8771 }
8772
8773 // clipboard
8774 data.clipboardMode = mHWData->mClipboardMode;
8775
8776 /* Guest */
8777 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8778
8779 // IO settings
8780 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8781 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8782
8783 /* BandwidthControl (required) */
8784 rc = mBandwidthControl->saveSettings(data.ioSettings);
8785 if (FAILED(rc)) throw rc;
8786
8787 /* Host PCI devices */
8788 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
8789 it != mHWData->mPciDeviceAssignments.end();
8790 ++it)
8791 {
8792 ComObjPtr<PciDeviceAttachment> pda = *it;
8793 settings::HostPciDeviceAttachment hpda;
8794
8795 rc = pda->saveSettings(hpda);
8796 if (FAILED(rc)) throw rc;
8797
8798 data.pciAttachments.push_back(hpda);
8799 }
8800
8801
8802 // guest properties
8803 data.llGuestProperties.clear();
8804#ifdef VBOX_WITH_GUEST_PROPS
8805 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8806 it != mHWData->mGuestProperties.end();
8807 ++it)
8808 {
8809 HWData::GuestProperty property = *it;
8810
8811 /* Remove transient guest properties at shutdown unless we
8812 * are saving state */
8813 if ( ( mData->mMachineState == MachineState_PoweredOff
8814 || mData->mMachineState == MachineState_Aborted
8815 || mData->mMachineState == MachineState_Teleported)
8816 && ( property.mFlags & guestProp::TRANSIENT
8817 || property.mFlags & guestProp::TRANSRESET))
8818 continue;
8819 settings::GuestProperty prop;
8820 prop.strName = property.strName;
8821 prop.strValue = property.strValue;
8822 prop.timestamp = property.mTimestamp;
8823 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8824 guestProp::writeFlags(property.mFlags, szFlags);
8825 prop.strFlags = szFlags;
8826
8827 data.llGuestProperties.push_back(prop);
8828 }
8829
8830 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8831 /* I presume this doesn't require a backup(). */
8832 mData->mGuestPropertiesModified = FALSE;
8833#endif /* VBOX_WITH_GUEST_PROPS defined */
8834 }
8835 catch(std::bad_alloc &)
8836 {
8837 return E_OUTOFMEMORY;
8838 }
8839
8840 AssertComRC(rc);
8841 return rc;
8842}
8843
8844/**
8845 * Saves the storage controller configuration.
8846 *
8847 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
8848 */
8849HRESULT Machine::saveStorageControllers(settings::Storage &data)
8850{
8851 data.llStorageControllers.clear();
8852
8853 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8854 it != mStorageControllers->end();
8855 ++it)
8856 {
8857 HRESULT rc;
8858 ComObjPtr<StorageController> pCtl = *it;
8859
8860 settings::StorageController ctl;
8861 ctl.strName = pCtl->getName();
8862 ctl.controllerType = pCtl->getControllerType();
8863 ctl.storageBus = pCtl->getStorageBus();
8864 ctl.ulInstance = pCtl->getInstance();
8865 ctl.fBootable = pCtl->getBootable();
8866
8867 /* Save the port count. */
8868 ULONG portCount;
8869 rc = pCtl->COMGETTER(PortCount)(&portCount);
8870 ComAssertComRCRet(rc, rc);
8871 ctl.ulPortCount = portCount;
8872
8873 /* Save fUseHostIOCache */
8874 BOOL fUseHostIOCache;
8875 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8876 ComAssertComRCRet(rc, rc);
8877 ctl.fUseHostIOCache = !!fUseHostIOCache;
8878
8879 /* Save IDE emulation settings. */
8880 if (ctl.controllerType == StorageControllerType_IntelAhci)
8881 {
8882 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8883 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8884 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8885 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8886 )
8887 ComAssertComRCRet(rc, rc);
8888 }
8889
8890 /* save the devices now. */
8891 rc = saveStorageDevices(pCtl, ctl);
8892 ComAssertComRCRet(rc, rc);
8893
8894 data.llStorageControllers.push_back(ctl);
8895 }
8896
8897 return S_OK;
8898}
8899
8900/**
8901 * Saves the hard disk configuration.
8902 */
8903HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8904 settings::StorageController &data)
8905{
8906 MediaData::AttachmentList atts;
8907
8908 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
8909 if (FAILED(rc)) return rc;
8910
8911 data.llAttachedDevices.clear();
8912 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8913 it != atts.end();
8914 ++it)
8915 {
8916 settings::AttachedDevice dev;
8917
8918 MediumAttachment *pAttach = *it;
8919 Medium *pMedium = pAttach->getMedium();
8920
8921 dev.deviceType = pAttach->getType();
8922 dev.lPort = pAttach->getPort();
8923 dev.lDevice = pAttach->getDevice();
8924 if (pMedium)
8925 {
8926 if (pMedium->isHostDrive())
8927 dev.strHostDriveSrc = pMedium->getLocationFull();
8928 else
8929 dev.uuid = pMedium->getId();
8930 dev.fPassThrough = pAttach->getPassthrough();
8931 }
8932
8933 dev.strBwGroup = pAttach->getBandwidthGroup();
8934
8935 data.llAttachedDevices.push_back(dev);
8936 }
8937
8938 return S_OK;
8939}
8940
8941/**
8942 * Saves machine state settings as defined by aFlags
8943 * (SaveSTS_* values).
8944 *
8945 * @param aFlags Combination of SaveSTS_* flags.
8946 *
8947 * @note Locks objects for writing.
8948 */
8949HRESULT Machine::saveStateSettings(int aFlags)
8950{
8951 if (aFlags == 0)
8952 return S_OK;
8953
8954 AutoCaller autoCaller(this);
8955 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8956
8957 /* This object's write lock is also necessary to serialize file access
8958 * (prevent concurrent reads and writes) */
8959 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8960
8961 HRESULT rc = S_OK;
8962
8963 Assert(mData->pMachineConfigFile);
8964
8965 try
8966 {
8967 if (aFlags & SaveSTS_CurStateModified)
8968 mData->pMachineConfigFile->fCurrentStateModified = true;
8969
8970 if (aFlags & SaveSTS_StateFilePath)
8971 {
8972 if (!mSSData->strStateFilePath.isEmpty())
8973 /* try to make the file name relative to the settings file dir */
8974 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
8975 else
8976 mData->pMachineConfigFile->strStateFile.setNull();
8977 }
8978
8979 if (aFlags & SaveSTS_StateTimeStamp)
8980 {
8981 Assert( mData->mMachineState != MachineState_Aborted
8982 || mSSData->strStateFilePath.isEmpty());
8983
8984 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8985
8986 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8987//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8988 }
8989
8990 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8991 }
8992 catch (...)
8993 {
8994 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8995 }
8996
8997 return rc;
8998}
8999
9000/**
9001 * Ensures that the given medium is added to a media registry. If this machine
9002 * was created with 4.0 or later, then the machine registry is used. Otherwise
9003 * the global VirtualBox media registry is used. If the medium was actually
9004 * added to a registry (because it wasn't in the registry yet), the UUID of
9005 * that registry is added to the given list so that the caller can save the
9006 * registry.
9007 *
9008 * Caller must hold machine read lock!
9009 *
9010 * @param pMedium
9011 * @param llRegistriesThatNeedSaving
9012 * @param puuid Optional buffer that receives the registry UUID that was used.
9013 */
9014void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
9015 GuidList &llRegistriesThatNeedSaving,
9016 Guid *puuid)
9017{
9018 // decide which medium registry to use now that the medium is attached:
9019 Guid uuid;
9020 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
9021 // machine XML is VirtualBox 4.0 or higher:
9022 uuid = getId(); // machine UUID
9023 else
9024 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
9025
9026 AutoCaller autoCaller(pMedium);
9027 if (FAILED(autoCaller.rc())) return;
9028 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9029
9030 if (pMedium->addRegistry(uuid, false /* fRecurse */))
9031 // registry actually changed:
9032 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
9033
9034 if (puuid)
9035 *puuid = uuid;
9036}
9037
9038/**
9039 * Creates differencing hard disks for all normal hard disks attached to this
9040 * machine and a new set of attachments to refer to created disks.
9041 *
9042 * Used when taking a snapshot or when deleting the current state. Gets called
9043 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
9044 *
9045 * This method assumes that mMediaData contains the original hard disk attachments
9046 * it needs to create diffs for. On success, these attachments will be replaced
9047 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
9048 * called to delete created diffs which will also rollback mMediaData and restore
9049 * whatever was backed up before calling this method.
9050 *
9051 * Attachments with non-normal hard disks are left as is.
9052 *
9053 * If @a aOnline is @c false then the original hard disks that require implicit
9054 * diffs will be locked for reading. Otherwise it is assumed that they are
9055 * already locked for writing (when the VM was started). Note that in the latter
9056 * case it is responsibility of the caller to lock the newly created diffs for
9057 * writing if this method succeeds.
9058 *
9059 * @param aProgress Progress object to run (must contain at least as
9060 * many operations left as the number of hard disks
9061 * attached).
9062 * @param aOnline Whether the VM was online prior to this operation.
9063 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9064 *
9065 * @note The progress object is not marked as completed, neither on success nor
9066 * on failure. This is a responsibility of the caller.
9067 *
9068 * @note Locks this object for writing.
9069 */
9070HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
9071 ULONG aWeight,
9072 bool aOnline,
9073 GuidList *pllRegistriesThatNeedSaving)
9074{
9075 LogFlowThisFunc(("aOnline=%d\n", aOnline));
9076
9077 AutoCaller autoCaller(this);
9078 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9079
9080 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9081
9082 /* must be in a protective state because we leave the lock below */
9083 AssertReturn( mData->mMachineState == MachineState_Saving
9084 || mData->mMachineState == MachineState_LiveSnapshotting
9085 || mData->mMachineState == MachineState_RestoringSnapshot
9086 || mData->mMachineState == MachineState_DeletingSnapshot
9087 , E_FAIL);
9088
9089 HRESULT rc = S_OK;
9090
9091 MediumLockListMap lockedMediaOffline;
9092 MediumLockListMap *lockedMediaMap;
9093 if (aOnline)
9094 lockedMediaMap = &mData->mSession.mLockedMedia;
9095 else
9096 lockedMediaMap = &lockedMediaOffline;
9097
9098 try
9099 {
9100 if (!aOnline)
9101 {
9102 /* lock all attached hard disks early to detect "in use"
9103 * situations before creating actual diffs */
9104 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9105 it != mMediaData->mAttachments.end();
9106 ++it)
9107 {
9108 MediumAttachment* pAtt = *it;
9109 if (pAtt->getType() == DeviceType_HardDisk)
9110 {
9111 Medium* pMedium = pAtt->getMedium();
9112 Assert(pMedium);
9113
9114 MediumLockList *pMediumLockList(new MediumLockList());
9115 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
9116 false /* fMediumLockWrite */,
9117 NULL,
9118 *pMediumLockList);
9119 if (FAILED(rc))
9120 {
9121 delete pMediumLockList;
9122 throw rc;
9123 }
9124 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
9125 if (FAILED(rc))
9126 {
9127 throw setError(rc,
9128 tr("Collecting locking information for all attached media failed"));
9129 }
9130 }
9131 }
9132
9133 /* Now lock all media. If this fails, nothing is locked. */
9134 rc = lockedMediaMap->Lock();
9135 if (FAILED(rc))
9136 {
9137 throw setError(rc,
9138 tr("Locking of attached media failed"));
9139 }
9140 }
9141
9142 /* remember the current list (note that we don't use backup() since
9143 * mMediaData may be already backed up) */
9144 MediaData::AttachmentList atts = mMediaData->mAttachments;
9145
9146 /* start from scratch */
9147 mMediaData->mAttachments.clear();
9148
9149 /* go through remembered attachments and create diffs for normal hard
9150 * disks and attach them */
9151 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9152 it != atts.end();
9153 ++it)
9154 {
9155 MediumAttachment* pAtt = *it;
9156
9157 DeviceType_T devType = pAtt->getType();
9158 Medium* pMedium = pAtt->getMedium();
9159
9160 if ( devType != DeviceType_HardDisk
9161 || pMedium == NULL
9162 || pMedium->getType() != MediumType_Normal)
9163 {
9164 /* copy the attachment as is */
9165
9166 /** @todo the progress object created in Console::TakeSnaphot
9167 * only expects operations for hard disks. Later other
9168 * device types need to show up in the progress as well. */
9169 if (devType == DeviceType_HardDisk)
9170 {
9171 if (pMedium == NULL)
9172 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9173 aWeight); // weight
9174 else
9175 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9176 pMedium->getBase()->getName().c_str()).raw(),
9177 aWeight); // weight
9178 }
9179
9180 mMediaData->mAttachments.push_back(pAtt);
9181 continue;
9182 }
9183
9184 /* need a diff */
9185 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9186 pMedium->getBase()->getName().c_str()).raw(),
9187 aWeight); // weight
9188
9189 Utf8Str strFullSnapshotFolder;
9190 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9191
9192 ComObjPtr<Medium> diff;
9193 diff.createObject();
9194 // store the diff in the same registry as the parent
9195 // (this cannot fail here because we can't create implicit diffs for
9196 // unregistered images)
9197 Guid uuidRegistryParent;
9198 bool fInRegistry = pMedium->getFirstRegistryMachineId(uuidRegistryParent);
9199 Assert(fInRegistry); NOREF(fInRegistry);
9200 rc = diff->init(mParent,
9201 pMedium->getPreferredDiffFormat(),
9202 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9203 uuidRegistryParent,
9204 pllRegistriesThatNeedSaving);
9205 if (FAILED(rc)) throw rc;
9206
9207 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9208 * the push_back? Looks like we're going to leave medium with the
9209 * wrong kind of lock (general issue with if we fail anywhere at all)
9210 * and an orphaned VDI in the snapshots folder. */
9211
9212 /* update the appropriate lock list */
9213 MediumLockList *pMediumLockList;
9214 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9215 AssertComRCThrowRC(rc);
9216 if (aOnline)
9217 {
9218 rc = pMediumLockList->Update(pMedium, false);
9219 AssertComRCThrowRC(rc);
9220 }
9221
9222 /* leave the lock before the potentially lengthy operation */
9223 alock.leave();
9224 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9225 pMediumLockList,
9226 NULL /* aProgress */,
9227 true /* aWait */,
9228 pllRegistriesThatNeedSaving);
9229 alock.enter();
9230 if (FAILED(rc)) throw rc;
9231
9232 rc = lockedMediaMap->Unlock();
9233 AssertComRCThrowRC(rc);
9234 rc = pMediumLockList->Append(diff, true);
9235 AssertComRCThrowRC(rc);
9236 rc = lockedMediaMap->Lock();
9237 AssertComRCThrowRC(rc);
9238
9239 rc = diff->addBackReference(mData->mUuid);
9240 AssertComRCThrowRC(rc);
9241
9242 /* add a new attachment */
9243 ComObjPtr<MediumAttachment> attachment;
9244 attachment.createObject();
9245 rc = attachment->init(this,
9246 diff,
9247 pAtt->getControllerName(),
9248 pAtt->getPort(),
9249 pAtt->getDevice(),
9250 DeviceType_HardDisk,
9251 true /* aImplicit */,
9252 pAtt->getBandwidthGroup());
9253 if (FAILED(rc)) throw rc;
9254
9255 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9256 AssertComRCThrowRC(rc);
9257 mMediaData->mAttachments.push_back(attachment);
9258 }
9259 }
9260 catch (HRESULT aRC) { rc = aRC; }
9261
9262 /* unlock all hard disks we locked */
9263 if (!aOnline)
9264 {
9265 ErrorInfoKeeper eik;
9266
9267 HRESULT rc1 = lockedMediaMap->Clear();
9268 AssertComRC(rc1);
9269 }
9270
9271 if (FAILED(rc))
9272 {
9273 MultiResult mrc = rc;
9274
9275 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9276 }
9277
9278 return rc;
9279}
9280
9281/**
9282 * Deletes implicit differencing hard disks created either by
9283 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
9284 *
9285 * Note that to delete hard disks created by #AttachMedium() this method is
9286 * called from #fixupMedia() when the changes are rolled back.
9287 *
9288 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9289 *
9290 * @note Locks this object for writing.
9291 */
9292HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9293{
9294 AutoCaller autoCaller(this);
9295 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9296
9297 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9298 LogFlowThisFuncEnter();
9299
9300 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9301
9302 HRESULT rc = S_OK;
9303
9304 MediaData::AttachmentList implicitAtts;
9305
9306 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9307
9308 /* enumerate new attachments */
9309 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9310 it != mMediaData->mAttachments.end();
9311 ++it)
9312 {
9313 ComObjPtr<Medium> hd = (*it)->getMedium();
9314 if (hd.isNull())
9315 continue;
9316
9317 if ((*it)->isImplicit())
9318 {
9319 /* deassociate and mark for deletion */
9320 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
9321 rc = hd->removeBackReference(mData->mUuid);
9322 AssertComRC(rc);
9323 implicitAtts.push_back(*it);
9324 continue;
9325 }
9326
9327 /* was this hard disk attached before? */
9328 if (!findAttachment(oldAtts, hd))
9329 {
9330 /* no: de-associate */
9331 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9332 rc = hd->removeBackReference(mData->mUuid);
9333 AssertComRC(rc);
9334 continue;
9335 }
9336 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9337 }
9338
9339 /* rollback hard disk changes */
9340 mMediaData.rollback();
9341
9342 MultiResult mrc(S_OK);
9343
9344 /* delete unused implicit diffs */
9345 if (implicitAtts.size() != 0)
9346 {
9347 /* will leave the lock before the potentially lengthy
9348 * operation, so protect with the special state (unless already
9349 * protected) */
9350 MachineState_T oldState = mData->mMachineState;
9351 if ( oldState != MachineState_Saving
9352 && oldState != MachineState_LiveSnapshotting
9353 && oldState != MachineState_RestoringSnapshot
9354 && oldState != MachineState_DeletingSnapshot
9355 && oldState != MachineState_DeletingSnapshotOnline
9356 && oldState != MachineState_DeletingSnapshotPaused
9357 )
9358 setMachineState(MachineState_SettingUp);
9359
9360 alock.leave();
9361
9362 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9363 it != implicitAtts.end();
9364 ++it)
9365 {
9366 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9367 ComObjPtr<Medium> hd = (*it)->getMedium();
9368
9369 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9370 pllRegistriesThatNeedSaving);
9371 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9372 mrc = rc;
9373 }
9374
9375 alock.enter();
9376
9377 if (mData->mMachineState == MachineState_SettingUp)
9378 setMachineState(oldState);
9379 }
9380
9381 return mrc;
9382}
9383
9384/**
9385 * Looks through the given list of media attachments for one with the given parameters
9386 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9387 * can be searched as well if needed.
9388 *
9389 * @param list
9390 * @param aControllerName
9391 * @param aControllerPort
9392 * @param aDevice
9393 * @return
9394 */
9395MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9396 IN_BSTR aControllerName,
9397 LONG aControllerPort,
9398 LONG aDevice)
9399{
9400 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9401 it != ll.end();
9402 ++it)
9403 {
9404 MediumAttachment *pAttach = *it;
9405 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9406 return pAttach;
9407 }
9408
9409 return NULL;
9410}
9411
9412/**
9413 * Looks through the given list of media attachments for one with the given parameters
9414 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9415 * can be searched as well if needed.
9416 *
9417 * @param list
9418 * @param aControllerName
9419 * @param aControllerPort
9420 * @param aDevice
9421 * @return
9422 */
9423MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9424 ComObjPtr<Medium> pMedium)
9425{
9426 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9427 it != ll.end();
9428 ++it)
9429 {
9430 MediumAttachment *pAttach = *it;
9431 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9432 if (pMediumThis == pMedium)
9433 return pAttach;
9434 }
9435
9436 return NULL;
9437}
9438
9439/**
9440 * Looks through the given list of media attachments for one with the given parameters
9441 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9442 * can be searched as well if needed.
9443 *
9444 * @param list
9445 * @param aControllerName
9446 * @param aControllerPort
9447 * @param aDevice
9448 * @return
9449 */
9450MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9451 Guid &id)
9452{
9453 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9454 it != ll.end();
9455 ++it)
9456 {
9457 MediumAttachment *pAttach = *it;
9458 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9459 if (pMediumThis->getId() == id)
9460 return pAttach;
9461 }
9462
9463 return NULL;
9464}
9465
9466/**
9467 * Main implementation for Machine::DetachDevice. This also gets called
9468 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9469 *
9470 * @param pAttach Medium attachment to detach.
9471 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9472 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9473 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9474 * @return
9475 */
9476HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9477 AutoWriteLock &writeLock,
9478 Snapshot *pSnapshot,
9479 GuidList *pllRegistriesThatNeedSaving)
9480{
9481 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9482 DeviceType_T mediumType = pAttach->getType();
9483
9484 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9485
9486 if (pAttach->isImplicit())
9487 {
9488 /* attempt to implicitly delete the implicitly created diff */
9489
9490 /// @todo move the implicit flag from MediumAttachment to Medium
9491 /// and forbid any hard disk operation when it is implicit. Or maybe
9492 /// a special media state for it to make it even more simple.
9493
9494 Assert(mMediaData.isBackedUp());
9495
9496 /* will leave the lock before the potentially lengthy operation, so
9497 * protect with the special state */
9498 MachineState_T oldState = mData->mMachineState;
9499 setMachineState(MachineState_SettingUp);
9500
9501 writeLock.release();
9502
9503 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
9504 true /*aWait*/,
9505 pllRegistriesThatNeedSaving);
9506
9507 writeLock.acquire();
9508
9509 setMachineState(oldState);
9510
9511 if (FAILED(rc)) return rc;
9512 }
9513
9514 setModified(IsModified_Storage);
9515 mMediaData.backup();
9516
9517 // we cannot use erase (it) below because backup() above will create
9518 // a copy of the list and make this copy active, but the iterator
9519 // still refers to the original and is not valid for the copy
9520 mMediaData->mAttachments.remove(pAttach);
9521
9522 if (!oldmedium.isNull())
9523 {
9524 // if this is from a snapshot, do not defer detachment to commitMedia()
9525 if (pSnapshot)
9526 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9527 // else if non-hard disk media, do not defer detachment to commitMedia() either
9528 else if (mediumType != DeviceType_HardDisk)
9529 oldmedium->removeBackReference(mData->mUuid);
9530 }
9531
9532 return S_OK;
9533}
9534
9535/**
9536 * Goes thru all media of the given list and
9537 *
9538 * 1) calls detachDevice() on each of them for this machine and
9539 * 2) adds all Medium objects found in the process to the given list,
9540 * depending on cleanupMode.
9541 *
9542 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
9543 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
9544 * media to the list.
9545 *
9546 * This gets called from Machine::Unregister, both for the actual Machine and
9547 * the SnapshotMachine objects that might be found in the snapshots.
9548 *
9549 * Requires caller and locking. The machine lock must be passed in because it
9550 * will be passed on to detachDevice which needs it for temporary unlocking.
9551 *
9552 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9553 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9554 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9555 * otherwise no media get added.
9556 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9557 * @return
9558 */
9559HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9560 Snapshot *pSnapshot,
9561 CleanupMode_T cleanupMode,
9562 MediaList &llMedia)
9563{
9564 Assert(isWriteLockOnCurrentThread());
9565
9566 HRESULT rc;
9567
9568 // make a temporary list because detachDevice invalidates iterators into
9569 // mMediaData->mAttachments
9570 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9571
9572 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9573 it != llAttachments2.end();
9574 ++it)
9575 {
9576 ComObjPtr<MediumAttachment> &pAttach = *it;
9577 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9578
9579 if (!pMedium.isNull())
9580 {
9581 DeviceType_T devType = pMedium->getDeviceType();
9582 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9583 && devType == DeviceType_HardDisk)
9584 || (cleanupMode == CleanupMode_Full)
9585 )
9586 llMedia.push_back(pMedium);
9587 }
9588
9589 // real machine: then we need to use the proper method
9590 rc = detachDevice(pAttach,
9591 writeLock,
9592 pSnapshot,
9593 NULL /* pfNeedsSaveSettings */);
9594
9595 if (FAILED(rc))
9596 return rc;
9597 }
9598
9599 return S_OK;
9600}
9601
9602/**
9603 * Perform deferred hard disk detachments.
9604 *
9605 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9606 * backed up).
9607 *
9608 * If @a aOnline is @c true then this method will also unlock the old hard disks
9609 * for which the new implicit diffs were created and will lock these new diffs for
9610 * writing.
9611 *
9612 * @param aOnline Whether the VM was online prior to this operation.
9613 *
9614 * @note Locks this object for writing!
9615 */
9616void Machine::commitMedia(bool aOnline /*= false*/)
9617{
9618 AutoCaller autoCaller(this);
9619 AssertComRCReturnVoid(autoCaller.rc());
9620
9621 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9622
9623 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9624
9625 HRESULT rc = S_OK;
9626
9627 /* no attach/detach operations -- nothing to do */
9628 if (!mMediaData.isBackedUp())
9629 return;
9630
9631 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9632 bool fMediaNeedsLocking = false;
9633
9634 /* enumerate new attachments */
9635 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9636 it != mMediaData->mAttachments.end();
9637 ++it)
9638 {
9639 MediumAttachment *pAttach = *it;
9640
9641 pAttach->commit();
9642
9643 Medium* pMedium = pAttach->getMedium();
9644 bool fImplicit = pAttach->isImplicit();
9645
9646 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9647 (pMedium) ? pMedium->getName().c_str() : "NULL",
9648 fImplicit));
9649
9650 /** @todo convert all this Machine-based voodoo to MediumAttachment
9651 * based commit logic. */
9652 if (fImplicit)
9653 {
9654 /* convert implicit attachment to normal */
9655 pAttach->setImplicit(false);
9656
9657 if ( aOnline
9658 && pMedium
9659 && pAttach->getType() == DeviceType_HardDisk
9660 )
9661 {
9662 ComObjPtr<Medium> parent = pMedium->getParent();
9663 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9664
9665 /* update the appropriate lock list */
9666 MediumLockList *pMediumLockList;
9667 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9668 AssertComRC(rc);
9669 if (pMediumLockList)
9670 {
9671 /* unlock if there's a need to change the locking */
9672 if (!fMediaNeedsLocking)
9673 {
9674 rc = mData->mSession.mLockedMedia.Unlock();
9675 AssertComRC(rc);
9676 fMediaNeedsLocking = true;
9677 }
9678 rc = pMediumLockList->Update(parent, false);
9679 AssertComRC(rc);
9680 rc = pMediumLockList->Append(pMedium, true);
9681 AssertComRC(rc);
9682 }
9683 }
9684
9685 continue;
9686 }
9687
9688 if (pMedium)
9689 {
9690 /* was this medium attached before? */
9691 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
9692 oldIt != oldAtts.end();
9693 ++oldIt)
9694 {
9695 MediumAttachment *pOldAttach = *oldIt;
9696 if (pOldAttach->getMedium() == pMedium)
9697 {
9698 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
9699
9700 /* yes: remove from old to avoid de-association */
9701 oldAtts.erase(oldIt);
9702 break;
9703 }
9704 }
9705 }
9706 }
9707
9708 /* enumerate remaining old attachments and de-associate from the
9709 * current machine state */
9710 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
9711 it != oldAtts.end();
9712 ++it)
9713 {
9714 MediumAttachment *pAttach = *it;
9715 Medium* pMedium = pAttach->getMedium();
9716
9717 /* Detach only hard disks, since DVD/floppy media is detached
9718 * instantly in MountMedium. */
9719 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
9720 {
9721 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
9722
9723 /* now de-associate from the current machine state */
9724 rc = pMedium->removeBackReference(mData->mUuid);
9725 AssertComRC(rc);
9726
9727 if (aOnline)
9728 {
9729 /* unlock since medium is not used anymore */
9730 MediumLockList *pMediumLockList;
9731 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9732 AssertComRC(rc);
9733 if (pMediumLockList)
9734 {
9735 rc = mData->mSession.mLockedMedia.Remove(pAttach);
9736 AssertComRC(rc);
9737 }
9738 }
9739 }
9740 }
9741
9742 /* take media locks again so that the locking state is consistent */
9743 if (fMediaNeedsLocking)
9744 {
9745 Assert(aOnline);
9746 rc = mData->mSession.mLockedMedia.Lock();
9747 AssertComRC(rc);
9748 }
9749
9750 /* commit the hard disk changes */
9751 mMediaData.commit();
9752
9753 if (isSessionMachine())
9754 {
9755 /*
9756 * Update the parent machine to point to the new owner.
9757 * This is necessary because the stored parent will point to the
9758 * session machine otherwise and cause crashes or errors later
9759 * when the session machine gets invalid.
9760 */
9761 /** @todo Change the MediumAttachment class to behave like any other
9762 * class in this regard by creating peer MediumAttachment
9763 * objects for session machines and share the data with the peer
9764 * machine.
9765 */
9766 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9767 it != mMediaData->mAttachments.end();
9768 ++it)
9769 {
9770 (*it)->updateParentMachine(mPeer);
9771 }
9772
9773 /* attach new data to the primary machine and reshare it */
9774 mPeer->mMediaData.attach(mMediaData);
9775 }
9776
9777 return;
9778}
9779
9780/**
9781 * Perform deferred deletion of implicitly created diffs.
9782 *
9783 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9784 * backed up).
9785 *
9786 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
9787 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
9788 *
9789 * @note Locks this object for writing!
9790 *
9791 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
9792 */
9793void Machine::rollbackMedia()
9794{
9795 AutoCaller autoCaller(this);
9796 AssertComRCReturnVoid (autoCaller.rc());
9797
9798 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9799
9800 LogFlowThisFunc(("Entering\n"));
9801
9802 HRESULT rc = S_OK;
9803
9804 /* no attach/detach operations -- nothing to do */
9805 if (!mMediaData.isBackedUp())
9806 return;
9807
9808 /* enumerate new attachments */
9809 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9810 it != mMediaData->mAttachments.end();
9811 ++it)
9812 {
9813 MediumAttachment *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->removeBackReference(mData->mUuid);
9821 AssertComRC(rc);
9822 }
9823 }
9824
9825 (*it)->rollback();
9826
9827 pAttach = *it;
9828 /* Fix up the backrefs for DVD/floppy media. */
9829 if (pAttach->getType() != DeviceType_HardDisk)
9830 {
9831 Medium* pMedium = pAttach->getMedium();
9832 if (pMedium)
9833 {
9834 rc = pMedium->addBackReference(mData->mUuid);
9835 AssertComRC(rc);
9836 }
9837 }
9838 }
9839
9840 /** @todo convert all this Machine-based voodoo to MediumAttachment
9841 * based rollback logic. */
9842 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9843 // which gets called if Machine::registeredInit() fails...
9844 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9845
9846 return;
9847}
9848
9849/**
9850 * Returns true if the settings file is located in the directory named exactly
9851 * as the machine; this means, among other things, that the machine directory
9852 * should be auto-renamed.
9853 *
9854 * @param aSettingsDir if not NULL, the full machine settings file directory
9855 * name will be assigned there.
9856 *
9857 * @note Doesn't lock anything.
9858 * @note Not thread safe (must be called from this object's lock).
9859 */
9860bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9861{
9862 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9863 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
9864 if (aSettingsDir)
9865 *aSettingsDir = strMachineDirName;
9866 strMachineDirName.stripPath(); // vmname
9867 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
9868 strConfigFileOnly.stripPath() // vmname.vbox
9869 .stripExt(); // vmname
9870
9871 AssertReturn(!strMachineDirName.isEmpty(), false);
9872 AssertReturn(!strConfigFileOnly.isEmpty(), false);
9873
9874 return strMachineDirName == strConfigFileOnly;
9875}
9876
9877/**
9878 * Discards all changes to machine settings.
9879 *
9880 * @param aNotify Whether to notify the direct session about changes or not.
9881 *
9882 * @note Locks objects for writing!
9883 */
9884void Machine::rollback(bool aNotify)
9885{
9886 AutoCaller autoCaller(this);
9887 AssertComRCReturn(autoCaller.rc(), (void)0);
9888
9889 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9890
9891 if (!mStorageControllers.isNull())
9892 {
9893 if (mStorageControllers.isBackedUp())
9894 {
9895 /* unitialize all new devices (absent in the backed up list). */
9896 StorageControllerList::const_iterator it = mStorageControllers->begin();
9897 StorageControllerList *backedList = mStorageControllers.backedUpData();
9898 while (it != mStorageControllers->end())
9899 {
9900 if ( std::find(backedList->begin(), backedList->end(), *it)
9901 == backedList->end()
9902 )
9903 {
9904 (*it)->uninit();
9905 }
9906 ++it;
9907 }
9908
9909 /* restore the list */
9910 mStorageControllers.rollback();
9911 }
9912
9913 /* rollback any changes to devices after restoring the list */
9914 if (mData->flModifications & IsModified_Storage)
9915 {
9916 StorageControllerList::const_iterator it = mStorageControllers->begin();
9917 while (it != mStorageControllers->end())
9918 {
9919 (*it)->rollback();
9920 ++it;
9921 }
9922 }
9923 }
9924
9925 mUserData.rollback();
9926
9927 mHWData.rollback();
9928
9929 if (mData->flModifications & IsModified_Storage)
9930 rollbackMedia();
9931
9932 if (mBIOSSettings)
9933 mBIOSSettings->rollback();
9934
9935 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
9936 mVRDEServer->rollback();
9937
9938 if (mAudioAdapter)
9939 mAudioAdapter->rollback();
9940
9941 if (mUSBController && (mData->flModifications & IsModified_USB))
9942 mUSBController->rollback();
9943
9944 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
9945 mBandwidthControl->rollback();
9946
9947 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9948 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9949 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9950
9951 if (mData->flModifications & IsModified_NetworkAdapters)
9952 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9953 if ( mNetworkAdapters[slot]
9954 && mNetworkAdapters[slot]->isModified())
9955 {
9956 mNetworkAdapters[slot]->rollback();
9957 networkAdapters[slot] = mNetworkAdapters[slot];
9958 }
9959
9960 if (mData->flModifications & IsModified_SerialPorts)
9961 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9962 if ( mSerialPorts[slot]
9963 && mSerialPorts[slot]->isModified())
9964 {
9965 mSerialPorts[slot]->rollback();
9966 serialPorts[slot] = mSerialPorts[slot];
9967 }
9968
9969 if (mData->flModifications & IsModified_ParallelPorts)
9970 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9971 if ( mParallelPorts[slot]
9972 && mParallelPorts[slot]->isModified())
9973 {
9974 mParallelPorts[slot]->rollback();
9975 parallelPorts[slot] = mParallelPorts[slot];
9976 }
9977
9978 if (aNotify)
9979 {
9980 /* inform the direct session about changes */
9981
9982 ComObjPtr<Machine> that = this;
9983 uint32_t flModifications = mData->flModifications;
9984 alock.leave();
9985
9986 if (flModifications & IsModified_SharedFolders)
9987 that->onSharedFolderChange();
9988
9989 if (flModifications & IsModified_VRDEServer)
9990 that->onVRDEServerChange(/* aRestart */ TRUE);
9991 if (flModifications & IsModified_USB)
9992 that->onUSBControllerChange();
9993
9994 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9995 if (networkAdapters[slot])
9996 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9997 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9998 if (serialPorts[slot])
9999 that->onSerialPortChange(serialPorts[slot]);
10000 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
10001 if (parallelPorts[slot])
10002 that->onParallelPortChange(parallelPorts[slot]);
10003
10004 if (flModifications & IsModified_Storage)
10005 that->onStorageControllerChange();
10006
10007#if 0
10008 if (flModifications & IsModified_BandwidthControl)
10009 that->onBandwidthControlChange();
10010#endif
10011 }
10012}
10013
10014/**
10015 * Commits all the changes to machine settings.
10016 *
10017 * Note that this operation is supposed to never fail.
10018 *
10019 * @note Locks this object and children for writing.
10020 */
10021void Machine::commit()
10022{
10023 AutoCaller autoCaller(this);
10024 AssertComRCReturnVoid(autoCaller.rc());
10025
10026 AutoCaller peerCaller(mPeer);
10027 AssertComRCReturnVoid(peerCaller.rc());
10028
10029 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
10030
10031 /*
10032 * use safe commit to ensure Snapshot machines (that share mUserData)
10033 * will still refer to a valid memory location
10034 */
10035 mUserData.commitCopy();
10036
10037 mHWData.commit();
10038
10039 if (mMediaData.isBackedUp())
10040 commitMedia();
10041
10042 mBIOSSettings->commit();
10043 mVRDEServer->commit();
10044 mAudioAdapter->commit();
10045 mUSBController->commit();
10046 mBandwidthControl->commit();
10047
10048 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10049 mNetworkAdapters[slot]->commit();
10050 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10051 mSerialPorts[slot]->commit();
10052 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10053 mParallelPorts[slot]->commit();
10054
10055 bool commitStorageControllers = false;
10056
10057 if (mStorageControllers.isBackedUp())
10058 {
10059 mStorageControllers.commit();
10060
10061 if (mPeer)
10062 {
10063 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
10064
10065 /* Commit all changes to new controllers (this will reshare data with
10066 * peers for those who have peers) */
10067 StorageControllerList *newList = new StorageControllerList();
10068 StorageControllerList::const_iterator it = mStorageControllers->begin();
10069 while (it != mStorageControllers->end())
10070 {
10071 (*it)->commit();
10072
10073 /* look if this controller has a peer device */
10074 ComObjPtr<StorageController> peer = (*it)->getPeer();
10075 if (!peer)
10076 {
10077 /* no peer means the device is a newly created one;
10078 * create a peer owning data this device share it with */
10079 peer.createObject();
10080 peer->init(mPeer, *it, true /* aReshare */);
10081 }
10082 else
10083 {
10084 /* remove peer from the old list */
10085 mPeer->mStorageControllers->remove(peer);
10086 }
10087 /* and add it to the new list */
10088 newList->push_back(peer);
10089
10090 ++it;
10091 }
10092
10093 /* uninit old peer's controllers that are left */
10094 it = mPeer->mStorageControllers->begin();
10095 while (it != mPeer->mStorageControllers->end())
10096 {
10097 (*it)->uninit();
10098 ++it;
10099 }
10100
10101 /* attach new list of controllers to our peer */
10102 mPeer->mStorageControllers.attach(newList);
10103 }
10104 else
10105 {
10106 /* we have no peer (our parent is the newly created machine);
10107 * just commit changes to devices */
10108 commitStorageControllers = true;
10109 }
10110 }
10111 else
10112 {
10113 /* the list of controllers itself is not changed,
10114 * just commit changes to controllers themselves */
10115 commitStorageControllers = true;
10116 }
10117
10118 if (commitStorageControllers)
10119 {
10120 StorageControllerList::const_iterator it = mStorageControllers->begin();
10121 while (it != mStorageControllers->end())
10122 {
10123 (*it)->commit();
10124 ++it;
10125 }
10126 }
10127
10128 if (isSessionMachine())
10129 {
10130 /* attach new data to the primary machine and reshare it */
10131 mPeer->mUserData.attach(mUserData);
10132 mPeer->mHWData.attach(mHWData);
10133 /* mMediaData is reshared by fixupMedia */
10134 // mPeer->mMediaData.attach(mMediaData);
10135 Assert(mPeer->mMediaData.data() == mMediaData.data());
10136 }
10137}
10138
10139/**
10140 * Copies all the hardware data from the given machine.
10141 *
10142 * Currently, only called when the VM is being restored from a snapshot. In
10143 * particular, this implies that the VM is not running during this method's
10144 * call.
10145 *
10146 * @note This method must be called from under this object's lock.
10147 *
10148 * @note This method doesn't call #commit(), so all data remains backed up and
10149 * unsaved.
10150 */
10151void Machine::copyFrom(Machine *aThat)
10152{
10153 AssertReturnVoid(!isSnapshotMachine());
10154 AssertReturnVoid(aThat->isSnapshotMachine());
10155
10156 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
10157
10158 mHWData.assignCopy(aThat->mHWData);
10159
10160 // create copies of all shared folders (mHWData after attaching a copy
10161 // contains just references to original objects)
10162 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10163 it != mHWData->mSharedFolders.end();
10164 ++it)
10165 {
10166 ComObjPtr<SharedFolder> folder;
10167 folder.createObject();
10168 HRESULT rc = folder->initCopy(getMachine(), *it);
10169 AssertComRC(rc);
10170 *it = folder;
10171 }
10172
10173 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
10174 mVRDEServer->copyFrom(aThat->mVRDEServer);
10175 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
10176 mUSBController->copyFrom(aThat->mUSBController);
10177 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10178
10179 /* create private copies of all controllers */
10180 mStorageControllers.backup();
10181 mStorageControllers->clear();
10182 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10183 it != aThat->mStorageControllers->end();
10184 ++it)
10185 {
10186 ComObjPtr<StorageController> ctrl;
10187 ctrl.createObject();
10188 ctrl->initCopy(this, *it);
10189 mStorageControllers->push_back(ctrl);
10190 }
10191
10192 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10193 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10194 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10195 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10196 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10197 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10198}
10199
10200/**
10201 * Returns whether the given storage controller is hotplug capable.
10202 *
10203 * @returns true if the controller supports hotplugging
10204 * false otherwise.
10205 * @param enmCtrlType The controller type to check for.
10206 */
10207bool Machine::isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
10208{
10209 switch (enmCtrlType)
10210 {
10211 case StorageControllerType_IntelAhci:
10212 return true;
10213 case StorageControllerType_LsiLogic:
10214 case StorageControllerType_LsiLogicSas:
10215 case StorageControllerType_BusLogic:
10216 case StorageControllerType_PIIX3:
10217 case StorageControllerType_PIIX4:
10218 case StorageControllerType_ICH6:
10219 case StorageControllerType_I82078:
10220 default:
10221 return false;
10222 }
10223}
10224
10225#ifdef VBOX_WITH_RESOURCE_USAGE_API
10226
10227void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10228{
10229 AssertReturnVoid(isWriteLockOnCurrentThread());
10230 AssertPtrReturnVoid(aCollector);
10231
10232 pm::CollectorHAL *hal = aCollector->getHAL();
10233 /* Create sub metrics */
10234 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10235 "Percentage of processor time spent in user mode by the VM process.");
10236 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10237 "Percentage of processor time spent in kernel mode by the VM process.");
10238 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10239 "Size of resident portion of VM process in memory.");
10240 /* Create and register base metrics */
10241 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10242 cpuLoadUser, cpuLoadKernel);
10243 aCollector->registerBaseMetric(cpuLoad);
10244 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10245 ramUsageUsed);
10246 aCollector->registerBaseMetric(ramUsage);
10247
10248 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10249 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10250 new pm::AggregateAvg()));
10251 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10252 new pm::AggregateMin()));
10253 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10254 new pm::AggregateMax()));
10255 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10256 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10257 new pm::AggregateAvg()));
10258 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10259 new pm::AggregateMin()));
10260 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10261 new pm::AggregateMax()));
10262
10263 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10264 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10265 new pm::AggregateAvg()));
10266 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10267 new pm::AggregateMin()));
10268 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10269 new pm::AggregateMax()));
10270
10271
10272 /* Guest metrics collector */
10273 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10274 aCollector->registerGuest(mCollectorGuest);
10275 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10276 this, __PRETTY_FUNCTION__, mCollectorGuest));
10277
10278 /* Create sub metrics */
10279 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10280 "Percentage of processor time spent in user mode as seen by the guest.");
10281 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10282 "Percentage of processor time spent in kernel mode as seen by the guest.");
10283 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10284 "Percentage of processor time spent idling as seen by the guest.");
10285
10286 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10287 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10288 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10289 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10290 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10291 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10292
10293 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10294
10295 /* Create and register base metrics */
10296 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10297 guestLoadUser, guestLoadKernel, guestLoadIdle);
10298 aCollector->registerBaseMetric(guestCpuLoad);
10299
10300 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10301 guestMemTotal, guestMemFree,
10302 guestMemBalloon, guestMemShared,
10303 guestMemCache, guestPagedTotal);
10304 aCollector->registerBaseMetric(guestCpuMem);
10305
10306 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10307 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10308 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10309 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
10310
10311 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
10312 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
10313 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
10314 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
10315
10316 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
10317 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
10318 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
10319 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
10320
10321 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
10322 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
10323 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
10324 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
10325
10326 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
10327 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
10328 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
10329 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
10330
10331 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
10332 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
10333 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
10334 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
10335
10336 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
10337 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
10338 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
10339 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
10340
10341 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
10342 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
10343 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
10344 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
10345
10346 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
10347 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
10348 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
10349 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
10350}
10351
10352void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
10353{
10354 AssertReturnVoid(isWriteLockOnCurrentThread());
10355
10356 if (aCollector)
10357 {
10358 aCollector->unregisterMetricsFor(aMachine);
10359 aCollector->unregisterBaseMetricsFor(aMachine);
10360 }
10361}
10362
10363#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10364
10365
10366////////////////////////////////////////////////////////////////////////////////
10367
10368DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
10369
10370HRESULT SessionMachine::FinalConstruct()
10371{
10372 LogFlowThisFunc(("\n"));
10373
10374#if defined(RT_OS_WINDOWS)
10375 mIPCSem = NULL;
10376#elif defined(RT_OS_OS2)
10377 mIPCSem = NULLHANDLE;
10378#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10379 mIPCSem = -1;
10380#else
10381# error "Port me!"
10382#endif
10383
10384 return BaseFinalConstruct();
10385}
10386
10387void SessionMachine::FinalRelease()
10388{
10389 LogFlowThisFunc(("\n"));
10390
10391 uninit(Uninit::Unexpected);
10392
10393 BaseFinalRelease();
10394}
10395
10396/**
10397 * @note Must be called only by Machine::openSession() from its own write lock.
10398 */
10399HRESULT SessionMachine::init(Machine *aMachine)
10400{
10401 LogFlowThisFuncEnter();
10402 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10403
10404 AssertReturn(aMachine, E_INVALIDARG);
10405
10406 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10407
10408 /* Enclose the state transition NotReady->InInit->Ready */
10409 AutoInitSpan autoInitSpan(this);
10410 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10411
10412 /* create the interprocess semaphore */
10413#if defined(RT_OS_WINDOWS)
10414 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10415 for (size_t i = 0; i < mIPCSemName.length(); i++)
10416 if (mIPCSemName.raw()[i] == '\\')
10417 mIPCSemName.raw()[i] = '/';
10418 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10419 ComAssertMsgRet(mIPCSem,
10420 ("Cannot create IPC mutex '%ls', err=%d",
10421 mIPCSemName.raw(), ::GetLastError()),
10422 E_FAIL);
10423#elif defined(RT_OS_OS2)
10424 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10425 aMachine->mData->mUuid.raw());
10426 mIPCSemName = ipcSem;
10427 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10428 ComAssertMsgRet(arc == NO_ERROR,
10429 ("Cannot create IPC mutex '%s', arc=%ld",
10430 ipcSem.c_str(), arc),
10431 E_FAIL);
10432#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10433# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10434# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10435 /** @todo Check that this still works correctly. */
10436 AssertCompileSize(key_t, 8);
10437# else
10438 AssertCompileSize(key_t, 4);
10439# endif
10440 key_t key;
10441 mIPCSem = -1;
10442 mIPCKey = "0";
10443 for (uint32_t i = 0; i < 1 << 24; i++)
10444 {
10445 key = ((uint32_t)'V' << 24) | i;
10446 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10447 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10448 {
10449 mIPCSem = sem;
10450 if (sem >= 0)
10451 mIPCKey = BstrFmt("%u", key);
10452 break;
10453 }
10454 }
10455# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10456 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10457 char *pszSemName = NULL;
10458 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10459 key_t key = ::ftok(pszSemName, 'V');
10460 RTStrFree(pszSemName);
10461
10462 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10463# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10464
10465 int errnoSave = errno;
10466 if (mIPCSem < 0 && errnoSave == ENOSYS)
10467 {
10468 setError(E_FAIL,
10469 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10470 "support for SysV IPC. Check the host kernel configuration for "
10471 "CONFIG_SYSVIPC=y"));
10472 return E_FAIL;
10473 }
10474 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10475 * the IPC semaphores */
10476 if (mIPCSem < 0 && errnoSave == ENOSPC)
10477 {
10478#ifdef RT_OS_LINUX
10479 setError(E_FAIL,
10480 tr("Cannot create IPC semaphore because the system limit for the "
10481 "maximum number of semaphore sets (SEMMNI), or the system wide "
10482 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10483 "current set of SysV IPC semaphores can be determined from "
10484 "the file /proc/sysvipc/sem"));
10485#else
10486 setError(E_FAIL,
10487 tr("Cannot create IPC semaphore because the system-imposed limit "
10488 "on the maximum number of allowed semaphores or semaphore "
10489 "identifiers system-wide would be exceeded"));
10490#endif
10491 return E_FAIL;
10492 }
10493 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10494 E_FAIL);
10495 /* set the initial value to 1 */
10496 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10497 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10498 E_FAIL);
10499#else
10500# error "Port me!"
10501#endif
10502
10503 /* memorize the peer Machine */
10504 unconst(mPeer) = aMachine;
10505 /* share the parent pointer */
10506 unconst(mParent) = aMachine->mParent;
10507
10508 /* take the pointers to data to share */
10509 mData.share(aMachine->mData);
10510 mSSData.share(aMachine->mSSData);
10511
10512 mUserData.share(aMachine->mUserData);
10513 mHWData.share(aMachine->mHWData);
10514 mMediaData.share(aMachine->mMediaData);
10515
10516 mStorageControllers.allocate();
10517 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10518 it != aMachine->mStorageControllers->end();
10519 ++it)
10520 {
10521 ComObjPtr<StorageController> ctl;
10522 ctl.createObject();
10523 ctl->init(this, *it);
10524 mStorageControllers->push_back(ctl);
10525 }
10526
10527 unconst(mBIOSSettings).createObject();
10528 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10529 /* create another VRDEServer object that will be mutable */
10530 unconst(mVRDEServer).createObject();
10531 mVRDEServer->init(this, aMachine->mVRDEServer);
10532 /* create another audio adapter object that will be mutable */
10533 unconst(mAudioAdapter).createObject();
10534 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10535 /* create a list of serial ports that will be mutable */
10536 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10537 {
10538 unconst(mSerialPorts[slot]).createObject();
10539 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10540 }
10541 /* create a list of parallel ports that will be mutable */
10542 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10543 {
10544 unconst(mParallelPorts[slot]).createObject();
10545 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10546 }
10547 /* create another USB controller object that will be mutable */
10548 unconst(mUSBController).createObject();
10549 mUSBController->init(this, aMachine->mUSBController);
10550
10551 /* create a list of network adapters that will be mutable */
10552 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10553 {
10554 unconst(mNetworkAdapters[slot]).createObject();
10555 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10556 }
10557
10558 /* create another bandwidth control object that will be mutable */
10559 unconst(mBandwidthControl).createObject();
10560 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10561
10562 /* default is to delete saved state on Saved -> PoweredOff transition */
10563 mRemoveSavedState = true;
10564
10565 /* Confirm a successful initialization when it's the case */
10566 autoInitSpan.setSucceeded();
10567
10568 LogFlowThisFuncLeave();
10569 return S_OK;
10570}
10571
10572/**
10573 * Uninitializes this session object. If the reason is other than
10574 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10575 *
10576 * @param aReason uninitialization reason
10577 *
10578 * @note Locks mParent + this object for writing.
10579 */
10580void SessionMachine::uninit(Uninit::Reason aReason)
10581{
10582 LogFlowThisFuncEnter();
10583 LogFlowThisFunc(("reason=%d\n", aReason));
10584
10585 /*
10586 * Strongly reference ourselves to prevent this object deletion after
10587 * mData->mSession.mMachine.setNull() below (which can release the last
10588 * reference and call the destructor). Important: this must be done before
10589 * accessing any members (and before AutoUninitSpan that does it as well).
10590 * This self reference will be released as the very last step on return.
10591 */
10592 ComObjPtr<SessionMachine> selfRef = this;
10593
10594 /* Enclose the state transition Ready->InUninit->NotReady */
10595 AutoUninitSpan autoUninitSpan(this);
10596 if (autoUninitSpan.uninitDone())
10597 {
10598 LogFlowThisFunc(("Already uninitialized\n"));
10599 LogFlowThisFuncLeave();
10600 return;
10601 }
10602
10603 if (autoUninitSpan.initFailed())
10604 {
10605 /* We've been called by init() because it's failed. It's not really
10606 * necessary (nor it's safe) to perform the regular uninit sequence
10607 * below, the following is enough.
10608 */
10609 LogFlowThisFunc(("Initialization failed.\n"));
10610#if defined(RT_OS_WINDOWS)
10611 if (mIPCSem)
10612 ::CloseHandle(mIPCSem);
10613 mIPCSem = NULL;
10614#elif defined(RT_OS_OS2)
10615 if (mIPCSem != NULLHANDLE)
10616 ::DosCloseMutexSem(mIPCSem);
10617 mIPCSem = NULLHANDLE;
10618#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10619 if (mIPCSem >= 0)
10620 ::semctl(mIPCSem, 0, IPC_RMID);
10621 mIPCSem = -1;
10622# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10623 mIPCKey = "0";
10624# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10625#else
10626# error "Port me!"
10627#endif
10628 uninitDataAndChildObjects();
10629 mData.free();
10630 unconst(mParent) = NULL;
10631 unconst(mPeer) = NULL;
10632 LogFlowThisFuncLeave();
10633 return;
10634 }
10635
10636 MachineState_T lastState;
10637 {
10638 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10639 lastState = mData->mMachineState;
10640 }
10641 NOREF(lastState);
10642
10643#ifdef VBOX_WITH_USB
10644 // release all captured USB devices, but do this before requesting the locks below
10645 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10646 {
10647 /* Console::captureUSBDevices() is called in the VM process only after
10648 * setting the machine state to Starting or Restoring.
10649 * Console::detachAllUSBDevices() will be called upon successful
10650 * termination. So, we need to release USB devices only if there was
10651 * an abnormal termination of a running VM.
10652 *
10653 * This is identical to SessionMachine::DetachAllUSBDevices except
10654 * for the aAbnormal argument. */
10655 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10656 AssertComRC(rc);
10657 NOREF(rc);
10658
10659 USBProxyService *service = mParent->host()->usbProxyService();
10660 if (service)
10661 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10662 }
10663#endif /* VBOX_WITH_USB */
10664
10665 // we need to lock this object in uninit() because the lock is shared
10666 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10667 // and others need mParent lock, and USB needs host lock.
10668 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10669
10670 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10671 this, __PRETTY_FUNCTION__, mCollectorGuest));
10672 if (mCollectorGuest)
10673 {
10674 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
10675 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
10676 mCollectorGuest = NULL;
10677 }
10678#if 0
10679 // Trigger async cleanup tasks, avoid doing things here which are not
10680 // vital to be done immediately and maybe need more locks. This calls
10681 // Machine::unregisterMetrics().
10682 mParent->onMachineUninit(mPeer);
10683#else
10684 /*
10685 * It is safe to call Machine::unregisterMetrics() here because
10686 * PerformanceCollector::samplerCallback no longer accesses guest methods
10687 * holding the lock.
10688 */
10689 unregisterMetrics(mParent->performanceCollector(), mPeer);
10690#endif
10691
10692 if (aReason == Uninit::Abnormal)
10693 {
10694 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
10695 Global::IsOnlineOrTransient(lastState)));
10696
10697 /* reset the state to Aborted */
10698 if (mData->mMachineState != MachineState_Aborted)
10699 setMachineState(MachineState_Aborted);
10700 }
10701
10702 // any machine settings modified?
10703 if (mData->flModifications)
10704 {
10705 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
10706 rollback(false /* aNotify */);
10707 }
10708
10709 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
10710 || !mConsoleTaskData.mSnapshot);
10711 if (!mConsoleTaskData.strStateFilePath.isEmpty())
10712 {
10713 LogWarningThisFunc(("canceling failed save state request!\n"));
10714 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
10715 }
10716 else if (!mConsoleTaskData.mSnapshot.isNull())
10717 {
10718 LogWarningThisFunc(("canceling untaken snapshot!\n"));
10719
10720 /* delete all differencing hard disks created (this will also attach
10721 * their parents back by rolling back mMediaData) */
10722 rollbackMedia();
10723
10724 // delete the saved state file (it might have been already created)
10725 // AFTER killing the snapshot so that releaseSavedStateFile() won't
10726 // think it's still in use
10727 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
10728 mConsoleTaskData.mSnapshot->uninit();
10729 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
10730 }
10731
10732 if (!mData->mSession.mType.isEmpty())
10733 {
10734 /* mType is not null when this machine's process has been started by
10735 * Machine::LaunchVMProcess(), therefore it is our child. We
10736 * need to queue the PID to reap the process (and avoid zombies on
10737 * Linux). */
10738 Assert(mData->mSession.mPid != NIL_RTPROCESS);
10739 mParent->addProcessToReap(mData->mSession.mPid);
10740 }
10741
10742 mData->mSession.mPid = NIL_RTPROCESS;
10743
10744 if (aReason == Uninit::Unexpected)
10745 {
10746 /* Uninitialization didn't come from #checkForDeath(), so tell the
10747 * client watcher thread to update the set of machines that have open
10748 * sessions. */
10749 mParent->updateClientWatcher();
10750 }
10751
10752 /* uninitialize all remote controls */
10753 if (mData->mSession.mRemoteControls.size())
10754 {
10755 LogFlowThisFunc(("Closing remote sessions (%d):\n",
10756 mData->mSession.mRemoteControls.size()));
10757
10758 Data::Session::RemoteControlList::iterator it =
10759 mData->mSession.mRemoteControls.begin();
10760 while (it != mData->mSession.mRemoteControls.end())
10761 {
10762 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
10763 HRESULT rc = (*it)->Uninitialize();
10764 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
10765 if (FAILED(rc))
10766 LogWarningThisFunc(("Forgot to close the remote session?\n"));
10767 ++it;
10768 }
10769 mData->mSession.mRemoteControls.clear();
10770 }
10771
10772 /*
10773 * An expected uninitialization can come only from #checkForDeath().
10774 * Otherwise it means that something's gone really wrong (for example,
10775 * the Session implementation has released the VirtualBox reference
10776 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
10777 * etc). However, it's also possible, that the client releases the IPC
10778 * semaphore correctly (i.e. before it releases the VirtualBox reference),
10779 * but the VirtualBox release event comes first to the server process.
10780 * This case is practically possible, so we should not assert on an
10781 * unexpected uninit, just log a warning.
10782 */
10783
10784 if ((aReason == Uninit::Unexpected))
10785 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
10786
10787 if (aReason != Uninit::Normal)
10788 {
10789 mData->mSession.mDirectControl.setNull();
10790 }
10791 else
10792 {
10793 /* this must be null here (see #OnSessionEnd()) */
10794 Assert(mData->mSession.mDirectControl.isNull());
10795 Assert(mData->mSession.mState == SessionState_Unlocking);
10796 Assert(!mData->mSession.mProgress.isNull());
10797 }
10798 if (mData->mSession.mProgress)
10799 {
10800 if (aReason == Uninit::Normal)
10801 mData->mSession.mProgress->notifyComplete(S_OK);
10802 else
10803 mData->mSession.mProgress->notifyComplete(E_FAIL,
10804 COM_IIDOF(ISession),
10805 getComponentName(),
10806 tr("The VM session was aborted"));
10807 mData->mSession.mProgress.setNull();
10808 }
10809
10810 /* remove the association between the peer machine and this session machine */
10811 Assert( (SessionMachine*)mData->mSession.mMachine == this
10812 || aReason == Uninit::Unexpected);
10813
10814 /* reset the rest of session data */
10815 mData->mSession.mMachine.setNull();
10816 mData->mSession.mState = SessionState_Unlocked;
10817 mData->mSession.mType.setNull();
10818
10819 /* close the interprocess semaphore before leaving the exclusive lock */
10820#if defined(RT_OS_WINDOWS)
10821 if (mIPCSem)
10822 ::CloseHandle(mIPCSem);
10823 mIPCSem = NULL;
10824#elif defined(RT_OS_OS2)
10825 if (mIPCSem != NULLHANDLE)
10826 ::DosCloseMutexSem(mIPCSem);
10827 mIPCSem = NULLHANDLE;
10828#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10829 if (mIPCSem >= 0)
10830 ::semctl(mIPCSem, 0, IPC_RMID);
10831 mIPCSem = -1;
10832# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10833 mIPCKey = "0";
10834# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10835#else
10836# error "Port me!"
10837#endif
10838
10839 /* fire an event */
10840 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
10841
10842 uninitDataAndChildObjects();
10843
10844 /* free the essential data structure last */
10845 mData.free();
10846
10847#if 1 /** @todo Please review this change! (bird) */
10848 /* drop the exclusive lock before setting the below two to NULL */
10849 multilock.release();
10850#else
10851 /* leave the exclusive lock before setting the below two to NULL */
10852 multilock.leave();
10853#endif
10854
10855 unconst(mParent) = NULL;
10856 unconst(mPeer) = NULL;
10857
10858 LogFlowThisFuncLeave();
10859}
10860
10861// util::Lockable interface
10862////////////////////////////////////////////////////////////////////////////////
10863
10864/**
10865 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10866 * with the primary Machine instance (mPeer).
10867 */
10868RWLockHandle *SessionMachine::lockHandle() const
10869{
10870 AssertReturn(mPeer != NULL, NULL);
10871 return mPeer->lockHandle();
10872}
10873
10874// IInternalMachineControl methods
10875////////////////////////////////////////////////////////////////////////////////
10876
10877/**
10878 * @note Locks this object for writing.
10879 */
10880STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
10881{
10882 AutoCaller autoCaller(this);
10883 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10884
10885 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10886
10887 mRemoveSavedState = aRemove;
10888
10889 return S_OK;
10890}
10891
10892/**
10893 * @note Locks the same as #setMachineState() does.
10894 */
10895STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10896{
10897 return setMachineState(aMachineState);
10898}
10899
10900/**
10901 * @note Locks this object for reading.
10902 */
10903STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10904{
10905 AutoCaller autoCaller(this);
10906 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10907
10908 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10909
10910#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10911 mIPCSemName.cloneTo(aId);
10912 return S_OK;
10913#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10914# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10915 mIPCKey.cloneTo(aId);
10916# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10917 mData->m_strConfigFileFull.cloneTo(aId);
10918# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10919 return S_OK;
10920#else
10921# error "Port me!"
10922#endif
10923}
10924
10925/**
10926 * @note Locks this object for writing.
10927 */
10928STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10929{
10930 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10931 AutoCaller autoCaller(this);
10932 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10933
10934 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10935
10936 if (mData->mSession.mState != SessionState_Locked)
10937 return VBOX_E_INVALID_OBJECT_STATE;
10938
10939 if (!mData->mSession.mProgress.isNull())
10940 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10941
10942 LogFlowThisFunc(("returns S_OK.\n"));
10943 return S_OK;
10944}
10945
10946/**
10947 * @note Locks this object for writing.
10948 */
10949STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10950{
10951 AutoCaller autoCaller(this);
10952 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10953
10954 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10955
10956 if (mData->mSession.mState != SessionState_Locked)
10957 return VBOX_E_INVALID_OBJECT_STATE;
10958
10959 /* Finalize the LaunchVMProcess progress object. */
10960 if (mData->mSession.mProgress)
10961 {
10962 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10963 mData->mSession.mProgress.setNull();
10964 }
10965
10966 if (SUCCEEDED((HRESULT)iResult))
10967 {
10968#ifdef VBOX_WITH_RESOURCE_USAGE_API
10969 /* The VM has been powered up successfully, so it makes sense
10970 * now to offer the performance metrics for a running machine
10971 * object. Doing it earlier wouldn't be safe. */
10972 registerMetrics(mParent->performanceCollector(), mPeer,
10973 mData->mSession.mPid);
10974#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10975 }
10976
10977 return S_OK;
10978}
10979
10980/**
10981 * @note Locks this object for writing.
10982 */
10983STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
10984{
10985 LogFlowThisFuncEnter();
10986
10987 CheckComArgOutPointerValid(aProgress);
10988
10989 AutoCaller autoCaller(this);
10990 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10991
10992 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10993
10994 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
10995 E_FAIL);
10996
10997 /* create a progress object to track operation completion */
10998 ComObjPtr<Progress> pProgress;
10999 pProgress.createObject();
11000 pProgress->init(getVirtualBox(),
11001 static_cast<IMachine *>(this) /* aInitiator */,
11002 Bstr(tr("Stopping the virtual machine")).raw(),
11003 FALSE /* aCancelable */);
11004
11005 /* fill in the console task data */
11006 mConsoleTaskData.mLastState = mData->mMachineState;
11007 mConsoleTaskData.mProgress = pProgress;
11008
11009 /* set the state to Stopping (this is expected by Console::PowerDown()) */
11010 setMachineState(MachineState_Stopping);
11011
11012 pProgress.queryInterfaceTo(aProgress);
11013
11014 return S_OK;
11015}
11016
11017/**
11018 * @note Locks this object for writing.
11019 */
11020STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
11021{
11022 LogFlowThisFuncEnter();
11023
11024 AutoCaller autoCaller(this);
11025 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11026
11027 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11028
11029 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
11030 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
11031 && mConsoleTaskData.mLastState != MachineState_Null,
11032 E_FAIL);
11033
11034 /*
11035 * On failure, set the state to the state we had when BeginPoweringDown()
11036 * was called (this is expected by Console::PowerDown() and the associated
11037 * task). On success the VM process already changed the state to
11038 * MachineState_PoweredOff, so no need to do anything.
11039 */
11040 if (FAILED(iResult))
11041 setMachineState(mConsoleTaskData.mLastState);
11042
11043 /* notify the progress object about operation completion */
11044 Assert(mConsoleTaskData.mProgress);
11045 if (SUCCEEDED(iResult))
11046 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11047 else
11048 {
11049 Utf8Str strErrMsg(aErrMsg);
11050 if (strErrMsg.length())
11051 mConsoleTaskData.mProgress->notifyComplete(iResult,
11052 COM_IIDOF(ISession),
11053 getComponentName(),
11054 strErrMsg.c_str());
11055 else
11056 mConsoleTaskData.mProgress->notifyComplete(iResult);
11057 }
11058
11059 /* clear out the temporary saved state data */
11060 mConsoleTaskData.mLastState = MachineState_Null;
11061 mConsoleTaskData.mProgress.setNull();
11062
11063 LogFlowThisFuncLeave();
11064 return S_OK;
11065}
11066
11067
11068/**
11069 * Goes through the USB filters of the given machine to see if the given
11070 * device matches any filter or not.
11071 *
11072 * @note Locks the same as USBController::hasMatchingFilter() does.
11073 */
11074STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
11075 BOOL *aMatched,
11076 ULONG *aMaskedIfs)
11077{
11078 LogFlowThisFunc(("\n"));
11079
11080 CheckComArgNotNull(aUSBDevice);
11081 CheckComArgOutPointerValid(aMatched);
11082
11083 AutoCaller autoCaller(this);
11084 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11085
11086#ifdef VBOX_WITH_USB
11087 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
11088#else
11089 NOREF(aUSBDevice);
11090 NOREF(aMaskedIfs);
11091 *aMatched = FALSE;
11092#endif
11093
11094 return S_OK;
11095}
11096
11097/**
11098 * @note Locks the same as Host::captureUSBDevice() does.
11099 */
11100STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
11101{
11102 LogFlowThisFunc(("\n"));
11103
11104 AutoCaller autoCaller(this);
11105 AssertComRCReturnRC(autoCaller.rc());
11106
11107#ifdef VBOX_WITH_USB
11108 /* if captureDeviceForVM() fails, it must have set extended error info */
11109 clearError();
11110 MultiResult rc = mParent->host()->checkUSBProxyService();
11111 if (FAILED(rc)) return rc;
11112
11113 USBProxyService *service = mParent->host()->usbProxyService();
11114 AssertReturn(service, E_FAIL);
11115 return service->captureDeviceForVM(this, Guid(aId).ref());
11116#else
11117 NOREF(aId);
11118 return E_NOTIMPL;
11119#endif
11120}
11121
11122/**
11123 * @note Locks the same as Host::detachUSBDevice() does.
11124 */
11125STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
11126{
11127 LogFlowThisFunc(("\n"));
11128
11129 AutoCaller autoCaller(this);
11130 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11131
11132#ifdef VBOX_WITH_USB
11133 USBProxyService *service = mParent->host()->usbProxyService();
11134 AssertReturn(service, E_FAIL);
11135 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
11136#else
11137 NOREF(aId);
11138 NOREF(aDone);
11139 return E_NOTIMPL;
11140#endif
11141}
11142
11143/**
11144 * Inserts all machine filters to the USB proxy service and then calls
11145 * Host::autoCaptureUSBDevices().
11146 *
11147 * Called by Console from the VM process upon VM startup.
11148 *
11149 * @note Locks what called methods lock.
11150 */
11151STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
11152{
11153 LogFlowThisFunc(("\n"));
11154
11155 AutoCaller autoCaller(this);
11156 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11157
11158#ifdef VBOX_WITH_USB
11159 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
11160 AssertComRC(rc);
11161 NOREF(rc);
11162
11163 USBProxyService *service = mParent->host()->usbProxyService();
11164 AssertReturn(service, E_FAIL);
11165 return service->autoCaptureDevicesForVM(this);
11166#else
11167 return S_OK;
11168#endif
11169}
11170
11171/**
11172 * Removes all machine filters from the USB proxy service and then calls
11173 * Host::detachAllUSBDevices().
11174 *
11175 * Called by Console from the VM process upon normal VM termination or by
11176 * SessionMachine::uninit() upon abnormal VM termination (from under the
11177 * Machine/SessionMachine lock).
11178 *
11179 * @note Locks what called methods lock.
11180 */
11181STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
11182{
11183 LogFlowThisFunc(("\n"));
11184
11185 AutoCaller autoCaller(this);
11186 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11187
11188#ifdef VBOX_WITH_USB
11189 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11190 AssertComRC(rc);
11191 NOREF(rc);
11192
11193 USBProxyService *service = mParent->host()->usbProxyService();
11194 AssertReturn(service, E_FAIL);
11195 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
11196#else
11197 NOREF(aDone);
11198 return S_OK;
11199#endif
11200}
11201
11202/**
11203 * @note Locks this object for writing.
11204 */
11205STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
11206 IProgress **aProgress)
11207{
11208 LogFlowThisFuncEnter();
11209
11210 AssertReturn(aSession, E_INVALIDARG);
11211 AssertReturn(aProgress, E_INVALIDARG);
11212
11213 AutoCaller autoCaller(this);
11214
11215 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11216 /*
11217 * We don't assert below because it might happen that a non-direct session
11218 * informs us it is closed right after we've been uninitialized -- it's ok.
11219 */
11220 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11221
11222 /* get IInternalSessionControl interface */
11223 ComPtr<IInternalSessionControl> control(aSession);
11224
11225 ComAssertRet(!control.isNull(), E_INVALIDARG);
11226
11227 /* Creating a Progress object requires the VirtualBox lock, and
11228 * thus locking it here is required by the lock order rules. */
11229 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
11230
11231 if (control == mData->mSession.mDirectControl)
11232 {
11233 ComAssertRet(aProgress, E_POINTER);
11234
11235 /* The direct session is being normally closed by the client process
11236 * ----------------------------------------------------------------- */
11237
11238 /* go to the closing state (essential for all open*Session() calls and
11239 * for #checkForDeath()) */
11240 Assert(mData->mSession.mState == SessionState_Locked);
11241 mData->mSession.mState = SessionState_Unlocking;
11242
11243 /* set direct control to NULL to release the remote instance */
11244 mData->mSession.mDirectControl.setNull();
11245 LogFlowThisFunc(("Direct control is set to NULL\n"));
11246
11247 if (mData->mSession.mProgress)
11248 {
11249 /* finalize the progress, someone might wait if a frontend
11250 * closes the session before powering on the VM. */
11251 mData->mSession.mProgress->notifyComplete(E_FAIL,
11252 COM_IIDOF(ISession),
11253 getComponentName(),
11254 tr("The VM session was closed before any attempt to power it on"));
11255 mData->mSession.mProgress.setNull();
11256 }
11257
11258 /* Create the progress object the client will use to wait until
11259 * #checkForDeath() is called to uninitialize this session object after
11260 * it releases the IPC semaphore.
11261 * Note! Because we're "reusing" mProgress here, this must be a proxy
11262 * object just like for LaunchVMProcess. */
11263 Assert(mData->mSession.mProgress.isNull());
11264 ComObjPtr<ProgressProxy> progress;
11265 progress.createObject();
11266 ComPtr<IUnknown> pPeer(mPeer);
11267 progress->init(mParent, pPeer,
11268 Bstr(tr("Closing session")).raw(),
11269 FALSE /* aCancelable */);
11270 progress.queryInterfaceTo(aProgress);
11271 mData->mSession.mProgress = progress;
11272 }
11273 else
11274 {
11275 /* the remote session is being normally closed */
11276 Data::Session::RemoteControlList::iterator it =
11277 mData->mSession.mRemoteControls.begin();
11278 while (it != mData->mSession.mRemoteControls.end())
11279 {
11280 if (control == *it)
11281 break;
11282 ++it;
11283 }
11284 BOOL found = it != mData->mSession.mRemoteControls.end();
11285 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11286 E_INVALIDARG);
11287 mData->mSession.mRemoteControls.remove(*it);
11288 }
11289
11290 LogFlowThisFuncLeave();
11291 return S_OK;
11292}
11293
11294/**
11295 * @note Locks this object for writing.
11296 */
11297STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11298{
11299 LogFlowThisFuncEnter();
11300
11301 CheckComArgOutPointerValid(aProgress);
11302 CheckComArgOutPointerValid(aStateFilePath);
11303
11304 AutoCaller autoCaller(this);
11305 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11306
11307 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11308
11309 AssertReturn( mData->mMachineState == MachineState_Paused
11310 && mConsoleTaskData.mLastState == MachineState_Null
11311 && mConsoleTaskData.strStateFilePath.isEmpty(),
11312 E_FAIL);
11313
11314 /* create a progress object to track operation completion */
11315 ComObjPtr<Progress> pProgress;
11316 pProgress.createObject();
11317 pProgress->init(getVirtualBox(),
11318 static_cast<IMachine *>(this) /* aInitiator */,
11319 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
11320 FALSE /* aCancelable */);
11321
11322 Utf8Str strStateFilePath;
11323 /* stateFilePath is null when the machine is not running */
11324 if (mData->mMachineState == MachineState_Paused)
11325 composeSavedStateFilename(strStateFilePath);
11326
11327 /* fill in the console task data */
11328 mConsoleTaskData.mLastState = mData->mMachineState;
11329 mConsoleTaskData.strStateFilePath = strStateFilePath;
11330 mConsoleTaskData.mProgress = pProgress;
11331
11332 /* set the state to Saving (this is expected by Console::SaveState()) */
11333 setMachineState(MachineState_Saving);
11334
11335 strStateFilePath.cloneTo(aStateFilePath);
11336 pProgress.queryInterfaceTo(aProgress);
11337
11338 return S_OK;
11339}
11340
11341/**
11342 * @note Locks mParent + this object for writing.
11343 */
11344STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
11345{
11346 LogFlowThisFunc(("\n"));
11347
11348 AutoCaller autoCaller(this);
11349 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11350
11351 /* endSavingState() need mParent lock */
11352 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11353
11354 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
11355 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
11356 && mConsoleTaskData.mLastState != MachineState_Null
11357 && !mConsoleTaskData.strStateFilePath.isEmpty(),
11358 E_FAIL);
11359
11360 /*
11361 * On failure, set the state to the state we had when BeginSavingState()
11362 * was called (this is expected by Console::SaveState() and the associated
11363 * task). On success the VM process already changed the state to
11364 * MachineState_Saved, so no need to do anything.
11365 */
11366 if (FAILED(iResult))
11367 setMachineState(mConsoleTaskData.mLastState);
11368
11369 return endSavingState(iResult, aErrMsg);
11370}
11371
11372/**
11373 * @note Locks this object for writing.
11374 */
11375STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
11376{
11377 LogFlowThisFunc(("\n"));
11378
11379 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
11380
11381 AutoCaller autoCaller(this);
11382 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11383
11384 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11385
11386 AssertReturn( mData->mMachineState == MachineState_PoweredOff
11387 || mData->mMachineState == MachineState_Teleported
11388 || mData->mMachineState == MachineState_Aborted
11389 , E_FAIL); /** @todo setError. */
11390
11391 Utf8Str stateFilePathFull = aSavedStateFile;
11392 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
11393 if (RT_FAILURE(vrc))
11394 return setError(VBOX_E_FILE_ERROR,
11395 tr("Invalid saved state file path '%ls' (%Rrc)"),
11396 aSavedStateFile,
11397 vrc);
11398
11399 mSSData->strStateFilePath = stateFilePathFull;
11400
11401 /* The below setMachineState() will detect the state transition and will
11402 * update the settings file */
11403
11404 return setMachineState(MachineState_Saved);
11405}
11406
11407STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
11408 ComSafeArrayOut(BSTR, aValues),
11409 ComSafeArrayOut(LONG64, aTimestamps),
11410 ComSafeArrayOut(BSTR, aFlags))
11411{
11412 LogFlowThisFunc(("\n"));
11413
11414#ifdef VBOX_WITH_GUEST_PROPS
11415 using namespace guestProp;
11416
11417 AutoCaller autoCaller(this);
11418 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11419
11420 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11421
11422 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
11423 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
11424 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
11425 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
11426
11427 size_t cEntries = mHWData->mGuestProperties.size();
11428 com::SafeArray<BSTR> names(cEntries);
11429 com::SafeArray<BSTR> values(cEntries);
11430 com::SafeArray<LONG64> timestamps(cEntries);
11431 com::SafeArray<BSTR> flags(cEntries);
11432 unsigned i = 0;
11433 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
11434 it != mHWData->mGuestProperties.end();
11435 ++it)
11436 {
11437 char szFlags[MAX_FLAGS_LEN + 1];
11438 it->strName.cloneTo(&names[i]);
11439 it->strValue.cloneTo(&values[i]);
11440 timestamps[i] = it->mTimestamp;
11441 /* If it is NULL, keep it NULL. */
11442 if (it->mFlags)
11443 {
11444 writeFlags(it->mFlags, szFlags);
11445 Bstr(szFlags).cloneTo(&flags[i]);
11446 }
11447 else
11448 flags[i] = NULL;
11449 ++i;
11450 }
11451 names.detachTo(ComSafeArrayOutArg(aNames));
11452 values.detachTo(ComSafeArrayOutArg(aValues));
11453 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11454 flags.detachTo(ComSafeArrayOutArg(aFlags));
11455 return S_OK;
11456#else
11457 ReturnComNotImplemented();
11458#endif
11459}
11460
11461STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11462 IN_BSTR aValue,
11463 LONG64 aTimestamp,
11464 IN_BSTR aFlags)
11465{
11466 LogFlowThisFunc(("\n"));
11467
11468#ifdef VBOX_WITH_GUEST_PROPS
11469 using namespace guestProp;
11470
11471 CheckComArgStrNotEmptyOrNull(aName);
11472 CheckComArgMaybeNull(aValue);
11473 CheckComArgMaybeNull(aFlags);
11474
11475 try
11476 {
11477 /*
11478 * Convert input up front.
11479 */
11480 Utf8Str utf8Name(aName);
11481 uint32_t fFlags = NILFLAG;
11482 if (aFlags)
11483 {
11484 Utf8Str utf8Flags(aFlags);
11485 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11486 AssertRCReturn(vrc, E_INVALIDARG);
11487 }
11488
11489 /*
11490 * Now grab the object lock, validate the state and do the update.
11491 */
11492 AutoCaller autoCaller(this);
11493 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11494
11495 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11496
11497 switch (mData->mMachineState)
11498 {
11499 case MachineState_Paused:
11500 case MachineState_Running:
11501 case MachineState_Teleporting:
11502 case MachineState_TeleportingPausedVM:
11503 case MachineState_LiveSnapshotting:
11504 case MachineState_DeletingSnapshotOnline:
11505 case MachineState_DeletingSnapshotPaused:
11506 case MachineState_Saving:
11507 break;
11508
11509 default:
11510#ifndef DEBUG_sunlover
11511 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11512 VBOX_E_INVALID_VM_STATE);
11513#else
11514 return VBOX_E_INVALID_VM_STATE;
11515#endif
11516 }
11517
11518 setModified(IsModified_MachineData);
11519 mHWData.backup();
11520
11521 /** @todo r=bird: The careful memory handling doesn't work out here because
11522 * the catch block won't undo any damage we've done. So, if push_back throws
11523 * bad_alloc then you've lost the value.
11524 *
11525 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11526 * since values that changes actually bubbles to the end of the list. Using
11527 * something that has an efficient lookup and can tolerate a bit of updates
11528 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11529 * combination of RTStrCache (for sharing names and getting uniqueness into
11530 * the bargain) and hash/tree is another. */
11531 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11532 iter != mHWData->mGuestProperties.end();
11533 ++iter)
11534 if (utf8Name == iter->strName)
11535 {
11536 mHWData->mGuestProperties.erase(iter);
11537 mData->mGuestPropertiesModified = TRUE;
11538 break;
11539 }
11540 if (aValue != NULL)
11541 {
11542 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11543 mHWData->mGuestProperties.push_back(property);
11544 mData->mGuestPropertiesModified = TRUE;
11545 }
11546
11547 /*
11548 * Send a callback notification if appropriate
11549 */
11550 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11551 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11552 RTSTR_MAX,
11553 utf8Name.c_str(),
11554 RTSTR_MAX, NULL)
11555 )
11556 {
11557 alock.leave();
11558
11559 mParent->onGuestPropertyChange(mData->mUuid,
11560 aName,
11561 aValue,
11562 aFlags);
11563 }
11564 }
11565 catch (...)
11566 {
11567 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11568 }
11569 return S_OK;
11570#else
11571 ReturnComNotImplemented();
11572#endif
11573}
11574
11575// public methods only for internal purposes
11576/////////////////////////////////////////////////////////////////////////////
11577
11578/**
11579 * Called from the client watcher thread to check for expected or unexpected
11580 * death of the client process that has a direct session to this machine.
11581 *
11582 * On Win32 and on OS/2, this method is called only when we've got the
11583 * mutex (i.e. the client has either died or terminated normally) so it always
11584 * returns @c true (the client is terminated, the session machine is
11585 * uninitialized).
11586 *
11587 * On other platforms, the method returns @c true if the client process has
11588 * terminated normally or abnormally and the session machine was uninitialized,
11589 * and @c false if the client process is still alive.
11590 *
11591 * @note Locks this object for writing.
11592 */
11593bool SessionMachine::checkForDeath()
11594{
11595 Uninit::Reason reason;
11596 bool terminated = false;
11597
11598 /* Enclose autoCaller with a block because calling uninit() from under it
11599 * will deadlock. */
11600 {
11601 AutoCaller autoCaller(this);
11602 if (!autoCaller.isOk())
11603 {
11604 /* return true if not ready, to cause the client watcher to exclude
11605 * the corresponding session from watching */
11606 LogFlowThisFunc(("Already uninitialized!\n"));
11607 return true;
11608 }
11609
11610 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11611
11612 /* Determine the reason of death: if the session state is Closing here,
11613 * everything is fine. Otherwise it means that the client did not call
11614 * OnSessionEnd() before it released the IPC semaphore. This may happen
11615 * either because the client process has abnormally terminated, or
11616 * because it simply forgot to call ISession::Close() before exiting. We
11617 * threat the latter also as an abnormal termination (see
11618 * Session::uninit() for details). */
11619 reason = mData->mSession.mState == SessionState_Unlocking ?
11620 Uninit::Normal :
11621 Uninit::Abnormal;
11622
11623#if defined(RT_OS_WINDOWS)
11624
11625 AssertMsg(mIPCSem, ("semaphore must be created"));
11626
11627 /* release the IPC mutex */
11628 ::ReleaseMutex(mIPCSem);
11629
11630 terminated = true;
11631
11632#elif defined(RT_OS_OS2)
11633
11634 AssertMsg(mIPCSem, ("semaphore must be created"));
11635
11636 /* release the IPC mutex */
11637 ::DosReleaseMutexSem(mIPCSem);
11638
11639 terminated = true;
11640
11641#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11642
11643 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
11644
11645 int val = ::semctl(mIPCSem, 0, GETVAL);
11646 if (val > 0)
11647 {
11648 /* the semaphore is signaled, meaning the session is terminated */
11649 terminated = true;
11650 }
11651
11652#else
11653# error "Port me!"
11654#endif
11655
11656 } /* AutoCaller block */
11657
11658 if (terminated)
11659 uninit(reason);
11660
11661 return terminated;
11662}
11663
11664/**
11665 * @note Locks this object for reading.
11666 */
11667HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
11668{
11669 LogFlowThisFunc(("\n"));
11670
11671 AutoCaller autoCaller(this);
11672 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11673
11674 ComPtr<IInternalSessionControl> directControl;
11675 {
11676 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11677 directControl = mData->mSession.mDirectControl;
11678 }
11679
11680 /* ignore notifications sent after #OnSessionEnd() is called */
11681 if (!directControl)
11682 return S_OK;
11683
11684 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
11685}
11686
11687/**
11688 * @note Locks this object for reading.
11689 */
11690HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
11691 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
11692{
11693 LogFlowThisFunc(("\n"));
11694
11695 AutoCaller autoCaller(this);
11696 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11697
11698 ComPtr<IInternalSessionControl> directControl;
11699 {
11700 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11701 directControl = mData->mSession.mDirectControl;
11702 }
11703
11704 /* ignore notifications sent after #OnSessionEnd() is called */
11705 if (!directControl)
11706 return S_OK;
11707 /*
11708 * instead acting like callback we ask IVirtualBox deliver corresponding event
11709 */
11710
11711 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
11712 return S_OK;
11713}
11714
11715/**
11716 * @note Locks this object for reading.
11717 */
11718HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
11719{
11720 LogFlowThisFunc(("\n"));
11721
11722 AutoCaller autoCaller(this);
11723 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11724
11725 ComPtr<IInternalSessionControl> directControl;
11726 {
11727 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11728 directControl = mData->mSession.mDirectControl;
11729 }
11730
11731 /* ignore notifications sent after #OnSessionEnd() is called */
11732 if (!directControl)
11733 return S_OK;
11734
11735 return directControl->OnSerialPortChange(serialPort);
11736}
11737
11738/**
11739 * @note Locks this object for reading.
11740 */
11741HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
11742{
11743 LogFlowThisFunc(("\n"));
11744
11745 AutoCaller autoCaller(this);
11746 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11747
11748 ComPtr<IInternalSessionControl> directControl;
11749 {
11750 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11751 directControl = mData->mSession.mDirectControl;
11752 }
11753
11754 /* ignore notifications sent after #OnSessionEnd() is called */
11755 if (!directControl)
11756 return S_OK;
11757
11758 return directControl->OnParallelPortChange(parallelPort);
11759}
11760
11761/**
11762 * @note Locks this object for reading.
11763 */
11764HRESULT SessionMachine::onStorageControllerChange()
11765{
11766 LogFlowThisFunc(("\n"));
11767
11768 AutoCaller autoCaller(this);
11769 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11770
11771 ComPtr<IInternalSessionControl> directControl;
11772 {
11773 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11774 directControl = mData->mSession.mDirectControl;
11775 }
11776
11777 /* ignore notifications sent after #OnSessionEnd() is called */
11778 if (!directControl)
11779 return S_OK;
11780
11781 return directControl->OnStorageControllerChange();
11782}
11783
11784/**
11785 * @note Locks this object for reading.
11786 */
11787HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
11788{
11789 LogFlowThisFunc(("\n"));
11790
11791 AutoCaller autoCaller(this);
11792 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11793
11794 ComPtr<IInternalSessionControl> directControl;
11795 {
11796 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11797 directControl = mData->mSession.mDirectControl;
11798 }
11799
11800 /* ignore notifications sent after #OnSessionEnd() is called */
11801 if (!directControl)
11802 return S_OK;
11803
11804 return directControl->OnMediumChange(aAttachment, aForce);
11805}
11806
11807/**
11808 * @note Locks this object for reading.
11809 */
11810HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
11811{
11812 LogFlowThisFunc(("\n"));
11813
11814 AutoCaller autoCaller(this);
11815 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11816
11817 ComPtr<IInternalSessionControl> directControl;
11818 {
11819 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11820 directControl = mData->mSession.mDirectControl;
11821 }
11822
11823 /* ignore notifications sent after #OnSessionEnd() is called */
11824 if (!directControl)
11825 return S_OK;
11826
11827 return directControl->OnCPUChange(aCPU, aRemove);
11828}
11829
11830HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
11831{
11832 LogFlowThisFunc(("\n"));
11833
11834 AutoCaller autoCaller(this);
11835 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11836
11837 ComPtr<IInternalSessionControl> directControl;
11838 {
11839 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11840 directControl = mData->mSession.mDirectControl;
11841 }
11842
11843 /* ignore notifications sent after #OnSessionEnd() is called */
11844 if (!directControl)
11845 return S_OK;
11846
11847 return directControl->OnCPUExecutionCapChange(aExecutionCap);
11848}
11849
11850/**
11851 * @note Locks this object for reading.
11852 */
11853HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
11854{
11855 LogFlowThisFunc(("\n"));
11856
11857 AutoCaller autoCaller(this);
11858 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11859
11860 ComPtr<IInternalSessionControl> directControl;
11861 {
11862 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11863 directControl = mData->mSession.mDirectControl;
11864 }
11865
11866 /* ignore notifications sent after #OnSessionEnd() is called */
11867 if (!directControl)
11868 return S_OK;
11869
11870 return directControl->OnVRDEServerChange(aRestart);
11871}
11872
11873/**
11874 * @note Locks this object for reading.
11875 */
11876HRESULT SessionMachine::onUSBControllerChange()
11877{
11878 LogFlowThisFunc(("\n"));
11879
11880 AutoCaller autoCaller(this);
11881 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11882
11883 ComPtr<IInternalSessionControl> directControl;
11884 {
11885 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11886 directControl = mData->mSession.mDirectControl;
11887 }
11888
11889 /* ignore notifications sent after #OnSessionEnd() is called */
11890 if (!directControl)
11891 return S_OK;
11892
11893 return directControl->OnUSBControllerChange();
11894}
11895
11896/**
11897 * @note Locks this object for reading.
11898 */
11899HRESULT SessionMachine::onSharedFolderChange()
11900{
11901 LogFlowThisFunc(("\n"));
11902
11903 AutoCaller autoCaller(this);
11904 AssertComRCReturnRC(autoCaller.rc());
11905
11906 ComPtr<IInternalSessionControl> directControl;
11907 {
11908 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11909 directControl = mData->mSession.mDirectControl;
11910 }
11911
11912 /* ignore notifications sent after #OnSessionEnd() is called */
11913 if (!directControl)
11914 return S_OK;
11915
11916 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
11917}
11918
11919/**
11920 * @note Locks this object for reading.
11921 */
11922HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
11923{
11924 LogFlowThisFunc(("\n"));
11925
11926 AutoCaller autoCaller(this);
11927 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
11928
11929 ComPtr<IInternalSessionControl> directControl;
11930 {
11931 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11932 directControl = mData->mSession.mDirectControl;
11933 }
11934
11935 /* ignore notifications sent after #OnSessionEnd() is called */
11936 if (!directControl)
11937 return S_OK;
11938
11939 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
11940}
11941
11942/**
11943 * @note Locks this object for reading.
11944 */
11945HRESULT SessionMachine::onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove)
11946{
11947 LogFlowThisFunc(("\n"));
11948
11949 AutoCaller autoCaller(this);
11950 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11951
11952 ComPtr<IInternalSessionControl> directControl;
11953 {
11954 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11955 directControl = mData->mSession.mDirectControl;
11956 }
11957
11958 /* ignore notifications sent after #OnSessionEnd() is called */
11959 if (!directControl)
11960 return S_OK;
11961
11962 return directControl->OnStorageDeviceChange(aAttachment, aRemove);
11963}
11964
11965/**
11966 * Returns @c true if this machine's USB controller reports it has a matching
11967 * filter for the given USB device and @c false otherwise.
11968 *
11969 * @note Caller must have requested machine read lock.
11970 */
11971bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
11972{
11973 AutoCaller autoCaller(this);
11974 /* silently return if not ready -- this method may be called after the
11975 * direct machine session has been called */
11976 if (!autoCaller.isOk())
11977 return false;
11978
11979
11980#ifdef VBOX_WITH_USB
11981 switch (mData->mMachineState)
11982 {
11983 case MachineState_Starting:
11984 case MachineState_Restoring:
11985 case MachineState_TeleportingIn:
11986 case MachineState_Paused:
11987 case MachineState_Running:
11988 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
11989 * elsewhere... */
11990 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
11991 default: break;
11992 }
11993#else
11994 NOREF(aDevice);
11995 NOREF(aMaskedIfs);
11996#endif
11997 return false;
11998}
11999
12000/**
12001 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12002 */
12003HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
12004 IVirtualBoxErrorInfo *aError,
12005 ULONG aMaskedIfs)
12006{
12007 LogFlowThisFunc(("\n"));
12008
12009 AutoCaller autoCaller(this);
12010
12011 /* This notification may happen after the machine object has been
12012 * uninitialized (the session was closed), so don't assert. */
12013 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12014
12015 ComPtr<IInternalSessionControl> directControl;
12016 {
12017 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12018 directControl = mData->mSession.mDirectControl;
12019 }
12020
12021 /* fail on notifications sent after #OnSessionEnd() is called, it is
12022 * expected by the caller */
12023 if (!directControl)
12024 return E_FAIL;
12025
12026 /* No locks should be held at this point. */
12027 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12028 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12029
12030 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
12031}
12032
12033/**
12034 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12035 */
12036HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
12037 IVirtualBoxErrorInfo *aError)
12038{
12039 LogFlowThisFunc(("\n"));
12040
12041 AutoCaller autoCaller(this);
12042
12043 /* This notification may happen after the machine object has been
12044 * uninitialized (the session was closed), so don't assert. */
12045 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12046
12047 ComPtr<IInternalSessionControl> directControl;
12048 {
12049 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12050 directControl = mData->mSession.mDirectControl;
12051 }
12052
12053 /* fail on notifications sent after #OnSessionEnd() is called, it is
12054 * expected by the caller */
12055 if (!directControl)
12056 return E_FAIL;
12057
12058 /* No locks should be held at this point. */
12059 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12060 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12061
12062 return directControl->OnUSBDeviceDetach(aId, aError);
12063}
12064
12065// protected methods
12066/////////////////////////////////////////////////////////////////////////////
12067
12068/**
12069 * Helper method to finalize saving the state.
12070 *
12071 * @note Must be called from under this object's lock.
12072 *
12073 * @param aRc S_OK if the snapshot has been taken successfully
12074 * @param aErrMsg human readable error message for failure
12075 *
12076 * @note Locks mParent + this objects for writing.
12077 */
12078HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
12079{
12080 LogFlowThisFuncEnter();
12081
12082 AutoCaller autoCaller(this);
12083 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12084
12085 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12086
12087 HRESULT rc = S_OK;
12088
12089 if (SUCCEEDED(aRc))
12090 {
12091 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
12092
12093 /* save all VM settings */
12094 rc = saveSettings(NULL);
12095 // no need to check whether VirtualBox.xml needs saving also since
12096 // we can't have a name change pending at this point
12097 }
12098 else
12099 {
12100 // delete the saved state file (it might have been already created);
12101 // we need not check whether this is shared with a snapshot here because
12102 // we certainly created this saved state file here anew
12103 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
12104 }
12105
12106 /* notify the progress object about operation completion */
12107 Assert(mConsoleTaskData.mProgress);
12108 if (SUCCEEDED(aRc))
12109 mConsoleTaskData.mProgress->notifyComplete(S_OK);
12110 else
12111 {
12112 if (aErrMsg.length())
12113 mConsoleTaskData.mProgress->notifyComplete(aRc,
12114 COM_IIDOF(ISession),
12115 getComponentName(),
12116 aErrMsg.c_str());
12117 else
12118 mConsoleTaskData.mProgress->notifyComplete(aRc);
12119 }
12120
12121 /* clear out the temporary saved state data */
12122 mConsoleTaskData.mLastState = MachineState_Null;
12123 mConsoleTaskData.strStateFilePath.setNull();
12124 mConsoleTaskData.mProgress.setNull();
12125
12126 LogFlowThisFuncLeave();
12127 return rc;
12128}
12129
12130/**
12131 * Deletes the given file if it is no longer in use by either the current machine state
12132 * (if the machine is "saved") or any of the machine's snapshots.
12133 *
12134 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
12135 * but is different for each SnapshotMachine. When calling this, the order of calling this
12136 * function on the one hand and changing that variable OR the snapshots tree on the other hand
12137 * is therefore critical. I know, it's all rather messy.
12138 *
12139 * @param strStateFile
12140 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
12141 */
12142void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
12143 Snapshot *pSnapshotToIgnore)
12144{
12145 // it is safe to delete this saved state file if it is not currently in use by the machine ...
12146 if ( (strStateFile.isNotEmpty())
12147 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
12148 )
12149 // ... and it must also not be shared with other snapshots
12150 if ( !mData->mFirstSnapshot
12151 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
12152 // this checks the SnapshotMachine's state file paths
12153 )
12154 RTFileDelete(strStateFile.c_str());
12155}
12156
12157/**
12158 * Locks the attached media.
12159 *
12160 * All attached hard disks are locked for writing and DVD/floppy are locked for
12161 * reading. Parents of attached hard disks (if any) are locked for reading.
12162 *
12163 * This method also performs accessibility check of all media it locks: if some
12164 * media is inaccessible, the method will return a failure and a bunch of
12165 * extended error info objects per each inaccessible medium.
12166 *
12167 * Note that this method is atomic: if it returns a success, all media are
12168 * locked as described above; on failure no media is locked at all (all
12169 * succeeded individual locks will be undone).
12170 *
12171 * This method is intended to be called when the machine is in Starting or
12172 * Restoring state and asserts otherwise.
12173 *
12174 * The locks made by this method must be undone by calling #unlockMedia() when
12175 * no more needed.
12176 */
12177HRESULT SessionMachine::lockMedia()
12178{
12179 AutoCaller autoCaller(this);
12180 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12181
12182 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12183
12184 AssertReturn( mData->mMachineState == MachineState_Starting
12185 || mData->mMachineState == MachineState_Restoring
12186 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
12187 /* bail out if trying to lock things with already set up locking */
12188 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
12189
12190 clearError();
12191 MultiResult mrc(S_OK);
12192
12193 /* Collect locking information for all medium objects attached to the VM. */
12194 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
12195 it != mMediaData->mAttachments.end();
12196 ++it)
12197 {
12198 MediumAttachment* pAtt = *it;
12199 DeviceType_T devType = pAtt->getType();
12200 Medium *pMedium = pAtt->getMedium();
12201
12202 MediumLockList *pMediumLockList(new MediumLockList());
12203 // There can be attachments without a medium (floppy/dvd), and thus
12204 // it's impossible to create a medium lock list. It still makes sense
12205 // to have the empty medium lock list in the map in case a medium is
12206 // attached later.
12207 if (pMedium != NULL)
12208 {
12209 MediumType_T mediumType = pMedium->getType();
12210 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
12211 || mediumType == MediumType_Shareable;
12212 bool fIsVitalImage = (devType == DeviceType_HardDisk);
12213
12214 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
12215 !fIsReadOnlyLock /* fMediumLockWrite */,
12216 NULL,
12217 *pMediumLockList);
12218 if (FAILED(mrc))
12219 {
12220 delete pMediumLockList;
12221 mData->mSession.mLockedMedia.Clear();
12222 break;
12223 }
12224 }
12225
12226 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
12227 if (FAILED(rc))
12228 {
12229 mData->mSession.mLockedMedia.Clear();
12230 mrc = setError(rc,
12231 tr("Collecting locking information for all attached media failed"));
12232 break;
12233 }
12234 }
12235
12236 if (SUCCEEDED(mrc))
12237 {
12238 /* Now lock all media. If this fails, nothing is locked. */
12239 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12240 if (FAILED(rc))
12241 {
12242 mrc = setError(rc,
12243 tr("Locking of attached media failed"));
12244 }
12245 }
12246
12247 return mrc;
12248}
12249
12250/**
12251 * Undoes the locks made by by #lockMedia().
12252 */
12253void SessionMachine::unlockMedia()
12254{
12255 AutoCaller autoCaller(this);
12256 AssertComRCReturnVoid(autoCaller.rc());
12257
12258 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12259
12260 /* we may be holding important error info on the current thread;
12261 * preserve it */
12262 ErrorInfoKeeper eik;
12263
12264 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12265 AssertComRC(rc);
12266}
12267
12268/**
12269 * Helper to change the machine state (reimplementation).
12270 *
12271 * @note Locks this object for writing.
12272 */
12273HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12274{
12275 LogFlowThisFuncEnter();
12276 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12277
12278 AutoCaller autoCaller(this);
12279 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12280
12281 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12282
12283 MachineState_T oldMachineState = mData->mMachineState;
12284
12285 AssertMsgReturn(oldMachineState != aMachineState,
12286 ("oldMachineState=%s, aMachineState=%s\n",
12287 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12288 E_FAIL);
12289
12290 HRESULT rc = S_OK;
12291
12292 int stsFlags = 0;
12293 bool deleteSavedState = false;
12294
12295 /* detect some state transitions */
12296
12297 if ( ( oldMachineState == MachineState_Saved
12298 && aMachineState == MachineState_Restoring)
12299 || ( ( oldMachineState == MachineState_PoweredOff
12300 || oldMachineState == MachineState_Teleported
12301 || oldMachineState == MachineState_Aborted
12302 )
12303 && ( aMachineState == MachineState_TeleportingIn
12304 || aMachineState == MachineState_Starting
12305 )
12306 )
12307 )
12308 {
12309 /* The EMT thread is about to start */
12310
12311 /* Nothing to do here for now... */
12312
12313 /// @todo NEWMEDIA don't let mDVDDrive and other children
12314 /// change anything when in the Starting/Restoring state
12315 }
12316 else if ( ( oldMachineState == MachineState_Running
12317 || oldMachineState == MachineState_Paused
12318 || oldMachineState == MachineState_Teleporting
12319 || oldMachineState == MachineState_LiveSnapshotting
12320 || oldMachineState == MachineState_Stuck
12321 || oldMachineState == MachineState_Starting
12322 || oldMachineState == MachineState_Stopping
12323 || oldMachineState == MachineState_Saving
12324 || oldMachineState == MachineState_Restoring
12325 || oldMachineState == MachineState_TeleportingPausedVM
12326 || oldMachineState == MachineState_TeleportingIn
12327 )
12328 && ( aMachineState == MachineState_PoweredOff
12329 || aMachineState == MachineState_Saved
12330 || aMachineState == MachineState_Teleported
12331 || aMachineState == MachineState_Aborted
12332 )
12333 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
12334 * snapshot */
12335 && ( mConsoleTaskData.mSnapshot.isNull()
12336 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
12337 )
12338 )
12339 {
12340 /* The EMT thread has just stopped, unlock attached media. Note that as
12341 * opposed to locking that is done from Console, we do unlocking here
12342 * because the VM process may have aborted before having a chance to
12343 * properly unlock all media it locked. */
12344
12345 unlockMedia();
12346 }
12347
12348 if (oldMachineState == MachineState_Restoring)
12349 {
12350 if (aMachineState != MachineState_Saved)
12351 {
12352 /*
12353 * delete the saved state file once the machine has finished
12354 * restoring from it (note that Console sets the state from
12355 * Restoring to Saved if the VM couldn't restore successfully,
12356 * to give the user an ability to fix an error and retry --
12357 * we keep the saved state file in this case)
12358 */
12359 deleteSavedState = true;
12360 }
12361 }
12362 else if ( oldMachineState == MachineState_Saved
12363 && ( aMachineState == MachineState_PoweredOff
12364 || aMachineState == MachineState_Aborted
12365 || aMachineState == MachineState_Teleported
12366 )
12367 )
12368 {
12369 /*
12370 * delete the saved state after Console::ForgetSavedState() is called
12371 * or if the VM process (owning a direct VM session) crashed while the
12372 * VM was Saved
12373 */
12374
12375 /// @todo (dmik)
12376 // Not sure that deleting the saved state file just because of the
12377 // client death before it attempted to restore the VM is a good
12378 // thing. But when it crashes we need to go to the Aborted state
12379 // which cannot have the saved state file associated... The only
12380 // way to fix this is to make the Aborted condition not a VM state
12381 // but a bool flag: i.e., when a crash occurs, set it to true and
12382 // change the state to PoweredOff or Saved depending on the
12383 // saved state presence.
12384
12385 deleteSavedState = true;
12386 mData->mCurrentStateModified = TRUE;
12387 stsFlags |= SaveSTS_CurStateModified;
12388 }
12389
12390 if ( aMachineState == MachineState_Starting
12391 || aMachineState == MachineState_Restoring
12392 || aMachineState == MachineState_TeleportingIn
12393 )
12394 {
12395 /* set the current state modified flag to indicate that the current
12396 * state is no more identical to the state in the
12397 * current snapshot */
12398 if (!mData->mCurrentSnapshot.isNull())
12399 {
12400 mData->mCurrentStateModified = TRUE;
12401 stsFlags |= SaveSTS_CurStateModified;
12402 }
12403 }
12404
12405 if (deleteSavedState)
12406 {
12407 if (mRemoveSavedState)
12408 {
12409 Assert(!mSSData->strStateFilePath.isEmpty());
12410
12411 // it is safe to delete the saved state file if ...
12412 if ( !mData->mFirstSnapshot // ... we have no snapshots or
12413 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
12414 // ... none of the snapshots share the saved state file
12415 )
12416 RTFileDelete(mSSData->strStateFilePath.c_str());
12417 }
12418
12419 mSSData->strStateFilePath.setNull();
12420 stsFlags |= SaveSTS_StateFilePath;
12421 }
12422
12423 /* redirect to the underlying peer machine */
12424 mPeer->setMachineState(aMachineState);
12425
12426 if ( aMachineState == MachineState_PoweredOff
12427 || aMachineState == MachineState_Teleported
12428 || aMachineState == MachineState_Aborted
12429 || aMachineState == MachineState_Saved)
12430 {
12431 /* the machine has stopped execution
12432 * (or the saved state file was adopted) */
12433 stsFlags |= SaveSTS_StateTimeStamp;
12434 }
12435
12436 if ( ( oldMachineState == MachineState_PoweredOff
12437 || oldMachineState == MachineState_Aborted
12438 || oldMachineState == MachineState_Teleported
12439 )
12440 && aMachineState == MachineState_Saved)
12441 {
12442 /* the saved state file was adopted */
12443 Assert(!mSSData->strStateFilePath.isEmpty());
12444 stsFlags |= SaveSTS_StateFilePath;
12445 }
12446
12447#ifdef VBOX_WITH_GUEST_PROPS
12448 if ( aMachineState == MachineState_PoweredOff
12449 || aMachineState == MachineState_Aborted
12450 || aMachineState == MachineState_Teleported)
12451 {
12452 /* Make sure any transient guest properties get removed from the
12453 * property store on shutdown. */
12454
12455 HWData::GuestPropertyList::iterator it;
12456 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
12457 if (!fNeedsSaving)
12458 for (it = mHWData->mGuestProperties.begin();
12459 it != mHWData->mGuestProperties.end(); ++it)
12460 if ( (it->mFlags & guestProp::TRANSIENT)
12461 || (it->mFlags & guestProp::TRANSRESET))
12462 {
12463 fNeedsSaving = true;
12464 break;
12465 }
12466 if (fNeedsSaving)
12467 {
12468 mData->mCurrentStateModified = TRUE;
12469 stsFlags |= SaveSTS_CurStateModified;
12470 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
12471 }
12472 }
12473#endif
12474
12475 rc = saveStateSettings(stsFlags);
12476
12477 if ( ( oldMachineState != MachineState_PoweredOff
12478 && oldMachineState != MachineState_Aborted
12479 && oldMachineState != MachineState_Teleported
12480 )
12481 && ( aMachineState == MachineState_PoweredOff
12482 || aMachineState == MachineState_Aborted
12483 || aMachineState == MachineState_Teleported
12484 )
12485 )
12486 {
12487 /* we've been shut down for any reason */
12488 /* no special action so far */
12489 }
12490
12491 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
12492 LogFlowThisFuncLeave();
12493 return rc;
12494}
12495
12496/**
12497 * Sends the current machine state value to the VM process.
12498 *
12499 * @note Locks this object for reading, then calls a client process.
12500 */
12501HRESULT SessionMachine::updateMachineStateOnClient()
12502{
12503 AutoCaller autoCaller(this);
12504 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12505
12506 ComPtr<IInternalSessionControl> directControl;
12507 {
12508 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12509 AssertReturn(!!mData, E_FAIL);
12510 directControl = mData->mSession.mDirectControl;
12511
12512 /* directControl may be already set to NULL here in #OnSessionEnd()
12513 * called too early by the direct session process while there is still
12514 * some operation (like deleting the snapshot) in progress. The client
12515 * process in this case is waiting inside Session::close() for the
12516 * "end session" process object to complete, while #uninit() called by
12517 * #checkForDeath() on the Watcher thread is waiting for the pending
12518 * operation to complete. For now, we accept this inconsistent behavior
12519 * and simply do nothing here. */
12520
12521 if (mData->mSession.mState == SessionState_Unlocking)
12522 return S_OK;
12523
12524 AssertReturn(!directControl.isNull(), E_FAIL);
12525 }
12526
12527 return directControl->UpdateMachineState(mData->mMachineState);
12528}
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