VirtualBox

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

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

Main: medias have to delete them self (using the location is wrong: e.g. 2G split); catch more errors

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