VirtualBox

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

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

Main: array size

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