VirtualBox

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

Last change on this file since 38357 was 38357, checked in by vboxsync, 13 years ago

Main: fix NonRational flag survival on snapshot creation (public #9379)

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette