VirtualBox

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

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

Settings: read the aborted flag

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