VirtualBox

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

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

FE/Qt4/CLI;Main;Docu: enable MachineAndChildren in clone VM again for ease of testing

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