VirtualBox

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

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

Main: flags for emulated USB Webcam and CardReader.

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