VirtualBox

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

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

Main/metrics: unregister guest after metrics (#5949)

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