VirtualBox

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

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

Main/Machine+MediumAttachment+Console: add method for marking a 'hard disk' as non-rotational, which optimizes performance in modern guest OSes
Frontends/VBoxManage+VirtualBox: support the new method
ChangeLog: add quite a few forgotten improvements and fixes

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

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