VirtualBox

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

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

Main: import extra data items on read

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