VirtualBox

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

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

Main/MediumAttachment+Machine: add a setting which controls the guest-triggered medium eject behavior, fix handling "implicit" media, and corresponding VBoxManage and documentation updates

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