VirtualBox

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

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

Main: Add API to set the discard flag for harddisks

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