VirtualBox

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

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

Main: TODO

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